Debian Codegraph @

imageio/core/request.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 # imageio is distributed under the terms of the (new) BSD License.
3
4 """
5 Definition of the Request object, which acts as a kind of bridge between
6 what the user wants and what the plugins can.
7 """
8
9 import errno
10 import os
11 from io import BytesIO
12 import zipfile
13 import tempfile
14 import shutil
15 import enum
16 import warnings
17
18 from ..core import urlopen, get_remote_file
19
20 from pathlib import Path
21 from urllib.parse import urlparse
22 from typing import Optional
23
24 # URI types
25 URI_BYTES = 1
26 URI_FILE = 2
27 URI_FILENAME = 3
28 URI_ZIPPED = 4
29 URI_HTTP = 5
30 URI_FTP = 6
31
32
33 class IOMode(str, enum.Enum):
34 """Available Image modes
35
36 This is a helper enum for ``Request.Mode`` which is a composite of a
37 ``Request.ImageMode`` and ``Request.IOMode``. The IOMode that tells the
38 plugin if the resource should be read from or written to. Available values are
39
40 - read ("r"): Read from the specified resource
41 - write ("w"): Write to the specified resource
42
43 """
44
45 read = "r"
46 write = "w"
47
48
49 class ImageMode(str, enum.Enum):
50 """Available Image modes
51
52 This is a helper enum for ``Request.Mode`` which is a composite of a
53 ``Request.ImageMode`` and ``Request.IOMode``. The image mode that tells the
54 plugin the desired (and expected) image shape. Available values are
55
56 - single_image ("i"): Return a single image extending in two spatial
57 dimensions
58 - multi_image ("I"): Return a list of images extending in two spatial
59 dimensions
60 - single_volume ("v"): Return an image extending into multiple dimensions.
61 E.g. three spatial dimensions for image stacks, or two spatial and one
62 time dimension for videos
63 - multi_volume ("V"): Return a list of images extending into multiple
64 dimensions.
65 - any_mode ("?"): Return an image in any format (the plugin decides the
66 appropriate action).
67
68 """
69
70 single_image = "i"
71 multi_image = "I"
72 single_volume = "v"
73 multi_volume = "V"
74 any_mode = "?"
75
76
77 @enum.unique
78 class Mode(str, enum.Enum):
79 """The mode to use when interacting with the resource
80
81 ``Request.Mode`` is a composite of ``Request.ImageMode`` and
82 ``Request.IOMode``. The image mode that tells the plugin the desired (and
83 expected) image shape and the ``Request.IOMode`` tells the plugin the way
84 the resource should be interacted with. For a detailed description of the
85 available modes, see the documentation for ``Request.ImageMode`` and
86 ``Request.IOMode`` respectively.
87
88 Available modes are all combinations of ``Request.IOMode`` and ``Request.ImageMode``:
89
90 - read_single_image ("ri")
91 - read_multi_image ("rI")
92 - read_single_volume ("rv")
93 - read_multi_volume ("rV")
94 - read_any ("r?")
95 - write_single_image ("wi")
96 - write_multi_image ("wI")
97 - write_single_volume ("wv")
98 - write_multi_volume ("wV")
99 - write_any ("w?")
100
101 Examples
102 --------
103 >>> Request.Mode("rI") # a list of simple images should be read from the resource
104 >>> Request.Mode("wv") # a single volume should be written to the resource
105
106 """
107
108 read_single_image = "ri"
109 read_multi_image = "rI"
110 read_single_volume = "rv"
111 read_multi_volume = "rV"
112 read_any = "r?"
113 write_single_image = "wi"
114 write_multi_image = "wI"
115 write_single_volume = "wv"
116 write_multi_volume = "wV"
117 write_any = "w?"
118
119 @classmethod
120 def _missing_(cls, value):
121 """Enable Mode("r") and Mode("w")
122
123 The sunder method ``_missing_`` is called whenever the constructor fails
124 to directly look up the corresponding enum value from the given input.
125 In our case, we use it to convert the modes "r" and "w" (from the v3
126 API) into their legacy versions "r?" and "w?".
127
128 More info on _missing_:
129 https://docs.python.org/3/library/enum.html#supported-sunder-names
130 """
131
132 if value == "r":
133 return cls("r?")
134 elif value == "w":
135 return cls("w?")
136 else:
137 raise ValueError(f"{value} is no valid Mode.")
138
139 @property
140 def io_mode(self) -> IOMode:
141 return IOMode(self.value[0])
142
143 @property
144 def image_mode(self) -> ImageMode:
145 return ImageMode(self.value[1])
146
147 def __getitem__(self, key):
148 """For backwards compatibility with the old non-enum modes"""
149 if key == 0:
150 return self.io_mode
151 elif key == 1:
152 return self.image_mode
153 else:
154 raise IndexError(f"Mode has no item {key}")
155
156
157 SPECIAL_READ_URIS = "<video", "<screen>", "<clipboard>"
158
159 # The user can use this string in a write call to get the data back as bytes.
160 RETURN_BYTES = "<bytes>"
161
162 # Example images that will be auto-downloaded
163 EXAMPLE_IMAGES = {
164 "astronaut.png": "Image of the astronaut Eileen Collins",
165 "camera.png": "A grayscale image of a photographer",
166 "checkerboard.png": "Black and white image of a checkerboard",
167 "wood.jpg": "A (repeatable) texture of wooden planks",
168 "bricks.jpg": "A (repeatable) texture of stone bricks",
169 "clock.png": "Photo of a clock with motion blur (Stefan van der Walt)",
170 "coffee.png": "Image of a cup of coffee (Rachel Michetti)",
171 "chelsea.png": "Image of Stefan's cat",
172 "wikkie.png": "Image of Almar's cat",
173 "coins.png": "Image showing greek coins from Pompeii",
174 "horse.png": "Image showing the silhouette of a horse (Andreas Preuss)",
175 "hubble_deep_field.png": "Photograph taken by Hubble telescope (NASA)",
176 "immunohistochemistry.png": "Immunohistochemical (IHC) staining",
177 "moon.png": "Image showing a portion of the surface of the moon",
178 "page.png": "A scanned page of text",
179 "text.png": "A photograph of handdrawn text",
180 "bacterial_colony.tif": "Multi-page TIFF image of a bacterial colony",
181 "calcium_imaging.tif": "Neuronal calcium imaging video",
182 "chelsea.zip": "The chelsea.png in a zipfile (for testing)",
183 "chelsea.bsdf": "The chelsea.png in a BSDF file(for testing)",
184 "newtonscradle.gif": "Animated GIF of a newton's cradle",
185 "cockatoo.mp4": "Video file of a cockatoo",
186 "cockatoo_yuv420.mp4": "Video file of a cockatoo with yuv420 pixel format",
187 "stent.npz": "Volumetric image showing a stented abdominal aorta",
188 "meadow_cube.jpg": "A cubemap image of a meadow, e.g. to render a skybox.",
189 }
190
191
192 class Request(object):
193 """ImageResource handling utility.
194
195 Represents a request for reading or saving an image resource. This
196 object wraps information to that request and acts as an interface
197 for the plugins to several resources; it allows the user to read
198 from filenames, files, http, zipfiles, raw bytes, etc., but offer
199 a simple interface to the plugins via ``get_file()`` and
200 ``get_local_filename()``.
201
202 For each read/write operation a single Request instance is used and passed
203 to the can_read/can_write method of a format, and subsequently to
204 the Reader/Writer class. This allows rudimentary passing of
205 information between different formats and between a format and
206 associated reader/writer.
207
208 Parameters
209 ----------
210 uri : {str, bytes, file}
211 The resource to load the image from.
212 mode : str
213 The first character is "r" or "w", indicating a read or write
214 request. The second character is used to indicate the kind of data:
215 "i" for an image, "I" for multiple images, "v" for a volume,
216 "V" for multiple volumes, "?" for don't care.
217
218 """
219
220 def __init__(self, uri, mode, *, extension=None, format_hint: str = None, **kwargs):
221 # General
222 self.raw_uri = uri
223 self._uri_type = None
224 self._filename = None
225 self._extension = None
226 self._format_hint = None
227 self._kwargs = kwargs
228 self._result = None # Some write actions may have a result
229
230 # To handle the user-side
231 self._filename_zip = None # not None if a zipfile is used
232 self._bytes = None # Incoming bytes
233 self._zipfile = None # To store a zipfile instance (if used)
234
235 # To handle the plugin side
236 self._file = None # To store the file instance
237 self._file_is_local = False # whether the data needs to be copied at end
238 self._filename_local = None # not None if using tempfile on this FS
239 self._firstbytes = None # For easy header parsing
240
241 # To store formats that may be able to fulfil this request
242 # self._potential_formats = []
243
244 # Check mode
245 try:
246 self._mode = Mode(mode)
247 except ValueError:
248 raise ValueError(f"Invalid Request.Mode: {mode}")
249
250 # Parse what was given
251 self._parse_uri(uri)
252
253 # Set extension
254 if extension is not None:
255 if extension[0] != ".":
256 raise ValueError(
257 "`extension` should be a file extension starting with a `.`,"
258 f" but is `{extension}`."
259 )
260 self._extension = extension
261 elif self._filename is not None:
262 if self._uri_type in (URI_FILENAME, URI_ZIPPED):
263 path = self._filename
264 else:
265 path = urlparse(self._filename).path
266 ext = Path(path).suffix.lower()
267 self._extension = ext if ext != "" else None
268
269 if format_hint is not None:
270 warnings.warn(
271 "The usage of `format_hint` is deprecated and will be removed "
272 "in ImageIO v3. Use `extension` instead.",
273 DeprecationWarning,
274 )
275
276 if format_hint is not None and format_hint[0] != ".":
277 raise ValueError(
278 "`format_hint` should be a file extension starting with a `.`,"
279 f" but is `{format_hint}`."
280 )
281
282 self.format_hint = format_hint
283
284 def _parse_uri(self, uri):
285 """Try to figure our what we were given"""
286 is_read_request = self.mode.io_mode is IOMode.read
287 is_write_request = self.mode.io_mode is IOMode.write
288
289 if isinstance(uri, str):
290 # Explicit
291 if uri.startswith("imageio:"):
292 if is_write_request:
293 raise RuntimeError("Cannot write to the standard images.")
294 fn = uri.split(":", 1)[-1].lower()
295 fn, _, zip_part = fn.partition(".zip/")
296 if zip_part:
297 fn += ".zip"
298 if fn not in EXAMPLE_IMAGES:
299 raise ValueError("Unknown standard image %r." % fn)
300 self._uri_type = URI_FILENAME
301 self._filename = get_remote_file("images/" + fn, auto=True)
302 if zip_part:
303 self._filename += "/" + zip_part
304 elif uri.startswith("http://") or uri.startswith("https://"):
305 self._uri_type = URI_HTTP
306 self._filename = uri
307 elif uri.startswith("ftp://") or uri.startswith("ftps://"):
308 self._uri_type = URI_FTP
309 self._filename = uri
310 elif uri.startswith("file://"):
311 self._uri_type = URI_FILENAME
312 self._filename = uri[7:]
313 elif uri.startswith(SPECIAL_READ_URIS) and is_read_request:
314 self._uri_type = URI_BYTES
315 self._filename = uri
316 elif uri.startswith(RETURN_BYTES) and is_write_request:
317 self._uri_type = URI_BYTES
318 self._filename = uri
319 else:
320 self._uri_type = URI_FILENAME
321 self._filename = uri
322
323 elif isinstance(uri, memoryview) and is_read_request:
324 self._uri_type = URI_BYTES
325 self._filename = "<bytes>"
326 self._bytes = uri.tobytes()
327 elif isinstance(uri, bytes) and is_read_request:
328 self._uri_type = URI_BYTES
329 self._filename = "<bytes>"
330 self._bytes = uri
331 elif isinstance(uri, Path):
332 self._uri_type = URI_FILENAME
333 self._filename = str(uri)
334 # Files
335 elif is_read_request:
336 if hasattr(uri, "read") and hasattr(uri, "close"):
337 self._uri_type = URI_FILE
338 self._filename = "<file>"
339 self._file = uri # Data must be read from here
340 elif is_write_request:
341 if hasattr(uri, "write") and hasattr(uri, "close"):
342 self._uri_type = URI_FILE
343 self._filename = "<file>"
344 self._file = uri # Data must be written here
345
346 # Expand user dir
347 if self._uri_type == URI_FILENAME and self._filename.startswith("~"):
348 self._filename = os.path.expanduser(self._filename)
349
350 # Check if a zipfile
351 if self._uri_type == URI_FILENAME:
352 # Search for zip extension followed by a path separator
353 for needle in [".zip/", ".zip\\"]:
354 zip_i = self._filename.lower().find(needle)
355 if zip_i > 0:
356 zip_i += 4
357 zip_path = self._filename[:zip_i]
358 if os.path.isdir(zip_path):
359 pass # is an existing dir (see #548)
360 elif is_write_request or os.path.isfile(zip_path):
361 self._uri_type = URI_ZIPPED
362 self._filename_zip = (
363 zip_path,
364 self._filename[zip_i:].lstrip("/\\"),
365 )
366 break
367
368 # Check if we could read it
369 if self._uri_type is None:
370 uri_r = repr(uri)
371 if len(uri_r) > 60:
372 uri_r = uri_r[:57] + "..."
373 raise IOError("Cannot understand given URI: %s." % uri_r)
374
375 # Check if this is supported
376 noWriting = [URI_HTTP, URI_FTP]
377 if is_write_request and self._uri_type in noWriting:
378 raise IOError("imageio does not support writing to http/ftp.")
379
380 # Deprecated way to load standard images, give a sensible error message
381 if is_read_request and self._uri_type in [URI_FILENAME, URI_ZIPPED]:
382 fn = self._filename
383 if self._filename_zip:
384 fn = self._filename_zip[0]
385 if (not os.path.exists(fn)) and (fn in EXAMPLE_IMAGES):
386 raise IOError(
387 "No such file: %r. This file looks like one of "
388 "the standard images, but from imageio 2.1, "
389 "standard images have to be specified using "
390 '"imageio:%s".' % (fn, fn)
391 )
392
393 # Make filename absolute
394 if self._uri_type in [URI_FILENAME, URI_ZIPPED]:
395 if self._filename_zip:
396 self._filename_zip = (
397 os.path.abspath(self._filename_zip[0]),
398 self._filename_zip[1],
399 )
400 else:
401 self._filename = os.path.abspath(self._filename)
402
403 # Check whether file name is valid
404 if self._uri_type in [URI_FILENAME, URI_ZIPPED]:
405 fn = self._filename
406 if self._filename_zip:
407 fn = self._filename_zip[0]
408 if is_read_request:
409 # Reading: check that the file exists (but is allowed a dir)
410 if not os.path.exists(fn):
411 raise FileNotFoundError(
412 errno.ENOENT, "No such file or directory", fn
413 )
414 else:
415 # Writing: check that the directory to write to does exist
416 dn = os.path.dirname(fn)
417 if not os.path.exists(dn):
418 raise FileNotFoundError(
419 errno.ENOENT, "The directory does not exist", dn
420 )
421
422 @property
423 def filename(self):
424 """Name of the ImageResource.
425
426
427 The uri for which reading/saving was requested. This
428 can be a filename, an http address, or other resource
429 identifier. Do not rely on the filename to obtain the data,
430 but use ``get_file()`` or ``get_local_filename()`` instead.
431 """
432 return self._filename
433
434 @property
435 def extension(self) -> str:
436 """The (lowercase) extension of the requested filename.
437 Suffixes in url's are stripped. Can be None if the request is
438 not based on a filename.
439 """
440 return self._extension
441
442 @property
443 def format_hint(self) -> Optional[str]:
444 return self._format_hint
445
446 @format_hint.setter
447 def format_hint(self, format: str) -> None:
448 self._format_hint = format
449 if self._extension is None:
450 self._extension = format
451
452 @property
453 def mode(self):
454 """The mode of the request. The first character is "r" or "w",
455 indicating a read or write request. The second character is
456 used to indicate the kind of data:
457 "i" for an image, "I" for multiple images, "v" for a volume,
458 "V" for multiple volumes, "?" for don't care.
459 """
460 return self._mode
461
462 @property
463 def kwargs(self):
464 """The dict of keyword arguments supplied by the user."""
465 return self._kwargs
466
467 # For obtaining data
468
469 def get_file(self):
470 """get_file()
471 Get a file object for the resource associated with this request.
472 If this is a reading request, the file is in read mode,
473 otherwise in write mode. This method is not thread safe. Plugins
474 should not close the file when done.
475
476 This is the preferred way to read/write the data. But if a
477 format cannot handle file-like objects, they should use
478 ``get_local_filename()``.
479 """
480 want_to_write = self.mode.io_mode is IOMode.write
481
482 # Is there already a file?
483 # Either _uri_type == URI_FILE, or we already opened the file,
484 # e.g. by using firstbytes
485 if self._file is not None:
486 return self._file
487
488 if self._uri_type == URI_BYTES:
489 if want_to_write:
490 # Create new file object, we catch the bytes in finish()
491 self._file = BytesIO()
492 self._file_is_local = True
493 else:
494 self._file = BytesIO(self._bytes)
495
496 elif self._uri_type == URI_FILENAME:
497 if want_to_write:
498 self._file = open(self.filename, "wb")
499 else:
500 self._file = open(self.filename, "rb")
501
502 elif self._uri_type == URI_ZIPPED:
503 # Get the correct filename
504 filename, name = self._filename_zip
505 if want_to_write:
506 # Create new file object, we catch the bytes in finish()
507 self._file = BytesIO()
508 self._file_is_local = True
509 else:
510 # Open zipfile and open new file object for specific file
511 self._zipfile = zipfile.ZipFile(filename, "r")
512 self._file = self._zipfile.open(name, "r")
513 self._file = SeekableFileObject(self._file)
514
515 elif self._uri_type in [URI_HTTP or URI_FTP]:
516 assert not want_to_write # This should have been tested in init
517 timeout = os.getenv("IMAGEIO_REQUEST_TIMEOUT")
518 if timeout is None or not timeout.isdigit():
519 timeout = 5
520 self._file = urlopen(self.filename, timeout=float(timeout))
521 self._file = SeekableFileObject(self._file)
522
523 return self._file
524
525 def get_local_filename(self):
526 """get_local_filename()
527 If the filename is an existing file on this filesystem, return
528 that. Otherwise a temporary file is created on the local file
529 system which can be used by the format to read from or write to.
530 """
531
532 if self._uri_type == URI_FILENAME:
533 return self._filename
534 else:
535 # Get filename
536 if self.extension is not None:
537 ext = self.extension
538 else:
539 ext = os.path.splitext(self._filename)[1]
540 fd, self._filename_local = tempfile.mkstemp(ext, "imageio_")
541 os.close(fd)
542 # Write stuff to it?
543 if self.mode.io_mode == IOMode.read:
544 with open(self._filename_local, "wb") as file:
545 shutil.copyfileobj(self.get_file(), file)
546 return self._filename_local
547
548 def finish(self) -> None:
549 """Wrap up this request.
550
551 Finishes any pending reads or writes, closes any open files and frees
552 any resources allocated by this request.
553 """
554
555 if self.mode.io_mode == IOMode.write:
556 # See if we "own" the data and must put it somewhere
557 bytes = None
558 if self._filename_local:
559 bytes = Path(self._filename_local).read_bytes()
560 elif self._file_is_local:
561 self._file_is_local = False
562 bytes = self._file.getvalue()
563
564 # Put the data in the right place
565 if bytes is not None:
566 if self._uri_type == URI_BYTES:
567 self._result = bytes # Picked up by imread function
568 elif self._uri_type == URI_FILE:
569 self._file.write(bytes)
570 elif self._uri_type == URI_ZIPPED:
571 zf = zipfile.ZipFile(self._filename_zip[0], "a")
572 zf.writestr(self._filename_zip[1], bytes)
573 zf.close()
574 # elif self._uri_type == URI_FILENAME: -> is always direct
575 # elif self._uri_type == URI_FTP/HTTP: -> write not supported
576
577 # Close open files that we know of (and are responsible for)
578 if self._file and self._uri_type != URI_FILE:
579 self._file.close()
580 self._file = None
581 if self._zipfile:
582 self._zipfile.close()
583 self._zipfile = None
584
585 # Remove temp file
586 if self._filename_local:
587 try:
588 os.remove(self._filename_local)
589 except Exception: # pragma: no cover
590 warnings.warn(
591 "Failed to delete the temporary file at "
592 f"`{self._filename_local}`. Please report this issue."
593 )
594 self._filename_local = None
595
596 # Detach so gc can clean even if a reference of self lingers
597 self._bytes = None
598
599 def get_result(self):
600 """For internal use. In some situations a write action can have
601 a result (bytes data). That is obtained with this function.
602 """
603 # Is there a reason to disallow reading multiple times?
604 self._result, res = None, self._result
605 return res
606
607 @property
608 def firstbytes(self):
609 """The first 256 bytes of the file. These can be used to
610 parse the header to determine the file-format.
611 """
612 if self._firstbytes is None:
613 self._read_first_bytes()
614 return self._firstbytes
615
616 def _read_first_bytes(self, N=256):
617 if self._bytes is not None:
618 self._firstbytes = self._bytes[:N]
619 else:
620 # Prepare
621 try:
622 f = self.get_file()
623 except IOError:
624 if os.path.isdir(self.filename): # A directory, e.g. for DICOM
625 self._firstbytes = bytes()
626 return
627 raise
628 try:
629 i = f.tell()
630 except Exception:
631 i = None
632 # Read
633 self._firstbytes = read_n_bytes(f, N)
634 # Set back
635 try:
636 if i is None:
637 raise Exception("cannot seek with None")
638 f.seek(i)
639 except Exception:
640 # Prevent get_file() from reusing the file
641 self._file = None
642 # If the given URI was a file object, we have a problem,
643 if self._uri_type == URI_FILE:
644 raise IOError("Cannot seek back after getting firstbytes!")
645
646
647 def read_n_bytes(f, N):
648 """read_n_bytes(file, n)
649
650 Read n bytes from the given file, or less if the file has less
651 bytes. Returns zero bytes if the file is closed.
652 """
653 bb = bytes()
654 while len(bb) < N:
655 extra_bytes = f.read(N - len(bb))
656 if not extra_bytes:
657 break
658 bb += extra_bytes
659 return bb
660
661
662 class SeekableFileObject:
663 """A readonly wrapper file object that add support for seeking, even if
664 the wrapped file object does not. The allows us to stream from http and
665 still use Pillow.
666 """
667
668 def __init__(self, f):
669 self.f = f
670 self._i = 0 # >=0 but can exceed buffer
671 self._buffer = b""
672 self._have_all = False
673 self.closed = False
674
675 def read(self, n=None):
676 # Fix up n
677 if n is None:
678 pass
679 else:
680 n = int(n)
681 if n < 0:
682 n = None
683
684 # Can and must we read more?
685 if not self._have_all:
686 more = b""
687 if n is None:
688 more = self.f.read()
689 self._have_all = True
690 else:
691 want_i = self._i + n
692 want_more = want_i - len(self._buffer)
693 if want_more > 0:
694 more = self.f.read(want_more)
695 if len(more) < want_more:
696 self._have_all = True
697 self._buffer += more
698
699 # Read data from buffer and update pointer
700 if n is None:
701 res = self._buffer[self._i :]
702 else:
703 res = self._buffer[self._i : self._i + n]
704 self._i += len(res)
705
706 return res
707
708 def readline(self):
709 yield from self._file.readline()
710
711 def tell(self):
712 return self._i
713
714 def seek(self, i, mode=0):
715 # Mimic BytesIO behavior
716
717 # Get the absolute new position
718 i = int(i)
719 if mode == 0:
720 if i < 0:
721 raise ValueError("negative seek value " + str(i))
722 real_i = i
723 elif mode == 1:
724 real_i = max(0, self._i + i) # negative ok here
725 elif mode == 2:
726 if not self._have_all:
727 self.read()
728 real_i = max(0, len(self._buffer) + i)
729 else:
730 raise ValueError("invalid whence (%s, should be 0, 1 or 2)" % i)
731
732 # Read some?
733 if real_i <= len(self._buffer):
734 pass # no need to read
735 elif not self._have_all:
736 assert real_i > self._i # if we don't have all, _i cannot be > _buffer
737 self.read(real_i - self._i) # sets self._i
738
739 self._i = real_i
740 return self._i
741
742 def close(self):
743 self.closed = True
744 self.f.close()
745
746 def isatty(self):
747 return False
748
749 def seekable(self):
750 return True
751
752
753 class InitializationError(Exception):
754 """The plugin could not initialize from the given request.
755
756 This is a _internal_ error that is raised by plugins that fail to handle
757 a given request. We use this to differentiate incompatibility between
758 a plugin and a request from an actual error/bug inside a plugin.
759
760 """
761
762 pass