ZTWHHH commited on
Commit
91a226a
·
verified ·
1 Parent(s): 85506a2

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. parrot/lib/python3.10/site-packages/imageio/__pycache__/__init__.cpython-310.pyc +0 -0
  2. parrot/lib/python3.10/site-packages/imageio/__pycache__/__main__.cpython-310.pyc +0 -0
  3. parrot/lib/python3.10/site-packages/imageio/__pycache__/freeze.cpython-310.pyc +0 -0
  4. parrot/lib/python3.10/site-packages/imageio/__pycache__/testing.cpython-310.pyc +0 -0
  5. parrot/lib/python3.10/site-packages/imageio/__pycache__/typing.cpython-310.pyc +0 -0
  6. parrot/lib/python3.10/site-packages/imageio/__pycache__/v2.cpython-310.pyc +0 -0
  7. parrot/lib/python3.10/site-packages/imageio/__pycache__/v3.cpython-310.pyc +0 -0
  8. parrot/lib/python3.10/site-packages/imageio/core/__pycache__/__init__.cpython-310.pyc +0 -0
  9. parrot/lib/python3.10/site-packages/imageio/core/__pycache__/fetching.cpython-310.pyc +0 -0
  10. parrot/lib/python3.10/site-packages/imageio/core/__pycache__/findlib.cpython-310.pyc +0 -0
  11. parrot/lib/python3.10/site-packages/imageio/core/__pycache__/format.cpython-310.pyc +0 -0
  12. parrot/lib/python3.10/site-packages/imageio/core/__pycache__/imopen.cpython-310.pyc +0 -0
  13. parrot/lib/python3.10/site-packages/imageio/core/__pycache__/legacy_plugin_wrapper.cpython-310.pyc +0 -0
  14. parrot/lib/python3.10/site-packages/imageio/core/__pycache__/request.cpython-310.pyc +0 -0
  15. parrot/lib/python3.10/site-packages/imageio/core/__pycache__/util.cpython-310.pyc +0 -0
  16. parrot/lib/python3.10/site-packages/imageio/core/__pycache__/v3_plugin_api.cpython-310.pyc +0 -0
  17. parrot/lib/python3.10/site-packages/imageio/core/fetching.py +247 -0
  18. parrot/lib/python3.10/site-packages/imageio/core/format.py +881 -0
  19. parrot/lib/python3.10/site-packages/imageio/core/imopen.py +281 -0
  20. parrot/lib/python3.10/site-packages/imageio/core/legacy_plugin_wrapper.py +363 -0
  21. parrot/lib/python3.10/site-packages/imageio/core/legacy_plugin_wrapper.pyi +27 -0
  22. parrot/lib/python3.10/site-packages/imageio/core/request.py +754 -0
  23. parrot/lib/python3.10/site-packages/imageio/core/request.pyi +90 -0
  24. parrot/lib/python3.10/site-packages/imageio/core/util.py +561 -0
  25. parrot/lib/python3.10/site-packages/imageio/plugins/__pycache__/_dicom.cpython-310.pyc +0 -0
  26. parrot/lib/python3.10/site-packages/imageio/plugins/__pycache__/_swf.cpython-310.pyc +0 -0
  27. parrot/lib/python3.10/site-packages/imageio/plugins/__pycache__/bsdf.cpython-310.pyc +0 -0
  28. parrot/lib/python3.10/site-packages/imageio/plugins/__pycache__/feisem.cpython-310.pyc +0 -0
  29. parrot/lib/python3.10/site-packages/imageio/plugins/__pycache__/fits.cpython-310.pyc +0 -0
  30. parrot/lib/python3.10/site-packages/imageio/plugins/__pycache__/simpleitk.cpython-310.pyc +0 -0
  31. parrot/lib/python3.10/site-packages/markdown_it/__init__.py +5 -0
  32. parrot/lib/python3.10/site-packages/markdown_it/_compat.py +10 -0
  33. parrot/lib/python3.10/site-packages/markdown_it/_punycode.py +66 -0
  34. parrot/lib/python3.10/site-packages/markdown_it/main.py +331 -0
  35. parrot/lib/python3.10/site-packages/markdown_it/parser_block.py +109 -0
  36. parrot/lib/python3.10/site-packages/markdown_it/parser_core.py +32 -0
  37. parrot/lib/python3.10/site-packages/markdown_it/parser_inline.py +124 -0
  38. parrot/lib/python3.10/site-packages/markdown_it/port.yaml +49 -0
  39. parrot/lib/python3.10/site-packages/markdown_it/presets/__init__.py +27 -0
  40. parrot/lib/python3.10/site-packages/markdown_it/presets/__pycache__/default.cpython-310.pyc +0 -0
  41. parrot/lib/python3.10/site-packages/markdown_it/presets/commonmark.py +73 -0
  42. parrot/lib/python3.10/site-packages/markdown_it/presets/default.py +34 -0
  43. parrot/lib/python3.10/site-packages/markdown_it/presets/zero.py +39 -0
  44. parrot/lib/python3.10/site-packages/markdown_it/py.typed +1 -0
  45. parrot/lib/python3.10/site-packages/markdown_it/renderer.py +334 -0
  46. parrot/lib/python3.10/site-packages/markdown_it/ruler.py +237 -0
  47. parrot/lib/python3.10/site-packages/markdown_it/rules_inline/__init__.py +29 -0
  48. parrot/lib/python3.10/site-packages/markdown_it/rules_inline/__pycache__/__init__.cpython-310.pyc +0 -0
  49. parrot/lib/python3.10/site-packages/markdown_it/rules_inline/__pycache__/autolink.cpython-310.pyc +0 -0
  50. parrot/lib/python3.10/site-packages/markdown_it/rules_inline/__pycache__/backticks.cpython-310.pyc +0 -0
parrot/lib/python3.10/site-packages/imageio/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (2.57 kB). View file
 
parrot/lib/python3.10/site-packages/imageio/__pycache__/__main__.cpython-310.pyc ADDED
Binary file (4.2 kB). View file
 
parrot/lib/python3.10/site-packages/imageio/__pycache__/freeze.cpython-310.pyc ADDED
Binary file (472 Bytes). View file
 
parrot/lib/python3.10/site-packages/imageio/__pycache__/testing.cpython-310.pyc ADDED
Binary file (1.55 kB). View file
 
parrot/lib/python3.10/site-packages/imageio/__pycache__/typing.cpython-310.pyc ADDED
Binary file (488 Bytes). View file
 
parrot/lib/python3.10/site-packages/imageio/__pycache__/v2.cpython-310.pyc ADDED
Binary file (20.8 kB). View file
 
parrot/lib/python3.10/site-packages/imageio/__pycache__/v3.cpython-310.pyc ADDED
Binary file (9.02 kB). View file
 
parrot/lib/python3.10/site-packages/imageio/core/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (890 Bytes). View file
 
parrot/lib/python3.10/site-packages/imageio/core/__pycache__/fetching.cpython-310.pyc ADDED
Binary file (6.92 kB). View file
 
parrot/lib/python3.10/site-packages/imageio/core/__pycache__/findlib.cpython-310.pyc ADDED
Binary file (4.07 kB). View file
 
parrot/lib/python3.10/site-packages/imageio/core/__pycache__/format.cpython-310.pyc ADDED
Binary file (29 kB). View file
 
parrot/lib/python3.10/site-packages/imageio/core/__pycache__/imopen.cpython-310.pyc ADDED
Binary file (6.71 kB). View file
 
parrot/lib/python3.10/site-packages/imageio/core/__pycache__/legacy_plugin_wrapper.cpython-310.pyc ADDED
Binary file (10.9 kB). View file
 
parrot/lib/python3.10/site-packages/imageio/core/__pycache__/request.cpython-310.pyc ADDED
Binary file (20.1 kB). View file
 
parrot/lib/python3.10/site-packages/imageio/core/__pycache__/util.cpython-310.pyc ADDED
Binary file (16.3 kB). View file
 
parrot/lib/python3.10/site-packages/imageio/core/__pycache__/v3_plugin_api.cpython-310.pyc ADDED
Binary file (16.8 kB). View file
 
parrot/lib/python3.10/site-packages/imageio/core/fetching.py ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Based on code from the vispy project
3
+ # Distributed under the (new) BSD License. See LICENSE.txt for more info.
4
+
5
+ """Data downloading and reading functions
6
+ """
7
+
8
+ from math import log
9
+ import os
10
+ from os import path as op
11
+ import sys
12
+ import shutil
13
+ import time
14
+
15
+ from . import appdata_dir, resource_dirs
16
+ from . import StdoutProgressIndicator, urlopen
17
+
18
+
19
+ class InternetNotAllowedError(IOError):
20
+ """Plugins that need resources can just use get_remote_file(), but
21
+ should catch this error and silently ignore it.
22
+ """
23
+
24
+ pass
25
+
26
+
27
+ class NeedDownloadError(IOError):
28
+ """Is raised when a remote file is requested that is not locally
29
+ available, but which needs to be explicitly downloaded by the user.
30
+ """
31
+
32
+
33
+ def get_remote_file(fname, directory=None, force_download=False, auto=True):
34
+ """Get a the filename for the local version of a file from the web
35
+
36
+ Parameters
37
+ ----------
38
+ fname : str
39
+ The relative filename on the remote data repository to download.
40
+ These correspond to paths on
41
+ ``https://github.com/imageio/imageio-binaries/``.
42
+ directory : str | None
43
+ The directory where the file will be cached if a download was
44
+ required to obtain the file. By default, the appdata directory
45
+ is used. This is also the first directory that is checked for
46
+ a local version of the file. If the directory does not exist,
47
+ it will be created.
48
+ force_download : bool | str
49
+ If True, the file will be downloaded even if a local copy exists
50
+ (and this copy will be overwritten). Can also be a YYYY-MM-DD date
51
+ to ensure a file is up-to-date (modified date of a file on disk,
52
+ if present, is checked).
53
+ auto : bool
54
+ Whether to auto-download the file if its not present locally. Default
55
+ True. If False and a download is needed, raises NeedDownloadError.
56
+
57
+ Returns
58
+ -------
59
+ fname : str
60
+ The path to the file on the local system.
61
+ """
62
+ _url_root = "https://github.com/imageio/imageio-binaries/raw/master/"
63
+ url = _url_root + fname
64
+ nfname = op.normcase(fname) # convert to native
65
+ # Get dirs to look for the resource
66
+ given_directory = directory
67
+ directory = given_directory or appdata_dir("imageio")
68
+ dirs = resource_dirs()
69
+ dirs.insert(0, directory) # Given dir has preference
70
+ # Try to find the resource locally
71
+ for dir in dirs:
72
+ filename = op.join(dir, nfname)
73
+ if op.isfile(filename):
74
+ if not force_download: # we're done
75
+ if given_directory and given_directory != dir:
76
+ filename2 = os.path.join(given_directory, nfname)
77
+ # Make sure the output directory exists
78
+ if not op.isdir(op.dirname(filename2)):
79
+ os.makedirs(op.abspath(op.dirname(filename2)))
80
+ shutil.copy(filename, filename2)
81
+ return filename2
82
+ return filename
83
+ if isinstance(force_download, str):
84
+ ntime = time.strptime(force_download, "%Y-%m-%d")
85
+ ftime = time.gmtime(op.getctime(filename))
86
+ if ftime >= ntime:
87
+ if given_directory and given_directory != dir:
88
+ filename2 = os.path.join(given_directory, nfname)
89
+ # Make sure the output directory exists
90
+ if not op.isdir(op.dirname(filename2)):
91
+ os.makedirs(op.abspath(op.dirname(filename2)))
92
+ shutil.copy(filename, filename2)
93
+ return filename2
94
+ return filename
95
+ else:
96
+ print("File older than %s, updating..." % force_download)
97
+ break
98
+
99
+ # If we get here, we're going to try to download the file
100
+ if os.getenv("IMAGEIO_NO_INTERNET", "").lower() in ("1", "true", "yes"):
101
+ raise InternetNotAllowedError(
102
+ "Will not download resource from the "
103
+ "internet because environment variable "
104
+ "IMAGEIO_NO_INTERNET is set."
105
+ )
106
+
107
+ # Can we proceed with auto-download?
108
+ if not auto:
109
+ raise NeedDownloadError()
110
+
111
+ # Get filename to store to and make sure the dir exists
112
+ filename = op.join(directory, nfname)
113
+ if not op.isdir(op.dirname(filename)):
114
+ os.makedirs(op.abspath(op.dirname(filename)))
115
+ # let's go get the file
116
+ if os.getenv("CONTINUOUS_INTEGRATION", False): # pragma: no cover
117
+ # On CI, we retry a few times ...
118
+ for i in range(2):
119
+ try:
120
+ _fetch_file(url, filename)
121
+ return filename
122
+ except IOError:
123
+ time.sleep(0.5)
124
+ else:
125
+ _fetch_file(url, filename)
126
+ return filename
127
+ else: # pragma: no cover
128
+ _fetch_file(url, filename)
129
+ return filename
130
+
131
+
132
+ def _fetch_file(url, file_name, print_destination=True):
133
+ """Load requested file, downloading it if needed or requested
134
+
135
+ Parameters
136
+ ----------
137
+ url: string
138
+ The url of file to be downloaded.
139
+ file_name: string
140
+ Name, along with the path, of where downloaded file will be saved.
141
+ print_destination: bool, optional
142
+ If true, destination of where file was saved will be printed after
143
+ download finishes.
144
+ resume: bool, optional
145
+ If true, try to resume partially downloaded files.
146
+ """
147
+ # Adapted from NISL:
148
+ # https://github.com/nisl/tutorial/blob/master/nisl/datasets.py
149
+
150
+ print(
151
+ "Imageio: %r was not found on your computer; "
152
+ "downloading it now." % os.path.basename(file_name)
153
+ )
154
+
155
+ temp_file_name = file_name + ".part"
156
+ local_file = None
157
+ initial_size = 0
158
+ errors = []
159
+ for tries in range(4):
160
+ try:
161
+ # Checking file size and displaying it alongside the download url
162
+ remote_file = urlopen(url, timeout=5.0)
163
+ file_size = int(remote_file.headers["Content-Length"].strip())
164
+ size_str = _sizeof_fmt(file_size)
165
+ print("Try %i. Download from %s (%s)" % (tries + 1, url, size_str))
166
+ # Downloading data (can be extended to resume if need be)
167
+ local_file = open(temp_file_name, "wb")
168
+ _chunk_read(remote_file, local_file, initial_size=initial_size)
169
+ # temp file must be closed prior to the move
170
+ if not local_file.closed:
171
+ local_file.close()
172
+ shutil.move(temp_file_name, file_name)
173
+ if print_destination is True:
174
+ sys.stdout.write("File saved as %s.\n" % file_name)
175
+ break
176
+ except Exception as e:
177
+ errors.append(e)
178
+ print("Error while fetching file: %s." % str(e))
179
+ finally:
180
+ if local_file is not None:
181
+ if not local_file.closed:
182
+ local_file.close()
183
+ else:
184
+ raise IOError(
185
+ "Unable to download %r. Perhaps there is no internet "
186
+ "connection? If there is, please report this problem."
187
+ % os.path.basename(file_name)
188
+ )
189
+
190
+
191
+ def _chunk_read(response, local_file, chunk_size=8192, initial_size=0):
192
+ """Download a file chunk by chunk and show advancement
193
+
194
+ Can also be used when resuming downloads over http.
195
+
196
+ Parameters
197
+ ----------
198
+ response: urllib.response.addinfourl
199
+ Response to the download request in order to get file size.
200
+ local_file: file
201
+ Hard disk file where data should be written.
202
+ chunk_size: integer, optional
203
+ Size of downloaded chunks. Default: 8192
204
+ initial_size: int, optional
205
+ If resuming, indicate the initial size of the file.
206
+ """
207
+ # Adapted from NISL:
208
+ # https://github.com/nisl/tutorial/blob/master/nisl/datasets.py
209
+
210
+ bytes_so_far = initial_size
211
+ # Returns only amount left to download when resuming, not the size of the
212
+ # entire file
213
+ total_size = int(response.headers["Content-Length"].strip())
214
+ total_size += initial_size
215
+
216
+ progress = StdoutProgressIndicator("Downloading")
217
+ progress.start("", "bytes", total_size)
218
+
219
+ while True:
220
+ chunk = response.read(chunk_size)
221
+ bytes_so_far += len(chunk)
222
+ if not chunk:
223
+ break
224
+ _chunk_write(chunk, local_file, progress)
225
+ progress.finish("Done")
226
+
227
+
228
+ def _chunk_write(chunk, local_file, progress):
229
+ """Write a chunk to file and update the progress bar"""
230
+ local_file.write(chunk)
231
+ progress.increase_progress(len(chunk))
232
+ time.sleep(0) # Give other threads a chance, e.g. those that handle stdout pipes
233
+
234
+
235
+ def _sizeof_fmt(num):
236
+ """Turn number of bytes into human-readable str"""
237
+ units = ["bytes", "kB", "MB", "GB", "TB", "PB"]
238
+ decimals = [0, 0, 1, 2, 2, 2]
239
+ """Human friendly file size"""
240
+ if num > 1:
241
+ exponent = min(int(log(num, 1024)), len(units) - 1)
242
+ quotient = float(num) / 1024**exponent
243
+ unit = units[exponent]
244
+ num_decimals = decimals[exponent]
245
+ format_string = "{0:.%sf} {1}" % num_decimals
246
+ return format_string.format(quotient, unit)
247
+ return "0 bytes" if num == 0 else "1 byte"
parrot/lib/python3.10/site-packages/imageio/core/format.py ADDED
@@ -0,0 +1,881 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # imageio is distributed under the terms of the (new) BSD License.
3
+
4
+ """
5
+
6
+ .. note::
7
+ imageio is under construction, some details with regard to the
8
+ Reader and Writer classes may change.
9
+
10
+ These are the main classes of imageio. They expose an interface for
11
+ advanced users and plugin developers. A brief overview:
12
+
13
+ * imageio.FormatManager - for keeping track of registered formats.
14
+ * imageio.Format - representation of a file format reader/writer
15
+ * imageio.Format.Reader - object used during the reading of a file.
16
+ * imageio.Format.Writer - object used during saving a file.
17
+ * imageio.Request - used to store the filename and other info.
18
+
19
+ Plugins need to implement a Format class and register
20
+ a format object using ``imageio.formats.add_format()``.
21
+
22
+ """
23
+
24
+ # todo: do we even use the known extensions?
25
+
26
+ # Some notes:
27
+ #
28
+ # The classes in this module use the Request object to pass filename and
29
+ # related info around. This request object is instantiated in
30
+ # imageio.get_reader and imageio.get_writer.
31
+
32
+ import sys
33
+ import warnings
34
+ import contextlib
35
+
36
+ import numpy as np
37
+ from pathlib import Path
38
+
39
+ from . import Array, asarray
40
+ from .request import ImageMode
41
+ from ..config import known_plugins, known_extensions, PluginConfig, FileExtension
42
+ from ..config.plugins import _original_order
43
+ from .imopen import imopen
44
+
45
+
46
+ # survived for backwards compatibility
47
+ # I don't know if external plugin code depends on it existing
48
+ # We no longer do
49
+ MODENAMES = ImageMode
50
+
51
+
52
+ def _get_config(plugin):
53
+ """Old Plugin resolution logic.
54
+
55
+ Remove once we remove the old format manager.
56
+ """
57
+
58
+ extension_name = None
59
+
60
+ if Path(plugin).suffix.lower() in known_extensions:
61
+ extension_name = Path(plugin).suffix.lower()
62
+ elif plugin in known_plugins:
63
+ pass
64
+ elif plugin.lower() in known_extensions:
65
+ extension_name = plugin.lower()
66
+ elif "." + plugin.lower() in known_extensions:
67
+ extension_name = "." + plugin.lower()
68
+ else:
69
+ raise IndexError(f"No format known by name `{plugin}`.")
70
+
71
+ if extension_name is not None:
72
+ for plugin_name in [
73
+ x
74
+ for file_extension in known_extensions[extension_name]
75
+ for x in file_extension.priority
76
+ ]:
77
+ if known_plugins[plugin_name].is_legacy:
78
+ plugin = plugin_name
79
+ break
80
+
81
+ return known_plugins[plugin]
82
+
83
+
84
+ class Format(object):
85
+ """Represents an implementation to read/write a particular file format
86
+
87
+ A format instance is responsible for 1) providing information about
88
+ a format; 2) determining whether a certain file can be read/written
89
+ with this format; 3) providing a reader/writer class.
90
+
91
+ Generally, imageio will select the right format and use that to
92
+ read/write an image. A format can also be explicitly chosen in all
93
+ read/write functions. Use ``print(format)``, or ``help(format_name)``
94
+ to see its documentation.
95
+
96
+ To implement a specific format, one should create a subclass of
97
+ Format and the Format.Reader and Format.Writer classes. See
98
+ :class:`imageio.plugins` for details.
99
+
100
+ Parameters
101
+ ----------
102
+ name : str
103
+ A short name of this format. Users can select a format using its name.
104
+ description : str
105
+ A one-line description of the format.
106
+ extensions : str | list | None
107
+ List of filename extensions that this format supports. If a
108
+ string is passed it should be space or comma separated. The
109
+ extensions are used in the documentation and to allow users to
110
+ select a format by file extension. It is not used to determine
111
+ what format to use for reading/saving a file.
112
+ modes : str
113
+ A string containing the modes that this format can handle ('iIvV'),
114
+ “i” for an image, “I” for multiple images, “v” for a volume,
115
+ “V” for multiple volumes.
116
+ This attribute is used in the documentation and to select the
117
+ formats when reading/saving a file.
118
+ """
119
+
120
+ def __init__(self, name, description, extensions=None, modes=None):
121
+ """Initialize the Plugin.
122
+
123
+ Parameters
124
+ ----------
125
+ name : str
126
+ A short name of this format. Users can select a format using its name.
127
+ description : str
128
+ A one-line description of the format.
129
+ extensions : str | list | None
130
+ List of filename extensions that this format supports. If a
131
+ string is passed it should be space or comma separated. The
132
+ extensions are used in the documentation and to allow users to
133
+ select a format by file extension. It is not used to determine
134
+ what format to use for reading/saving a file.
135
+ modes : str
136
+ A string containing the modes that this format can handle ('iIvV'),
137
+ “i” for an image, “I” for multiple images, “v” for a volume,
138
+ “V” for multiple volumes.
139
+ This attribute is used in the documentation and to select the
140
+ formats when reading/saving a file.
141
+ """
142
+
143
+ # Store name and description
144
+ self._name = name.upper()
145
+ self._description = description
146
+
147
+ # Store extensions, do some effort to normalize them.
148
+ # They are stored as a list of lowercase strings without leading dots.
149
+ if extensions is None:
150
+ extensions = []
151
+ elif isinstance(extensions, str):
152
+ extensions = extensions.replace(",", " ").split(" ")
153
+ #
154
+ if isinstance(extensions, (tuple, list)):
155
+ self._extensions = tuple(
156
+ ["." + e.strip(".").lower() for e in extensions if e]
157
+ )
158
+ else:
159
+ raise ValueError("Invalid value for extensions given.")
160
+
161
+ # Store mode
162
+ self._modes = modes or ""
163
+ if not isinstance(self._modes, str):
164
+ raise ValueError("Invalid value for modes given.")
165
+ for m in self._modes:
166
+ if m not in "iIvV?":
167
+ raise ValueError("Invalid value for mode given.")
168
+
169
+ def __repr__(self):
170
+ # Short description
171
+ return "<Format %s - %s>" % (self.name, self.description)
172
+
173
+ def __str__(self):
174
+ return self.doc
175
+
176
+ @property
177
+ def doc(self):
178
+ """The documentation for this format (name + description + docstring)."""
179
+ # Our docsring is assumed to be indented by four spaces. The
180
+ # first line needs special attention.
181
+ return "%s - %s\n\n %s\n" % (
182
+ self.name,
183
+ self.description,
184
+ self.__doc__.strip(),
185
+ )
186
+
187
+ @property
188
+ def name(self):
189
+ """The name of this format."""
190
+ return self._name
191
+
192
+ @property
193
+ def description(self):
194
+ """A short description of this format."""
195
+ return self._description
196
+
197
+ @property
198
+ def extensions(self):
199
+ """A list of file extensions supported by this plugin.
200
+ These are all lowercase with a leading dot.
201
+ """
202
+ return self._extensions
203
+
204
+ @property
205
+ def modes(self):
206
+ """A string specifying the modes that this format can handle."""
207
+ return self._modes
208
+
209
+ def get_reader(self, request):
210
+ """get_reader(request)
211
+
212
+ Return a reader object that can be used to read data and info
213
+ from the given file. Users are encouraged to use
214
+ imageio.get_reader() instead.
215
+ """
216
+ select_mode = request.mode[1] if request.mode[1] in "iIvV" else ""
217
+ if select_mode not in self.modes:
218
+ raise RuntimeError(
219
+ f"Format {self.name} cannot read in {request.mode.image_mode} mode"
220
+ )
221
+ return self.Reader(self, request)
222
+
223
+ def get_writer(self, request):
224
+ """get_writer(request)
225
+
226
+ Return a writer object that can be used to write data and info
227
+ to the given file. Users are encouraged to use
228
+ imageio.get_writer() instead.
229
+ """
230
+ select_mode = request.mode[1] if request.mode[1] in "iIvV" else ""
231
+ if select_mode not in self.modes:
232
+ raise RuntimeError(
233
+ f"Format {self.name} cannot write in {request.mode.image_mode} mode"
234
+ )
235
+ return self.Writer(self, request)
236
+
237
+ def can_read(self, request):
238
+ """can_read(request)
239
+
240
+ Get whether this format can read data from the specified uri.
241
+ """
242
+ return self._can_read(request)
243
+
244
+ def can_write(self, request):
245
+ """can_write(request)
246
+
247
+ Get whether this format can write data to the speciefed uri.
248
+ """
249
+ return self._can_write(request)
250
+
251
+ def _can_read(self, request): # pragma: no cover
252
+ """Check if Plugin can read from ImageResource.
253
+
254
+ This method is called when the format manager is searching for a format
255
+ to read a certain image. Return True if this format can do it.
256
+
257
+ The format manager is aware of the extensions and the modes that each
258
+ format can handle. It will first ask all formats that *seem* to be able
259
+ to read it whether they can. If none can, it will ask the remaining
260
+ formats if they can: the extension might be missing, and this allows
261
+ formats to provide functionality for certain extensions, while giving
262
+ preference to other plugins.
263
+
264
+ If a format says it can, it should live up to it. The format would
265
+ ideally check the request.firstbytes and look for a header of some kind.
266
+
267
+ Parameters
268
+ ----------
269
+ request : Request
270
+ A request that can be used to access the ImageResource and obtain
271
+ metadata about it.
272
+
273
+ Returns
274
+ -------
275
+ can_read : bool
276
+ True if the plugin can read from the ImageResource, False otherwise.
277
+
278
+ """
279
+ return None # Plugins must implement this
280
+
281
+ def _can_write(self, request): # pragma: no cover
282
+ """Check if Plugin can write to ImageResource.
283
+
284
+ Parameters
285
+ ----------
286
+ request : Request
287
+ A request that can be used to access the ImageResource and obtain
288
+ metadata about it.
289
+
290
+ Returns
291
+ -------
292
+ can_read : bool
293
+ True if the plugin can write to the ImageResource, False otherwise.
294
+
295
+ """
296
+ return None # Plugins must implement this
297
+
298
+ # -----
299
+
300
+ class _BaseReaderWriter(object):
301
+ """Base class for the Reader and Writer class to implement common
302
+ functionality. It implements a similar approach for opening/closing
303
+ and context management as Python's file objects.
304
+ """
305
+
306
+ def __init__(self, format, request):
307
+ self.__closed = False
308
+ self._BaseReaderWriter_last_index = -1
309
+ self._format = format
310
+ self._request = request
311
+ # Open the reader/writer
312
+ self._open(**self.request.kwargs.copy())
313
+
314
+ @property
315
+ def format(self):
316
+ """The :class:`.Format` object corresponding to the current
317
+ read/write operation.
318
+ """
319
+ return self._format
320
+
321
+ @property
322
+ def request(self):
323
+ """The :class:`.Request` object corresponding to the
324
+ current read/write operation.
325
+ """
326
+ return self._request
327
+
328
+ def __enter__(self):
329
+ self._checkClosed()
330
+ return self
331
+
332
+ def __exit__(self, type, value, traceback):
333
+ if value is None:
334
+ # Otherwise error in close hide the real error.
335
+ self.close()
336
+
337
+ def __del__(self):
338
+ try:
339
+ self.close()
340
+ except Exception: # pragma: no cover
341
+ pass # Suppress noise when called during interpreter shutdown
342
+
343
+ def close(self):
344
+ """Flush and close the reader/writer.
345
+ This method has no effect if it is already closed.
346
+ """
347
+ if self.__closed:
348
+ return
349
+ self.__closed = True
350
+ self._close()
351
+ # Process results and clean request object
352
+ self.request.finish()
353
+
354
+ @property
355
+ def closed(self):
356
+ """Whether the reader/writer is closed."""
357
+ return self.__closed
358
+
359
+ def _checkClosed(self, msg=None):
360
+ """Internal: raise an ValueError if reader/writer is closed"""
361
+ if self.closed:
362
+ what = self.__class__.__name__
363
+ msg = msg or ("I/O operation on closed %s." % what)
364
+ raise RuntimeError(msg)
365
+
366
+ # To implement
367
+
368
+ def _open(self, **kwargs):
369
+ """_open(**kwargs)
370
+
371
+ Plugins should probably implement this.
372
+
373
+ It is called when reader/writer is created. Here the
374
+ plugin can do its initialization. The given keyword arguments
375
+ are those that were given by the user at imageio.read() or
376
+ imageio.write().
377
+ """
378
+ raise NotImplementedError()
379
+
380
+ def _close(self):
381
+ """_close()
382
+
383
+ Plugins should probably implement this.
384
+
385
+ It is called when the reader/writer is closed. Here the plugin
386
+ can do a cleanup, flush, etc.
387
+
388
+ """
389
+ raise NotImplementedError()
390
+
391
+ # -----
392
+
393
+ class Reader(_BaseReaderWriter):
394
+ """
395
+ The purpose of a reader object is to read data from an image
396
+ resource, and should be obtained by calling :func:`.get_reader`.
397
+
398
+ A reader can be used as an iterator to read multiple images,
399
+ and (if the format permits) only reads data from the file when
400
+ new data is requested (i.e. streaming). A reader can also be
401
+ used as a context manager so that it is automatically closed.
402
+
403
+ Plugins implement Reader's for different formats. Though rare,
404
+ plugins may provide additional functionality (beyond what is
405
+ provided by the base reader class).
406
+ """
407
+
408
+ def get_length(self):
409
+ """get_length()
410
+
411
+ Get the number of images in the file. (Note: you can also
412
+ use ``len(reader_object)``.)
413
+
414
+ The result can be:
415
+ * 0 for files that only have meta data
416
+ * 1 for singleton images (e.g. in PNG, JPEG, etc.)
417
+ * N for image series
418
+ * inf for streams (series of unknown length)
419
+ """
420
+ return self._get_length()
421
+
422
+ def get_data(self, index, **kwargs):
423
+ """get_data(index, **kwargs)
424
+
425
+ Read image data from the file, using the image index. The
426
+ returned image has a 'meta' attribute with the meta data.
427
+ Raises IndexError if the index is out of range.
428
+
429
+ Some formats may support additional keyword arguments. These are
430
+ listed in the documentation of those formats.
431
+ """
432
+ self._checkClosed()
433
+ self._BaseReaderWriter_last_index = index
434
+ try:
435
+ im, meta = self._get_data(index, **kwargs)
436
+ except StopIteration:
437
+ raise IndexError(index)
438
+ return Array(im, meta) # Array tests im and meta
439
+
440
+ def get_next_data(self, **kwargs):
441
+ """get_next_data(**kwargs)
442
+
443
+ Read the next image from the series.
444
+
445
+ Some formats may support additional keyword arguments. These are
446
+ listed in the documentation of those formats.
447
+ """
448
+ return self.get_data(self._BaseReaderWriter_last_index + 1, **kwargs)
449
+
450
+ def set_image_index(self, index, **kwargs):
451
+ """set_image_index(index)
452
+
453
+ Set the internal pointer such that the next call to
454
+ get_next_data() returns the image specified by the index
455
+ """
456
+ self._checkClosed()
457
+ n = self.get_length()
458
+ self._BaseReaderWriter_last_index = min(max(index - 1, -1), n)
459
+
460
+ def get_meta_data(self, index=None):
461
+ """get_meta_data(index=None)
462
+
463
+ Read meta data from the file. using the image index. If the
464
+ index is omitted or None, return the file's (global) meta data.
465
+
466
+ Note that ``get_data`` also provides the meta data for the returned
467
+ image as an attribute of that image.
468
+
469
+ The meta data is a dict, which shape depends on the format.
470
+ E.g. for JPEG, the dict maps group names to subdicts and each
471
+ group is a dict with name-value pairs. The groups represent
472
+ the different metadata formats (EXIF, XMP, etc.).
473
+ """
474
+ self._checkClosed()
475
+ meta = self._get_meta_data(index)
476
+ if not isinstance(meta, dict):
477
+ raise ValueError(
478
+ "Meta data must be a dict, not %r" % meta.__class__.__name__
479
+ )
480
+ return meta
481
+
482
+ def iter_data(self):
483
+ """iter_data()
484
+
485
+ Iterate over all images in the series. (Note: you can also
486
+ iterate over the reader object.)
487
+
488
+ """
489
+ self._checkClosed()
490
+ n = self.get_length()
491
+ i = 0
492
+ while i < n:
493
+ try:
494
+ im, meta = self._get_data(i)
495
+ except StopIteration:
496
+ return
497
+ except IndexError:
498
+ if n == float("inf"):
499
+ return
500
+ raise
501
+ yield Array(im, meta)
502
+ i += 1
503
+
504
+ # Compatibility
505
+
506
+ def __iter__(self):
507
+ return self.iter_data()
508
+
509
+ def __len__(self):
510
+ n = self.get_length()
511
+ if n == float("inf"):
512
+ n = sys.maxsize
513
+ return n
514
+
515
+ # To implement
516
+
517
+ def _get_length(self):
518
+ """_get_length()
519
+
520
+ Plugins must implement this.
521
+
522
+ The returned scalar specifies the number of images in the series.
523
+ See Reader.get_length for more information.
524
+ """
525
+ raise NotImplementedError()
526
+
527
+ def _get_data(self, index):
528
+ """_get_data()
529
+
530
+ Plugins must implement this, but may raise an IndexError in
531
+ case the plugin does not support random access.
532
+
533
+ It should return the image and meta data: (ndarray, dict).
534
+ """
535
+ raise NotImplementedError()
536
+
537
+ def _get_meta_data(self, index):
538
+ """_get_meta_data(index)
539
+
540
+ Plugins must implement this.
541
+
542
+ It should return the meta data as a dict, corresponding to the
543
+ given index, or to the file's (global) meta data if index is
544
+ None.
545
+ """
546
+ raise NotImplementedError()
547
+
548
+ # -----
549
+
550
+ class Writer(_BaseReaderWriter):
551
+ """
552
+ The purpose of a writer object is to write data to an image
553
+ resource, and should be obtained by calling :func:`.get_writer`.
554
+
555
+ A writer will (if the format permits) write data to the file
556
+ as soon as new data is provided (i.e. streaming). A writer can
557
+ also be used as a context manager so that it is automatically
558
+ closed.
559
+
560
+ Plugins implement Writer's for different formats. Though rare,
561
+ plugins may provide additional functionality (beyond what is
562
+ provided by the base writer class).
563
+ """
564
+
565
+ def append_data(self, im, meta=None):
566
+ """append_data(im, meta={})
567
+
568
+ Append an image (and meta data) to the file. The final meta
569
+ data that is used consists of the meta data on the given
570
+ image (if applicable), updated with the given meta data.
571
+ """
572
+ self._checkClosed()
573
+ # Check image data
574
+ if not isinstance(im, np.ndarray):
575
+ raise ValueError("append_data requires ndarray as first arg")
576
+ # Get total meta dict
577
+ total_meta = {}
578
+ if hasattr(im, "meta") and isinstance(im.meta, dict):
579
+ total_meta.update(im.meta)
580
+ if meta is None:
581
+ pass
582
+ elif not isinstance(meta, dict):
583
+ raise ValueError("Meta must be a dict.")
584
+ else:
585
+ total_meta.update(meta)
586
+
587
+ # Decouple meta info
588
+ im = asarray(im)
589
+ # Call
590
+ return self._append_data(im, total_meta)
591
+
592
+ def set_meta_data(self, meta):
593
+ """set_meta_data(meta)
594
+
595
+ Sets the file's (global) meta data. The meta data is a dict which
596
+ shape depends on the format. E.g. for JPEG the dict maps
597
+ group names to subdicts, and each group is a dict with
598
+ name-value pairs. The groups represents the different
599
+ metadata formats (EXIF, XMP, etc.).
600
+
601
+ Note that some meta formats may not be supported for
602
+ writing, and individual fields may be ignored without
603
+ warning if they are invalid.
604
+ """
605
+ self._checkClosed()
606
+ if not isinstance(meta, dict):
607
+ raise ValueError("Meta must be a dict.")
608
+ else:
609
+ return self._set_meta_data(meta)
610
+
611
+ # To implement
612
+
613
+ def _append_data(self, im, meta):
614
+ # Plugins must implement this
615
+ raise NotImplementedError()
616
+
617
+ def _set_meta_data(self, meta):
618
+ # Plugins must implement this
619
+ raise NotImplementedError()
620
+
621
+
622
+ class FormatManager(object):
623
+ """
624
+ The FormatManager is a singleton plugin factory.
625
+
626
+ The format manager supports getting a format object using indexing (by
627
+ format name or extension). When used as an iterator, this object
628
+ yields all registered format objects.
629
+
630
+ See also :func:`.help`.
631
+ """
632
+
633
+ @property
634
+ def _formats(self):
635
+ available_formats = list()
636
+
637
+ for config in known_plugins.values():
638
+ with contextlib.suppress(ImportError):
639
+ # if an exception is raised, then format not installed
640
+ if config.is_legacy and config.format is not None:
641
+ available_formats.append(config)
642
+
643
+ return available_formats
644
+
645
+ def __repr__(self):
646
+ return f"<imageio.FormatManager with {len(self._formats)} registered formats>"
647
+
648
+ def __iter__(self):
649
+ return iter(x.format for x in self._formats)
650
+
651
+ def __len__(self):
652
+ return len(self._formats)
653
+
654
+ def __str__(self):
655
+ ss = []
656
+ for config in self._formats:
657
+ ext = config.legacy_args["extensions"]
658
+ desc = config.legacy_args["description"]
659
+ s = f"{config.name} - {desc} [{ext}]"
660
+ ss.append(s)
661
+ return "\n".join(ss)
662
+
663
+ def __getitem__(self, name):
664
+ warnings.warn(
665
+ "The usage of `FormatManager` is deprecated and it will be "
666
+ "removed in Imageio v3. Use `iio.imopen` instead.",
667
+ DeprecationWarning,
668
+ stacklevel=2,
669
+ )
670
+
671
+ if not isinstance(name, str):
672
+ raise ValueError(
673
+ "Looking up a format should be done by name or by extension."
674
+ )
675
+
676
+ if name == "":
677
+ raise ValueError("No format matches the empty string.")
678
+
679
+ # Test if name is existing file
680
+ if Path(name).is_file():
681
+ # legacy compatibility - why test reading here??
682
+ try:
683
+ return imopen(name, "r", legacy_mode=True)._format
684
+ except ValueError:
685
+ # no plugin can read the file
686
+ pass
687
+
688
+ config = _get_config(name.upper())
689
+
690
+ try:
691
+ return config.format
692
+ except ImportError:
693
+ raise ImportError(
694
+ f"The `{config.name}` format is not installed. "
695
+ f"Use `pip install imageio[{config.install_name}]` to install it."
696
+ )
697
+
698
+ def sort(self, *names):
699
+ """sort(name1, name2, name3, ...)
700
+
701
+ Sort the formats based on zero or more given names; a format with
702
+ a name that matches one of the given names will take precedence
703
+ over other formats. A match means an equal name, or ending with
704
+ that name (though the former counts higher). Case insensitive.
705
+
706
+ Format preference will match the order of the given names: using
707
+ ``sort('TIFF', '-FI', '-PIL')`` would prefer the FreeImage formats
708
+ over the Pillow formats, but prefer TIFF even more. Each time
709
+ this is called, the starting point is the default format order,
710
+ and calling ``sort()`` with no arguments will reset the order.
711
+
712
+ Be aware that using the function can affect the behavior of
713
+ other code that makes use of imageio.
714
+
715
+ Also see the ``IMAGEIO_FORMAT_ORDER`` environment variable.
716
+ """
717
+
718
+ warnings.warn(
719
+ "`FormatManager` is deprecated and it will be removed in ImageIO v3."
720
+ " Migrating `FormatManager.sort` depends on your use-case:\n"
721
+ "\t- modify `iio.config.known_plugins` to specify the search order for "
722
+ "unrecognized formats.\n"
723
+ "\t- modify `iio.config.known_extensions[<extension>].priority`"
724
+ " to control a specific extension.",
725
+ DeprecationWarning,
726
+ stacklevel=2,
727
+ )
728
+
729
+ # Check and sanitize input
730
+ for name in names:
731
+ if not isinstance(name, str):
732
+ raise TypeError("formats.sort() accepts only string names.")
733
+ if any(c in name for c in ".,"):
734
+ raise ValueError(
735
+ "Names given to formats.sort() should not "
736
+ "contain dots `.` or commas `,`."
737
+ )
738
+
739
+ should_reset = len(names) == 0
740
+ if should_reset:
741
+ names = _original_order
742
+
743
+ sane_names = [name.strip().upper() for name in names if name != ""]
744
+
745
+ # enforce order for every extension that uses it
746
+ flat_extensions = [
747
+ ext for ext_list in known_extensions.values() for ext in ext_list
748
+ ]
749
+ for extension in flat_extensions:
750
+ if should_reset:
751
+ extension.reset()
752
+ continue
753
+
754
+ for name in reversed(sane_names):
755
+ for plugin in [x for x in extension.default_priority]:
756
+ if plugin.endswith(name):
757
+ extension.priority.remove(plugin)
758
+ extension.priority.insert(0, plugin)
759
+
760
+ old_order = known_plugins.copy()
761
+ known_plugins.clear()
762
+
763
+ for name in sane_names:
764
+ plugin = old_order.pop(name, None)
765
+ if plugin is not None:
766
+ known_plugins[name] = plugin
767
+
768
+ known_plugins.update(old_order)
769
+
770
+ def add_format(self, iio_format, overwrite=False):
771
+ """add_format(format, overwrite=False)
772
+
773
+ Register a format, so that imageio can use it. If a format with the
774
+ same name already exists, an error is raised, unless overwrite is True,
775
+ in which case the current format is replaced.
776
+ """
777
+
778
+ warnings.warn(
779
+ "`FormatManager` is deprecated and it will be removed in ImageIO v3."
780
+ "To migrate `FormatManager.add_format` add the plugin directly to "
781
+ "`iio.config.known_plugins`.",
782
+ DeprecationWarning,
783
+ stacklevel=2,
784
+ )
785
+
786
+ if not isinstance(iio_format, Format):
787
+ raise ValueError("add_format needs argument to be a Format object")
788
+ elif not overwrite and iio_format.name in self.get_format_names():
789
+ raise ValueError(
790
+ f"A Format named {iio_format.name} is already registered, use"
791
+ " `overwrite=True` to replace."
792
+ )
793
+
794
+ config = PluginConfig(
795
+ name=iio_format.name.upper(),
796
+ class_name=iio_format.__class__.__name__,
797
+ module_name=iio_format.__class__.__module__,
798
+ is_legacy=True,
799
+ install_name="unknown",
800
+ legacy_args={
801
+ "name": iio_format.name,
802
+ "description": iio_format.description,
803
+ "extensions": " ".join(iio_format.extensions),
804
+ "modes": iio_format.modes,
805
+ },
806
+ )
807
+
808
+ known_plugins[config.name] = config
809
+
810
+ for extension in iio_format.extensions:
811
+ # be conservative and always treat it as a unique file format
812
+ ext = FileExtension(
813
+ extension=extension,
814
+ priority=[config.name],
815
+ name="Unique Format",
816
+ description="A format inserted at runtime."
817
+ f" It is being read by the `{config.name}` plugin.",
818
+ )
819
+ known_extensions.setdefault(extension, list()).append(ext)
820
+
821
+ def search_read_format(self, request):
822
+ """search_read_format(request)
823
+
824
+ Search a format that can read a file according to the given request.
825
+ Returns None if no appropriate format was found. (used internally)
826
+ """
827
+
828
+ try:
829
+ # in legacy_mode imopen returns a LegacyPlugin
830
+ return imopen(request, request.mode.io_mode, legacy_mode=True)._format
831
+ except AttributeError:
832
+ warnings.warn(
833
+ "ImageIO now uses a v3 plugin when reading this format."
834
+ " Please migrate to the v3 API (preferred) or use imageio.v2.",
835
+ DeprecationWarning,
836
+ stacklevel=2,
837
+ )
838
+ return None
839
+ except ValueError:
840
+ # no plugin can read this request
841
+ # but the legacy API doesn't raise
842
+ return None
843
+
844
+ def search_write_format(self, request):
845
+ """search_write_format(request)
846
+
847
+ Search a format that can write a file according to the given request.
848
+ Returns None if no appropriate format was found. (used internally)
849
+ """
850
+
851
+ try:
852
+ # in legacy_mode imopen returns a LegacyPlugin
853
+ return imopen(request, request.mode.io_mode, legacy_mode=True)._format
854
+ except AttributeError:
855
+ warnings.warn(
856
+ "ImageIO now uses a v3 plugin when writing this format."
857
+ " Please migrate to the v3 API (preferred) or use imageio.v2.",
858
+ DeprecationWarning,
859
+ stacklevel=2,
860
+ )
861
+ return None
862
+ except ValueError:
863
+ # no plugin can write this request
864
+ # but the legacy API doesn't raise
865
+ return None
866
+
867
+ def get_format_names(self):
868
+ """Get the names of all registered formats."""
869
+
870
+ warnings.warn(
871
+ "`FormatManager` is deprecated and it will be removed in ImageIO v3."
872
+ "To migrate `FormatManager.get_format_names` use `iio.config.known_plugins.keys()` instead.",
873
+ DeprecationWarning,
874
+ stacklevel=2,
875
+ )
876
+
877
+ return [f.name for f in self._formats]
878
+
879
+ def show(self):
880
+ """Show a nicely formatted list of available formats"""
881
+ print(self)
parrot/lib/python3.10/site-packages/imageio/core/imopen.py ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ import warnings
3
+
4
+ from ..config import known_plugins
5
+ from ..config.extensions import known_extensions
6
+ from .request import (
7
+ SPECIAL_READ_URIS,
8
+ URI_FILENAME,
9
+ InitializationError,
10
+ IOMode,
11
+ Request,
12
+ )
13
+
14
+
15
+ def imopen(
16
+ uri,
17
+ io_mode,
18
+ *,
19
+ plugin=None,
20
+ extension=None,
21
+ format_hint=None,
22
+ legacy_mode=False,
23
+ **kwargs,
24
+ ):
25
+ """Open an ImageResource.
26
+
27
+ .. warning::
28
+ This warning is for pypy users. If you are not using a context manager,
29
+ remember to deconstruct the returned plugin to avoid leaking the file
30
+ handle to an unclosed file.
31
+
32
+ Parameters
33
+ ----------
34
+ uri : str or pathlib.Path or bytes or file or Request
35
+ The :doc:`ImageResource <../../user_guide/requests>` to load the
36
+ image from.
37
+ io_mode : str
38
+ The mode in which the file is opened. Possible values are::
39
+
40
+ ``r`` - open the file for reading
41
+ ``w`` - open the file for writing
42
+
43
+ Depreciated since v2.9:
44
+ A second character can be added to give the reader a hint on what
45
+ the user expects. This will be ignored by new plugins and will
46
+ only have an effect on legacy plugins. Possible values are::
47
+
48
+ ``i`` for a single image,
49
+ ``I`` for multiple images,
50
+ ``v`` for a single volume,
51
+ ``V`` for multiple volumes,
52
+ ``?`` for don't care
53
+
54
+ plugin : str, Plugin, or None
55
+ The plugin to use. If set to None imopen will perform a
56
+ search for a matching plugin. If not None, this takes priority over
57
+ the provided format hint.
58
+ extension : str
59
+ If not None, treat the provided ImageResource as if it had the given
60
+ extension. This affects the order in which backends are considered, and
61
+ when writing this may also influence the format used when encoding.
62
+ format_hint : str
63
+ Deprecated. Use `extension` instead.
64
+ legacy_mode : bool
65
+ If true use the v2 behavior when searching for a suitable
66
+ plugin. This will ignore v3 plugins and will check ``plugin``
67
+ against known extensions if no plugin with the given name can be found.
68
+ **kwargs : Any
69
+ Additional keyword arguments will be passed to the plugin upon
70
+ construction.
71
+
72
+ Notes
73
+ -----
74
+ Registered plugins are controlled via the ``known_plugins`` dict in
75
+ ``imageio.config``.
76
+
77
+ Passing a ``Request`` as the uri is only supported if ``legacy_mode``
78
+ is ``True``. In this case ``io_mode`` is ignored.
79
+
80
+ Using the kwarg ``format_hint`` does not enforce the given format. It merely
81
+ provides a `hint` to the selection process and plugin. The selection
82
+ processes uses this hint for optimization; however, a plugin's decision how
83
+ to read a ImageResource will - typically - still be based on the content of
84
+ the resource.
85
+
86
+
87
+ Examples
88
+ --------
89
+
90
+ >>> import imageio.v3 as iio
91
+ >>> with iio.imopen("/path/to/image.png", "r") as file:
92
+ >>> im = file.read()
93
+
94
+ >>> with iio.imopen("/path/to/output.jpg", "w") as file:
95
+ >>> file.write(im)
96
+
97
+ """
98
+
99
+ if isinstance(uri, Request) and legacy_mode:
100
+ warnings.warn(
101
+ "`iio.core.Request` is a low-level object and using it"
102
+ " directly as input to `imopen` is discouraged. This will raise"
103
+ " an exception in ImageIO v3.",
104
+ DeprecationWarning,
105
+ stacklevel=2,
106
+ )
107
+
108
+ request = uri
109
+ uri = request.raw_uri
110
+ io_mode = request.mode.io_mode
111
+ request.format_hint = format_hint
112
+ else:
113
+ request = Request(uri, io_mode, format_hint=format_hint, extension=extension)
114
+
115
+ source = "<bytes>" if isinstance(uri, bytes) else uri
116
+
117
+ # fast-path based on plugin
118
+ # (except in legacy mode)
119
+ if plugin is not None:
120
+ if isinstance(plugin, str):
121
+ try:
122
+ config = known_plugins[plugin]
123
+ except KeyError:
124
+ request.finish()
125
+ raise ValueError(
126
+ f"`{plugin}` is not a registered plugin name."
127
+ ) from None
128
+
129
+ def loader(request, **kwargs):
130
+ return config.plugin_class(request, **kwargs)
131
+
132
+ else:
133
+
134
+ def loader(request, **kwargs):
135
+ return plugin(request, **kwargs)
136
+
137
+ try:
138
+ return loader(request, **kwargs)
139
+ except InitializationError as class_specific:
140
+ err_from = class_specific
141
+ err_type = RuntimeError if legacy_mode else IOError
142
+ err_msg = f"`{plugin}` can not handle the given uri."
143
+ except ImportError:
144
+ err_from = None
145
+ err_type = ImportError
146
+ err_msg = (
147
+ f"The `{config.name}` plugin is not installed. "
148
+ f"Use `pip install imageio[{config.install_name}]` to install it."
149
+ )
150
+ except Exception as generic_error:
151
+ err_from = generic_error
152
+ err_type = IOError
153
+ err_msg = f"An unknown error occurred while initializing plugin `{plugin}`."
154
+
155
+ request.finish()
156
+ raise err_type(err_msg) from err_from
157
+
158
+ # fast-path based on format_hint
159
+ if request.format_hint is not None:
160
+ for candidate_format in known_extensions[format_hint]:
161
+ for plugin_name in candidate_format.priority:
162
+ config = known_plugins[plugin_name]
163
+
164
+ try:
165
+ candidate_plugin = config.plugin_class
166
+ except ImportError:
167
+ # not installed
168
+ continue
169
+
170
+ try:
171
+ plugin_instance = candidate_plugin(request, **kwargs)
172
+ except InitializationError:
173
+ # file extension doesn't match file type
174
+ continue
175
+
176
+ return plugin_instance
177
+ else:
178
+ resource = (
179
+ "<bytes>" if isinstance(request.raw_uri, bytes) else request.raw_uri
180
+ )
181
+ warnings.warn(f"`{resource}` can not be opened as a `{format_hint}` file.")
182
+
183
+ # fast-path based on file extension
184
+ if request.extension in known_extensions:
185
+ for candidate_format in known_extensions[request.extension]:
186
+ for plugin_name in candidate_format.priority:
187
+ config = known_plugins[plugin_name]
188
+
189
+ try:
190
+ candidate_plugin = config.plugin_class
191
+ except ImportError:
192
+ # not installed
193
+ continue
194
+
195
+ try:
196
+ plugin_instance = candidate_plugin(request, **kwargs)
197
+ except InitializationError:
198
+ # file extension doesn't match file type
199
+ continue
200
+
201
+ return plugin_instance
202
+
203
+ # error out for read-only special targets
204
+ # this is hacky; can we come up with a better solution for this?
205
+ if request.mode.io_mode == IOMode.write:
206
+ if isinstance(uri, str) and uri.startswith(SPECIAL_READ_URIS):
207
+ request.finish()
208
+ err_type = ValueError if legacy_mode else IOError
209
+ err_msg = f"`{source}` is read-only."
210
+ raise err_type(err_msg)
211
+
212
+ # error out for directories
213
+ # this is a bit hacky and should be cleaned once we decide
214
+ # how to gracefully handle DICOM
215
+ if request._uri_type == URI_FILENAME and Path(request.raw_uri).is_dir():
216
+ request.finish()
217
+ err_type = ValueError if legacy_mode else IOError
218
+ err_msg = (
219
+ "ImageIO does not generally support reading folders. "
220
+ "Limited support may be available via specific plugins. "
221
+ "Specify the plugin explicitly using the `plugin` kwarg, e.g. `plugin='DICOM'`"
222
+ )
223
+ raise err_type(err_msg)
224
+
225
+ # close the current request here and use fresh/new ones while trying each
226
+ # plugin This is slow (means potentially reopening a resource several
227
+ # times), but should only happen rarely because this is the fallback if all
228
+ # else fails.
229
+ request.finish()
230
+
231
+ # fallback option: try all plugins
232
+ for config in known_plugins.values():
233
+ # each plugin gets its own request
234
+ request = Request(uri, io_mode, format_hint=format_hint)
235
+
236
+ try:
237
+ plugin_instance = config.plugin_class(request, **kwargs)
238
+ except InitializationError:
239
+ continue
240
+ except ImportError:
241
+ continue
242
+ else:
243
+ return plugin_instance
244
+
245
+ err_type = ValueError if legacy_mode else IOError
246
+ err_msg = f"Could not find a backend to open `{source}`` with iomode `{io_mode}`."
247
+
248
+ # check if a missing plugin could help
249
+ if request.extension in known_extensions:
250
+ missing_plugins = list()
251
+
252
+ formats = known_extensions[request.extension]
253
+ plugin_names = [
254
+ plugin for file_format in formats for plugin in file_format.priority
255
+ ]
256
+ for name in plugin_names:
257
+ config = known_plugins[name]
258
+
259
+ try:
260
+ config.plugin_class
261
+ continue
262
+ except ImportError:
263
+ missing_plugins.append(config)
264
+
265
+ if len(missing_plugins) > 0:
266
+ install_candidates = "\n".join(
267
+ [
268
+ (
269
+ f" {config.name}: "
270
+ f"pip install imageio[{config.install_name}]"
271
+ )
272
+ for config in missing_plugins
273
+ ]
274
+ )
275
+ err_msg += (
276
+ "\nBased on the extension, the following plugins might add capable backends:\n"
277
+ f"{install_candidates}"
278
+ )
279
+
280
+ request.finish()
281
+ raise err_type(err_msg)
parrot/lib/python3.10/site-packages/imageio/core/legacy_plugin_wrapper.py ADDED
@@ -0,0 +1,363 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+
3
+ import numpy as np
4
+
5
+ from ..config import known_extensions
6
+ from .request import InitializationError, IOMode
7
+ from .v3_plugin_api import ImageProperties, PluginV3
8
+
9
+
10
+ def _legacy_default_index(format):
11
+ if format._name == "FFMPEG":
12
+ index = Ellipsis
13
+ elif format._name == "GIF-PIL":
14
+ index = Ellipsis
15
+ else:
16
+ index = 0
17
+
18
+ return index
19
+
20
+
21
+ class LegacyPlugin(PluginV3):
22
+ """A plugin to make old (v2.9) plugins compatible with v3.0
23
+
24
+ .. depreciated:: 2.9
25
+ `legacy_get_reader` will be removed in a future version of imageio.
26
+ `legacy_get_writer` will be removed in a future version of imageio.
27
+
28
+ This plugin is a wrapper around the old FormatManager class and exposes
29
+ all the old plugins via the new API. On top of this it has
30
+ ``legacy_get_reader`` and ``legacy_get_writer`` methods to allow using
31
+ it with the v2.9 API.
32
+
33
+ Methods
34
+ -------
35
+ read(index=None, **kwargs)
36
+ Read the image at position ``index``.
37
+ write(image, **kwargs)
38
+ Write image to the URI.
39
+ iter(**kwargs)
40
+ Iteratively yield images from the given URI.
41
+ get_meta(index=None)
42
+ Return the metadata for the image at position ``index``.
43
+ legacy_get_reader(**kwargs)
44
+ Returns the v2.9 image reader. (depreciated)
45
+ legacy_get_writer(**kwargs)
46
+ Returns the v2.9 image writer. (depreciated)
47
+
48
+ Examples
49
+ --------
50
+
51
+ >>> import imageio.v3 as iio
52
+ >>> with iio.imopen("/path/to/image.tiff", "r", legacy_mode=True) as file:
53
+ >>> reader = file.legacy_get_reader() # depreciated
54
+ >>> for im in file.iter():
55
+ >>> print(im.shape)
56
+
57
+ """
58
+
59
+ def __init__(self, request, legacy_plugin):
60
+ """Instantiate a new Legacy Plugin
61
+
62
+ Parameters
63
+ ----------
64
+ uri : {str, pathlib.Path, bytes, file}
65
+ The resource to load the image from, e.g. a filename, pathlib.Path,
66
+ http address or file object, see the docs for more info.
67
+ legacy_plugin : Format
68
+ The (legacy) format to use to interface with the URI.
69
+
70
+ """
71
+ self._request = request
72
+ self._format = legacy_plugin
73
+
74
+ source = (
75
+ "<bytes>"
76
+ if isinstance(self._request.raw_uri, bytes)
77
+ else self._request.raw_uri
78
+ )
79
+ if self._request.mode.io_mode == IOMode.read:
80
+ if not self._format.can_read(request):
81
+ raise InitializationError(
82
+ f"`{self._format.name}`" f" can not read `{source}`."
83
+ )
84
+ else:
85
+ if not self._format.can_write(request):
86
+ raise InitializationError(
87
+ f"`{self._format.name}`" f" can not write to `{source}`."
88
+ )
89
+
90
+ def legacy_get_reader(self, **kwargs):
91
+ """legacy_get_reader(**kwargs)
92
+
93
+ a utility method to provide support vor the V2.9 API
94
+
95
+ Parameters
96
+ ----------
97
+ kwargs : ...
98
+ Further keyword arguments are passed to the reader. See :func:`.help`
99
+ to see what arguments are available for a particular format.
100
+ """
101
+
102
+ # Note: this will break thread-safety
103
+ self._request._kwargs = kwargs
104
+
105
+ # safeguard for DICOM plugin reading from folders
106
+ try:
107
+ assert Path(self._request.filename).is_dir()
108
+ except OSError:
109
+ pass # not a valid path on this OS
110
+ except AssertionError:
111
+ pass # not a folder
112
+ else:
113
+ return self._format.get_reader(self._request)
114
+
115
+ self._request.get_file().seek(0)
116
+ return self._format.get_reader(self._request)
117
+
118
+ def read(self, *, index=None, **kwargs):
119
+ """
120
+ Parses the given URI and creates a ndarray from it.
121
+
122
+ Parameters
123
+ ----------
124
+ index : {integer, None}
125
+ If the URI contains a list of ndimages return the index-th
126
+ image. If None, stack all images into an ndimage along the
127
+ 0-th dimension (equivalent to np.stack(imgs, axis=0)).
128
+ kwargs : ...
129
+ Further keyword arguments are passed to the reader. See
130
+ :func:`.help` to see what arguments are available for a particular
131
+ format.
132
+
133
+ Returns
134
+ -------
135
+ ndimage : np.ndarray
136
+ A numpy array containing the decoded image data.
137
+
138
+ """
139
+
140
+ if index is None:
141
+ index = _legacy_default_index(self._format)
142
+
143
+ if index is Ellipsis:
144
+ img = np.stack([im for im in self.iter(**kwargs)])
145
+ return img
146
+
147
+ reader = self.legacy_get_reader(**kwargs)
148
+ return reader.get_data(index)
149
+
150
+ def legacy_get_writer(self, **kwargs):
151
+ """legacy_get_writer(**kwargs)
152
+
153
+ Returns a :class:`.Writer` object which can be used to write data
154
+ and meta data to the specified file.
155
+
156
+ Parameters
157
+ ----------
158
+ kwargs : ...
159
+ Further keyword arguments are passed to the writer. See :func:`.help`
160
+ to see what arguments are available for a particular format.
161
+ """
162
+
163
+ # Note: this will break thread-safety
164
+ self._request._kwargs = kwargs
165
+ return self._format.get_writer(self._request)
166
+
167
+ def write(self, ndimage, *, is_batch=None, metadata=None, **kwargs):
168
+ """
169
+ Write an ndimage to the URI specified in path.
170
+
171
+ If the URI points to a file on the current host and the file does not
172
+ yet exist it will be created. If the file exists already, it will be
173
+ appended if possible; otherwise, it will be replaced.
174
+
175
+ Parameters
176
+ ----------
177
+ ndimage : numpy.ndarray
178
+ The ndimage or list of ndimages to write.
179
+ is_batch : bool
180
+ If True, treat the supplied ndimage as a batch of images. If False,
181
+ treat the supplied ndimage as a single image. If None, try to
182
+ determine ``is_batch`` from the ndimage's shape and ndim.
183
+ metadata : dict
184
+ The metadata passed to write alongside the image.
185
+ kwargs : ...
186
+ Further keyword arguments are passed to the writer. See
187
+ :func:`.help` to see what arguments are available for a
188
+ particular format.
189
+
190
+
191
+ Returns
192
+ -------
193
+ buffer : bytes
194
+ When writing to the special target "<bytes>", this function will
195
+ return the encoded image data as a bytes string. Otherwise it
196
+ returns None.
197
+
198
+ Notes
199
+ -----
200
+ Automatically determining ``is_batch`` may fail for some images due to
201
+ shape aliasing. For example, it may classify a channel-first color image
202
+ as a batch of gray images. In most cases this automatic deduction works
203
+ fine (it has for almost a decade), but if you do have one of those edge
204
+ cases (or are worried that you might) consider explicitly setting
205
+ ``is_batch``.
206
+
207
+ """
208
+
209
+ if is_batch or isinstance(ndimage, (list, tuple)):
210
+ pass # ndimage is list of images
211
+ elif is_batch is False:
212
+ ndimage = [ndimage]
213
+ else:
214
+ # Write the largest possible block by guessing the meaning of each
215
+ # dimension from the shape/ndim and then checking if any batch
216
+ # dimensions are left.
217
+ ndimage = np.asanyarray(ndimage)
218
+ batch_dims = ndimage.ndim
219
+
220
+ # two spatial dimensions
221
+ batch_dims = max(batch_dims - 2, 0)
222
+
223
+ # packed (channel-last) image
224
+ if ndimage.ndim >= 3 and ndimage.shape[-1] < 5:
225
+ batch_dims = max(batch_dims - 1, 0)
226
+
227
+ # format supports volumetric images
228
+ ext_infos = known_extensions.get(self._request.extension, list())
229
+ for ext_info in ext_infos:
230
+ if self._format.name in ext_info.priority and ext_info.volume_support:
231
+ batch_dims = max(batch_dims - 1, 0)
232
+ break
233
+
234
+ if batch_dims == 0:
235
+ ndimage = [ndimage]
236
+
237
+ with self.legacy_get_writer(**kwargs) as writer:
238
+ for image in ndimage:
239
+ image = np.asanyarray(image)
240
+
241
+ if image.ndim < 2:
242
+ raise ValueError(
243
+ "The image must have at least two spatial dimensions."
244
+ )
245
+
246
+ if not np.issubdtype(image.dtype, np.number) and not np.issubdtype(
247
+ image.dtype, bool
248
+ ):
249
+ raise ValueError(
250
+ f"All images have to be numeric, and not `{image.dtype}`."
251
+ )
252
+
253
+ writer.append_data(image, metadata)
254
+
255
+ return writer.request.get_result()
256
+
257
+ def iter(self, **kwargs):
258
+ """Iterate over a list of ndimages given by the URI
259
+
260
+ Parameters
261
+ ----------
262
+ kwargs : ...
263
+ Further keyword arguments are passed to the reader. See
264
+ :func:`.help` to see what arguments are available for a particular
265
+ format.
266
+ """
267
+
268
+ reader = self.legacy_get_reader(**kwargs)
269
+ for image in reader:
270
+ yield image
271
+
272
+ def properties(self, index=None):
273
+ """Standardized ndimage metadata.
274
+
275
+ Parameters
276
+ ----------
277
+ index : int
278
+ The index of the ndimage for which to return properties. If the
279
+ index is out of bounds a ``ValueError`` is raised. If ``None``,
280
+ return the properties for the ndimage stack. If this is impossible,
281
+ e.g., due to shape mismatch, an exception will be raised.
282
+
283
+ Returns
284
+ -------
285
+ properties : ImageProperties
286
+ A dataclass filled with standardized image metadata.
287
+
288
+ """
289
+
290
+ if index is None:
291
+ index = _legacy_default_index(self._format)
292
+
293
+ # for backwards compatibility ... actually reads pixel data :(
294
+ if index is Ellipsis:
295
+ image = self.read(index=0)
296
+ n_images = self.legacy_get_reader().get_length()
297
+ return ImageProperties(
298
+ shape=(n_images, *image.shape),
299
+ dtype=image.dtype,
300
+ n_images=n_images,
301
+ is_batch=True,
302
+ )
303
+
304
+ image = self.read(index=index)
305
+ return ImageProperties(
306
+ shape=image.shape,
307
+ dtype=image.dtype,
308
+ is_batch=False,
309
+ )
310
+
311
+ def get_meta(self, *, index=None):
312
+ """Read ndimage metadata from the URI
313
+
314
+ Parameters
315
+ ----------
316
+ index : {integer, None}
317
+ If the URI contains a list of ndimages return the metadata
318
+ corresponding to the index-th image. If None, behavior depends on
319
+ the used api
320
+
321
+ Legacy-style API: return metadata of the first element (index=0)
322
+ New-style API: Behavior depends on the used Plugin.
323
+
324
+ Returns
325
+ -------
326
+ metadata : dict
327
+ A dictionary of metadata.
328
+
329
+ """
330
+
331
+ return self.metadata(index=index, exclude_applied=False)
332
+
333
+ def metadata(self, index=None, exclude_applied: bool = True):
334
+ """Format-Specific ndimage metadata.
335
+
336
+ Parameters
337
+ ----------
338
+ index : int
339
+ The index of the ndimage to read. If the index is out of bounds a
340
+ ``ValueError`` is raised. If ``None``, global metadata is returned.
341
+ exclude_applied : bool
342
+ This parameter exists for compatibility and has no effect. Legacy
343
+ plugins always report all metadata they find.
344
+
345
+ Returns
346
+ -------
347
+ metadata : dict
348
+ A dictionary filled with format-specific metadata fields and their
349
+ values.
350
+
351
+ """
352
+
353
+ if index is None:
354
+ index = _legacy_default_index(self._format)
355
+
356
+ return self.legacy_get_reader().get_meta_data(index=index)
357
+
358
+ def __del__(self) -> None:
359
+ pass
360
+ # turns out we can't close the file here for LegacyPlugin
361
+ # because it would break backwards compatibility
362
+ # with legacy_get_writer and legacy_get_reader
363
+ # self._request.finish()
parrot/lib/python3.10/site-packages/imageio/core/legacy_plugin_wrapper.pyi ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from typing import Optional, Dict, Any, Union, List, Iterator
3
+
4
+ from .request import Request
5
+ from .v3_plugin_api import PluginV3, ImageProperties
6
+ from .format import Format
7
+ from ..typing import ArrayLike
8
+
9
+ class LegacyPlugin(PluginV3):
10
+ def __init__(self, request: Request, legacy_plugin: Format) -> None: ...
11
+ def legacy_get_reader(self, **kwargs) -> Format.Reader: ...
12
+ def read(self, *, index: Optional[int] = 0, **kwargs) -> np.ndarray: ...
13
+ def legacy_get_writer(self, **kwargs) -> Format.Writer: ...
14
+ def write(
15
+ self,
16
+ ndimage: Union[ArrayLike, List[ArrayLike]],
17
+ *,
18
+ is_batch: bool = None,
19
+ **kwargs
20
+ ) -> Optional[bytes]: ...
21
+ def iter(self, **kwargs) -> Iterator[np.ndarray]: ...
22
+ def properties(self, index: Optional[int] = 0) -> ImageProperties: ...
23
+ def get_meta(self, *, index: Optional[int] = 0) -> Dict[str, Any]: ...
24
+ def metadata(
25
+ self, index: Optional[int] = 0, exclude_applied: bool = True
26
+ ) -> Dict[str, Any]: ...
27
+ def __del__(self) -> None: ...
parrot/lib/python3.10/site-packages/imageio/core/request.py ADDED
@@ -0,0 +1,754 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 os
10
+ from io import BytesIO
11
+ import zipfile
12
+ import tempfile
13
+ import shutil
14
+ import enum
15
+ import warnings
16
+
17
+ from ..core import urlopen, get_remote_file
18
+
19
+ from pathlib import Path
20
+ from urllib.parse import urlparse
21
+ from typing import Optional
22
+
23
+ # URI types
24
+ URI_BYTES = 1
25
+ URI_FILE = 2
26
+ URI_FILENAME = 3
27
+ URI_ZIPPED = 4
28
+ URI_HTTP = 5
29
+ URI_FTP = 6
30
+
31
+
32
+ class IOMode(str, enum.Enum):
33
+ """Available Image modes
34
+
35
+ This is a helper enum for ``Request.Mode`` which is a composite of a
36
+ ``Request.ImageMode`` and ``Request.IOMode``. The IOMode that tells the
37
+ plugin if the resource should be read from or written to. Available values are
38
+
39
+ - read ("r"): Read from the specified resource
40
+ - write ("w"): Write to the specified resource
41
+
42
+ """
43
+
44
+ read = "r"
45
+ write = "w"
46
+
47
+
48
+ class ImageMode(str, enum.Enum):
49
+ """Available Image modes
50
+
51
+ This is a helper enum for ``Request.Mode`` which is a composite of a
52
+ ``Request.ImageMode`` and ``Request.IOMode``. The image mode that tells the
53
+ plugin the desired (and expected) image shape. Available values are
54
+
55
+ - single_image ("i"): Return a single image extending in two spacial
56
+ dimensions
57
+ - multi_image ("I"): Return a list of images extending in two spacial
58
+ dimensions
59
+ - single_volume ("v"): Return an image extending into multiple dimensions.
60
+ E.g. three spacial dimensions for image stacks, or two spatial and one
61
+ time dimension for videos
62
+ - multi_volume ("V"): Return a list of images extending into multiple
63
+ dimensions.
64
+ - any_mode ("?"): Return an image in any format (the plugin decides the
65
+ appropriate action).
66
+
67
+ """
68
+
69
+ single_image = "i"
70
+ multi_image = "I"
71
+ single_volume = "v"
72
+ multi_volume = "V"
73
+ any_mode = "?"
74
+
75
+
76
+ @enum.unique
77
+ class Mode(str, enum.Enum):
78
+ """The mode to use when interacting with the resource
79
+
80
+ ``Request.Mode`` is a composite of ``Request.ImageMode`` and
81
+ ``Request.IOMode``. The image mode that tells the plugin the desired (and
82
+ expected) image shape and the ``Request.IOMode`` tells the plugin the way
83
+ the resource should be interacted with. For a detailed description of the
84
+ available modes, see the documentation for ``Request.ImageMode`` and
85
+ ``Request.IOMode`` respectively.
86
+
87
+ Available modes are all combinations of ``Request.IOMode`` and ``Request.ImageMode``:
88
+
89
+ - read_single_image ("ri")
90
+ - read_multi_image ("rI")
91
+ - read_single_volume ("rv")
92
+ - read_multi_volume ("rV")
93
+ - read_any ("r?")
94
+ - write_single_image ("wi")
95
+ - write_multi_image ("wI")
96
+ - write_single_volume ("wv")
97
+ - write_multi_volume ("wV")
98
+ - write_any ("w?")
99
+
100
+ Examples
101
+ --------
102
+ >>> Request.Mode("rI") # a list of simple images should be read from the resource
103
+ >>> Request.Mode("wv") # a single volume should be written to the resource
104
+
105
+ """
106
+
107
+ read_single_image = "ri"
108
+ read_multi_image = "rI"
109
+ read_single_volume = "rv"
110
+ read_multi_volume = "rV"
111
+ read_any = "r?"
112
+ write_single_image = "wi"
113
+ write_multi_image = "wI"
114
+ write_single_volume = "wv"
115
+ write_multi_volume = "wV"
116
+ write_any = "w?"
117
+
118
+ @classmethod
119
+ def _missing_(cls, value):
120
+ """Enable Mode("r") and Mode("w")
121
+
122
+ The sunder method ``_missing_`` is called whenever the constructor fails
123
+ to directly look up the corresponding enum value from the given input.
124
+ In our case, we use it to convert the modes "r" and "w" (from the v3
125
+ API) into their legacy versions "r?" and "w?".
126
+
127
+ More info on _missing_:
128
+ https://docs.python.org/3/library/enum.html#supported-sunder-names
129
+ """
130
+
131
+ if value == "r":
132
+ return cls("r?")
133
+ elif value == "w":
134
+ return cls("w?")
135
+ else:
136
+ raise ValueError(f"{value} is no valid Mode.")
137
+
138
+ @property
139
+ def io_mode(self) -> IOMode:
140
+ return IOMode(self.value[0])
141
+
142
+ @property
143
+ def image_mode(self) -> ImageMode:
144
+ return ImageMode(self.value[1])
145
+
146
+ def __getitem__(self, key):
147
+ """For backwards compatibility with the old non-enum modes"""
148
+ if key == 0:
149
+ return self.io_mode
150
+ elif key == 1:
151
+ return self.image_mode
152
+ else:
153
+ raise IndexError(f"Mode has no item {key}")
154
+
155
+
156
+ SPECIAL_READ_URIS = "<video", "<screen>", "<clipboard>"
157
+
158
+ # The user can use this string in a write call to get the data back as bytes.
159
+ RETURN_BYTES = "<bytes>"
160
+
161
+ # Example images that will be auto-downloaded
162
+ EXAMPLE_IMAGES = {
163
+ "astronaut.png": "Image of the astronaut Eileen Collins",
164
+ "camera.png": "A grayscale image of a photographer",
165
+ "checkerboard.png": "Black and white image of a chekerboard",
166
+ "wood.jpg": "A (repeatable) texture of wooden planks",
167
+ "bricks.jpg": "A (repeatable) texture of stone bricks",
168
+ "clock.png": "Photo of a clock with motion blur (Stefan van der Walt)",
169
+ "coffee.png": "Image of a cup of coffee (Rachel Michetti)",
170
+ "chelsea.png": "Image of Stefan's cat",
171
+ "wikkie.png": "Image of Almar's cat",
172
+ "coins.png": "Image showing greek coins from Pompeii",
173
+ "horse.png": "Image showing the silhouette of a horse (Andreas Preuss)",
174
+ "hubble_deep_field.png": "Photograph taken by Hubble telescope (NASA)",
175
+ "immunohistochemistry.png": "Immunohistochemical (IHC) staining",
176
+ "moon.png": "Image showing a portion of the surface of the moon",
177
+ "page.png": "A scanned page of text",
178
+ "text.png": "A photograph of handdrawn text",
179
+ "chelsea.zip": "The chelsea.png in a zipfile (for testing)",
180
+ "chelsea.bsdf": "The chelsea.png in a BSDF file(for testing)",
181
+ "newtonscradle.gif": "Animated GIF of a newton's cradle",
182
+ "cockatoo.mp4": "Video file of a cockatoo",
183
+ "stent.npz": "Volumetric image showing a stented abdominal aorta",
184
+ "meadow_cube.jpg": "A cubemap image of a meadow, e.g. to render a skybox.",
185
+ }
186
+
187
+
188
+ class Request(object):
189
+ """ImageResource handling utility.
190
+
191
+ Represents a request for reading or saving an image resource. This
192
+ object wraps information to that request and acts as an interface
193
+ for the plugins to several resources; it allows the user to read
194
+ from filenames, files, http, zipfiles, raw bytes, etc., but offer
195
+ a simple interface to the plugins via ``get_file()`` and
196
+ ``get_local_filename()``.
197
+
198
+ For each read/write operation a single Request instance is used and passed
199
+ to the can_read/can_write method of a format, and subsequently to
200
+ the Reader/Writer class. This allows rudimentary passing of
201
+ information between different formats and between a format and
202
+ associated reader/writer.
203
+
204
+ Parameters
205
+ ----------
206
+ uri : {str, bytes, file}
207
+ The resource to load the image from.
208
+ mode : str
209
+ The first character is "r" or "w", indicating a read or write
210
+ request. The second character is used to indicate the kind of data:
211
+ "i" for an image, "I" for multiple images, "v" for a volume,
212
+ "V" for multiple volumes, "?" for don't care.
213
+
214
+ """
215
+
216
+ def __init__(self, uri, mode, *, extension=None, format_hint: str = None, **kwargs):
217
+ # General
218
+ self.raw_uri = uri
219
+ self._uri_type = None
220
+ self._filename = None
221
+ self._extension = None
222
+ self._format_hint = None
223
+ self._kwargs = kwargs
224
+ self._result = None # Some write actions may have a result
225
+
226
+ # To handle the user-side
227
+ self._filename_zip = None # not None if a zipfile is used
228
+ self._bytes = None # Incoming bytes
229
+ self._zipfile = None # To store a zipfile instance (if used)
230
+
231
+ # To handle the plugin side
232
+ self._file = None # To store the file instance
233
+ self._file_is_local = False # whether the data needs to be copied at end
234
+ self._filename_local = None # not None if using tempfile on this FS
235
+ self._firstbytes = None # For easy header parsing
236
+
237
+ # To store formats that may be able to fulfil this request
238
+ # self._potential_formats = []
239
+
240
+ # Check mode
241
+ try:
242
+ self._mode = Mode(mode)
243
+ except ValueError:
244
+ raise ValueError(f"Invalid Request.Mode: {mode}")
245
+
246
+ # Parse what was given
247
+ self._parse_uri(uri)
248
+
249
+ # Set extension
250
+ if extension is not None:
251
+ if extension[0] != ".":
252
+ raise ValueError(
253
+ "`extension` should be a file extension starting with a `.`,"
254
+ f" but is `{extension}`."
255
+ )
256
+ self._extension = extension
257
+ elif self._filename is not None:
258
+ if self._uri_type in (URI_FILENAME, URI_ZIPPED):
259
+ path = self._filename
260
+ else:
261
+ path = urlparse(self._filename).path
262
+ ext = Path(path).suffix.lower()
263
+ self._extension = ext if ext != "" else None
264
+
265
+ if format_hint is not None:
266
+ warnings.warn(
267
+ "The usage of `format_hint` is deprecated and will be removed "
268
+ "in ImageIO v3. Use `extension` instead.",
269
+ DeprecationWarning,
270
+ )
271
+
272
+ if format_hint is not None and format_hint[0] != ".":
273
+ raise ValueError(
274
+ "`format_hint` should be a file extension starting with a `.`,"
275
+ f" but is `{format_hint}`."
276
+ )
277
+
278
+ self.format_hint = format_hint
279
+
280
+ def _parse_uri(self, uri):
281
+ """Try to figure our what we were given"""
282
+ is_read_request = self.mode.io_mode is IOMode.read
283
+ is_write_request = self.mode.io_mode is IOMode.write
284
+
285
+ if isinstance(uri, str):
286
+ # Explicit
287
+ if uri.startswith("imageio:"):
288
+ if is_write_request:
289
+ raise RuntimeError("Cannot write to the standard images.")
290
+ fn = uri.split(":", 1)[-1].lower()
291
+ fn, _, zip_part = fn.partition(".zip/")
292
+ if zip_part:
293
+ fn += ".zip"
294
+ if fn not in EXAMPLE_IMAGES:
295
+ raise ValueError("Unknown standard image %r." % fn)
296
+ self._uri_type = URI_FILENAME
297
+ self._filename = get_remote_file("images/" + fn, auto=True)
298
+ if zip_part:
299
+ self._filename += "/" + zip_part
300
+ elif uri.startswith("http://") or uri.startswith("https://"):
301
+ self._uri_type = URI_HTTP
302
+ self._filename = uri
303
+ elif uri.startswith("ftp://") or uri.startswith("ftps://"):
304
+ self._uri_type = URI_FTP
305
+ self._filename = uri
306
+ elif uri.startswith("file://"):
307
+ self._uri_type = URI_FILENAME
308
+ self._filename = uri[7:]
309
+ elif uri.startswith(SPECIAL_READ_URIS) and is_read_request:
310
+ self._uri_type = URI_BYTES
311
+ self._filename = uri
312
+ elif uri.startswith(RETURN_BYTES) and is_write_request:
313
+ self._uri_type = URI_BYTES
314
+ self._filename = uri
315
+ else:
316
+ self._uri_type = URI_FILENAME
317
+ self._filename = uri
318
+
319
+ elif isinstance(uri, memoryview) and is_read_request:
320
+ self._uri_type = URI_BYTES
321
+ self._filename = "<bytes>"
322
+ self._bytes = uri.tobytes()
323
+ elif isinstance(uri, bytes) and is_read_request:
324
+ self._uri_type = URI_BYTES
325
+ self._filename = "<bytes>"
326
+ self._bytes = uri
327
+ elif isinstance(uri, Path):
328
+ self._uri_type = URI_FILENAME
329
+ self._filename = str(uri)
330
+ # Files
331
+ elif is_read_request:
332
+ if hasattr(uri, "read") and hasattr(uri, "close"):
333
+ self._uri_type = URI_FILE
334
+ self._filename = "<file>"
335
+ self._file = uri # Data must be read from here
336
+ elif is_write_request:
337
+ if hasattr(uri, "write") and hasattr(uri, "close"):
338
+ self._uri_type = URI_FILE
339
+ self._filename = "<file>"
340
+ self._file = uri # Data must be written here
341
+
342
+ # Expand user dir
343
+ if self._uri_type == URI_FILENAME and self._filename.startswith("~"):
344
+ self._filename = os.path.expanduser(self._filename)
345
+
346
+ # Check if a zipfile
347
+ if self._uri_type == URI_FILENAME:
348
+ # Search for zip extension followed by a path separator
349
+ for needle in [".zip/", ".zip\\"]:
350
+ zip_i = self._filename.lower().find(needle)
351
+ if zip_i > 0:
352
+ zip_i += 4
353
+ zip_path = self._filename[:zip_i]
354
+ if os.path.isdir(zip_path):
355
+ pass # is an existing dir (see #548)
356
+ elif is_write_request or os.path.isfile(zip_path):
357
+ self._uri_type = URI_ZIPPED
358
+ self._filename_zip = (
359
+ zip_path,
360
+ self._filename[zip_i:].lstrip("/\\"),
361
+ )
362
+ break
363
+
364
+ # Check if we could read it
365
+ if self._uri_type is None:
366
+ uri_r = repr(uri)
367
+ if len(uri_r) > 60:
368
+ uri_r = uri_r[:57] + "..."
369
+ raise IOError("Cannot understand given URI: %s." % uri_r)
370
+
371
+ # Check if this is supported
372
+ noWriting = [URI_HTTP, URI_FTP]
373
+ if is_write_request and self._uri_type in noWriting:
374
+ raise IOError("imageio does not support writing to http/ftp.")
375
+
376
+ # Deprecated way to load standard images, give a sensible error message
377
+ if is_read_request and self._uri_type in [URI_FILENAME, URI_ZIPPED]:
378
+ fn = self._filename
379
+ if self._filename_zip:
380
+ fn = self._filename_zip[0]
381
+ if (not os.path.exists(fn)) and (fn in EXAMPLE_IMAGES):
382
+ raise IOError(
383
+ "No such file: %r. This file looks like one of "
384
+ "the standard images, but from imageio 2.1, "
385
+ "standard images have to be specified using "
386
+ '"imageio:%s".' % (fn, fn)
387
+ )
388
+
389
+ # Make filename absolute
390
+ if self._uri_type in [URI_FILENAME, URI_ZIPPED]:
391
+ if self._filename_zip:
392
+ self._filename_zip = (
393
+ os.path.abspath(self._filename_zip[0]),
394
+ self._filename_zip[1],
395
+ )
396
+ else:
397
+ self._filename = os.path.abspath(self._filename)
398
+
399
+ # Check whether file name is valid
400
+ if self._uri_type in [URI_FILENAME, URI_ZIPPED]:
401
+ fn = self._filename
402
+ if self._filename_zip:
403
+ fn = self._filename_zip[0]
404
+ if is_read_request:
405
+ # Reading: check that the file exists (but is allowed a dir)
406
+ if not os.path.exists(fn):
407
+ raise FileNotFoundError("No such file: '%s'" % fn)
408
+ else:
409
+ # Writing: check that the directory to write to does exist
410
+ dn = os.path.dirname(fn)
411
+ if not os.path.exists(dn):
412
+ raise FileNotFoundError("The directory %r does not exist" % dn)
413
+
414
+ @property
415
+ def filename(self):
416
+ """Name of the ImageResource.
417
+
418
+
419
+ The uri for which reading/saving was requested. This
420
+ can be a filename, an http address, or other resource
421
+ identifier. Do not rely on the filename to obtain the data,
422
+ but use ``get_file()`` or ``get_local_filename()`` instead.
423
+ """
424
+ return self._filename
425
+
426
+ @property
427
+ def extension(self) -> str:
428
+ """The (lowercase) extension of the requested filename.
429
+ Suffixes in url's are stripped. Can be None if the request is
430
+ not based on a filename.
431
+ """
432
+ return self._extension
433
+
434
+ @property
435
+ def format_hint(self) -> Optional[str]:
436
+ return self._format_hint
437
+
438
+ @format_hint.setter
439
+ def format_hint(self, format: str) -> None:
440
+ self._format_hint = format
441
+ if self._extension is None:
442
+ self._extension = format
443
+
444
+ @property
445
+ def mode(self):
446
+ """The mode of the request. The first character is "r" or "w",
447
+ indicating a read or write request. The second character is
448
+ used to indicate the kind of data:
449
+ "i" for an image, "I" for multiple images, "v" for a volume,
450
+ "V" for multiple volumes, "?" for don't care.
451
+ """
452
+ return self._mode
453
+
454
+ @property
455
+ def kwargs(self):
456
+ """The dict of keyword arguments supplied by the user."""
457
+ return self._kwargs
458
+
459
+ # For obtaining data
460
+
461
+ def get_file(self):
462
+ """get_file()
463
+ Get a file object for the resource associated with this request.
464
+ If this is a reading request, the file is in read mode,
465
+ otherwise in write mode. This method is not thread safe. Plugins
466
+ should not close the file when done.
467
+
468
+ This is the preferred way to read/write the data. But if a
469
+ format cannot handle file-like objects, they should use
470
+ ``get_local_filename()``.
471
+ """
472
+ want_to_write = self.mode.io_mode is IOMode.write
473
+
474
+ # Is there already a file?
475
+ # Either _uri_type == URI_FILE, or we already opened the file,
476
+ # e.g. by using firstbytes
477
+ if self._file is not None:
478
+ return self._file
479
+
480
+ if self._uri_type == URI_BYTES:
481
+ if want_to_write:
482
+ # Create new file object, we catch the bytes in finish()
483
+ self._file = BytesIO()
484
+ self._file_is_local = True
485
+ else:
486
+ self._file = BytesIO(self._bytes)
487
+
488
+ elif self._uri_type == URI_FILENAME:
489
+ if want_to_write:
490
+ self._file = open(self.filename, "wb")
491
+ else:
492
+ self._file = open(self.filename, "rb")
493
+
494
+ elif self._uri_type == URI_ZIPPED:
495
+ # Get the correct filename
496
+ filename, name = self._filename_zip
497
+ if want_to_write:
498
+ # Create new file object, we catch the bytes in finish()
499
+ self._file = BytesIO()
500
+ self._file_is_local = True
501
+ else:
502
+ # Open zipfile and open new file object for specific file
503
+ self._zipfile = zipfile.ZipFile(filename, "r")
504
+ self._file = self._zipfile.open(name, "r")
505
+ self._file = SeekableFileObject(self._file)
506
+
507
+ elif self._uri_type in [URI_HTTP or URI_FTP]:
508
+ assert not want_to_write # This should have been tested in init
509
+ timeout = os.getenv("IMAGEIO_REQUEST_TIMEOUT")
510
+ if timeout is None or not timeout.isdigit():
511
+ timeout = 5
512
+ self._file = urlopen(self.filename, timeout=float(timeout))
513
+ self._file = SeekableFileObject(self._file)
514
+
515
+ return self._file
516
+
517
+ def get_local_filename(self):
518
+ """get_local_filename()
519
+ If the filename is an existing file on this filesystem, return
520
+ that. Otherwise a temporary file is created on the local file
521
+ system which can be used by the format to read from or write to.
522
+ """
523
+
524
+ if self._uri_type == URI_FILENAME:
525
+ return self._filename
526
+ else:
527
+ # Get filename
528
+ if self.extension is not None:
529
+ ext = self.extension
530
+ else:
531
+ ext = os.path.splitext(self._filename)[1]
532
+ fd, self._filename_local = tempfile.mkstemp(ext, "imageio_")
533
+ os.close(fd)
534
+ # Write stuff to it?
535
+ if self.mode.io_mode == IOMode.read:
536
+ with open(self._filename_local, "wb") as file:
537
+ shutil.copyfileobj(self.get_file(), file)
538
+ return self._filename_local
539
+
540
+ def finish(self) -> None:
541
+ """Wrap up this request.
542
+
543
+ Finishes any pending reads or writes, closes any open files and frees
544
+ any resources allocated by this request.
545
+ """
546
+
547
+ if self.mode.io_mode == IOMode.write:
548
+ # See if we "own" the data and must put it somewhere
549
+ bytes = None
550
+ if self._filename_local:
551
+ bytes = Path(self._filename_local).read_bytes()
552
+ elif self._file_is_local:
553
+ self._file_is_local = False
554
+ bytes = self._file.getvalue()
555
+
556
+ # Put the data in the right place
557
+ if bytes is not None:
558
+ if self._uri_type == URI_BYTES:
559
+ self._result = bytes # Picked up by imread function
560
+ elif self._uri_type == URI_FILE:
561
+ self._file.write(bytes)
562
+ elif self._uri_type == URI_ZIPPED:
563
+ zf = zipfile.ZipFile(self._filename_zip[0], "a")
564
+ zf.writestr(self._filename_zip[1], bytes)
565
+ zf.close()
566
+ # elif self._uri_type == URI_FILENAME: -> is always direct
567
+ # elif self._uri_type == URI_FTP/HTTP: -> write not supported
568
+
569
+ # Close open files that we know of (and are responsible for)
570
+ if self._file and self._uri_type != URI_FILE:
571
+ self._file.close()
572
+ self._file = None
573
+ if self._zipfile:
574
+ self._zipfile.close()
575
+ self._zipfile = None
576
+
577
+ # Remove temp file
578
+ if self._filename_local:
579
+ try:
580
+ os.remove(self._filename_local)
581
+ except Exception: # pragma: no cover
582
+ warnings.warn(
583
+ "Failed to delete the temporary file at "
584
+ f"`{self._filename_local}`. Please report this issue."
585
+ )
586
+ self._filename_local = None
587
+
588
+ # Detach so gc can clean even if a reference of self lingers
589
+ self._bytes = None
590
+
591
+ def get_result(self):
592
+ """For internal use. In some situations a write action can have
593
+ a result (bytes data). That is obtained with this function.
594
+ """
595
+ # Is there a reason to disallow reading multiple times?
596
+ self._result, res = None, self._result
597
+ return res
598
+
599
+ @property
600
+ def firstbytes(self):
601
+ """The first 256 bytes of the file. These can be used to
602
+ parse the header to determine the file-format.
603
+ """
604
+ if self._firstbytes is None:
605
+ self._read_first_bytes()
606
+ return self._firstbytes
607
+
608
+ def _read_first_bytes(self, N=256):
609
+ if self._bytes is not None:
610
+ self._firstbytes = self._bytes[:N]
611
+ else:
612
+ # Prepare
613
+ try:
614
+ f = self.get_file()
615
+ except IOError:
616
+ if os.path.isdir(self.filename): # A directory, e.g. for DICOM
617
+ self._firstbytes = bytes()
618
+ return
619
+ raise
620
+ try:
621
+ i = f.tell()
622
+ except Exception:
623
+ i = None
624
+ # Read
625
+ self._firstbytes = read_n_bytes(f, N)
626
+ # Set back
627
+ try:
628
+ if i is None:
629
+ raise Exception("cannot seek with None")
630
+ f.seek(i)
631
+ except Exception:
632
+ # Prevent get_file() from reusing the file
633
+ self._file = None
634
+ # If the given URI was a file object, we have a problem,
635
+ if self._uri_type == URI_FILE:
636
+ raise IOError("Cannot seek back after getting firstbytes!")
637
+
638
+
639
+ def read_n_bytes(f, N):
640
+ """read_n_bytes(file, n)
641
+
642
+ Read n bytes from the given file, or less if the file has less
643
+ bytes. Returns zero bytes if the file is closed.
644
+ """
645
+ bb = bytes()
646
+ while len(bb) < N:
647
+ extra_bytes = f.read(N - len(bb))
648
+ if not extra_bytes:
649
+ break
650
+ bb += extra_bytes
651
+ return bb
652
+
653
+
654
+ class SeekableFileObject:
655
+ """A readonly wrapper file object that add support for seeking, even if
656
+ the wrapped file object does not. The allows us to stream from http and
657
+ still use Pillow.
658
+ """
659
+
660
+ def __init__(self, f):
661
+ self.f = f
662
+ self._i = 0 # >=0 but can exceed buffer
663
+ self._buffer = b""
664
+ self._have_all = False
665
+ self.closed = False
666
+
667
+ def read(self, n=None):
668
+ # Fix up n
669
+ if n is None:
670
+ pass
671
+ else:
672
+ n = int(n)
673
+ if n < 0:
674
+ n = None
675
+
676
+ # Can and must we read more?
677
+ if not self._have_all:
678
+ more = b""
679
+ if n is None:
680
+ more = self.f.read()
681
+ self._have_all = True
682
+ else:
683
+ want_i = self._i + n
684
+ want_more = want_i - len(self._buffer)
685
+ if want_more > 0:
686
+ more = self.f.read(want_more)
687
+ if len(more) < want_more:
688
+ self._have_all = True
689
+ self._buffer += more
690
+
691
+ # Read data from buffer and update pointer
692
+ if n is None:
693
+ res = self._buffer[self._i :]
694
+ else:
695
+ res = self._buffer[self._i : self._i + n]
696
+ self._i += len(res)
697
+
698
+ return res
699
+
700
+ def readline(self):
701
+ yield from self._file.readline()
702
+
703
+ def tell(self):
704
+ return self._i
705
+
706
+ def seek(self, i, mode=0):
707
+ # Mimic BytesIO behavior
708
+
709
+ # Get the absolute new position
710
+ i = int(i)
711
+ if mode == 0:
712
+ if i < 0:
713
+ raise ValueError("negative seek value " + str(i))
714
+ real_i = i
715
+ elif mode == 1:
716
+ real_i = max(0, self._i + i) # negative ok here
717
+ elif mode == 2:
718
+ if not self._have_all:
719
+ self.read()
720
+ real_i = max(0, len(self._buffer) + i)
721
+ else:
722
+ raise ValueError("invalid whence (%s, should be 0, 1 or 2)" % i)
723
+
724
+ # Read some?
725
+ if real_i <= len(self._buffer):
726
+ pass # no need to read
727
+ elif not self._have_all:
728
+ assert real_i > self._i # if we don't have all, _i cannot be > _buffer
729
+ self.read(real_i - self._i) # sets self._i
730
+
731
+ self._i = real_i
732
+ return self._i
733
+
734
+ def close(self):
735
+ self.closed = True
736
+ self.f.close()
737
+
738
+ def isatty(self):
739
+ return False
740
+
741
+ def seekable(self):
742
+ return True
743
+
744
+
745
+ class InitializationError(Exception):
746
+ """The plugin could not initialize from the given request.
747
+
748
+ This is a _internal_ error that is raised by plugins that fail to handle
749
+ a given request. We use this to differentiate incompatibility between
750
+ a plugin and a request from an actual error/bug inside a plugin.
751
+
752
+ """
753
+
754
+ pass
parrot/lib/python3.10/site-packages/imageio/core/request.pyi ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import BinaryIO, Optional, Dict, Any, Sequence, overload, Literal
2
+ from ..typing import ImageResource
3
+ import enum
4
+
5
+ EXAMPLE_IMAGES: Dict[str, str]
6
+ RETURN_BYTES = "<bytes>"
7
+ URI_BYTES = 1
8
+ URI_FILE = 2
9
+ URI_FILENAME = 3
10
+ URI_ZIPPED = 4
11
+ URI_HTTP = 5
12
+ URI_FTP = 6
13
+
14
+ class IOMode(str, enum.Enum):
15
+ read = "r"
16
+ write = "w"
17
+
18
+ class ImageMode(str, enum.Enum):
19
+ single_image = "i"
20
+ multi_image = "I"
21
+ single_volume = "v"
22
+ multi_volume = "V"
23
+ any_mode = "?"
24
+
25
+ @enum.unique
26
+ class Mode(str, enum.Enum):
27
+ read_single_image = "ri"
28
+ read_multi_image = "rI"
29
+ read_single_volume = "rv"
30
+ read_multi_volume = "rV"
31
+ read_any = "r?"
32
+ write_single_image = "wi"
33
+ write_multi_image = "wI"
34
+ write_single_volume = "wv"
35
+ write_multi_volume = "wV"
36
+ write_any = "w?"
37
+
38
+ @classmethod
39
+ def _missing_(cls, value: Any) -> Mode: ...
40
+ @property
41
+ def io_mode(self) -> IOMode: ...
42
+ @property
43
+ def image_mode(self) -> ImageMode: ...
44
+
45
+ class InitializationError(Exception): ...
46
+
47
+ class Request(object):
48
+ _uri_type: int
49
+ raw_uri: ImageResource
50
+
51
+ @property
52
+ def filename(self) -> str: ...
53
+ @property
54
+ def extension(self) -> str: ...
55
+ @property
56
+ def format_hint(self) -> Optional[str]: ...
57
+ @format_hint.setter
58
+ def format_hint(self, format: str) -> None: ...
59
+ @property
60
+ def mode(self) -> Mode: ...
61
+ @property
62
+ def kwargs(self) -> Dict[str, Any]: ...
63
+ @property
64
+ def firstbytes(self) -> bytes: ...
65
+ def __init__(
66
+ self,
67
+ uri: ImageResource,
68
+ mode: str,
69
+ *,
70
+ extension: str = None,
71
+ format_hint: str = None,
72
+ **kwargs
73
+ ) -> None: ...
74
+ def _parse_uri(self, uri: ImageResource) -> None: ...
75
+ def get_file(self) -> BinaryIO: ...
76
+ def get_local_filename(self) -> str: ...
77
+ def finish(self) -> None: ...
78
+ def get_result(self) -> Optional[bytes]: ...
79
+ def _read_first_bytes(self, N: int = 256) -> bytes: ...
80
+
81
+ def read_n_bytes(f: BinaryIO, N: int) -> bytes: ...
82
+
83
+ class SeekableFileObject:
84
+ def __init__(self, f: BinaryIO) -> None: ...
85
+ def read(self, n: int = None) -> bytes: ...
86
+ def tell(self) -> int: ...
87
+ def seek(self, i: int, mode: int = 0) -> int: ...
88
+ def close(self) -> None: ...
89
+ def isatty(self) -> bool: ...
90
+ def seekable(self) -> bool: ...
parrot/lib/python3.10/site-packages/imageio/core/util.py ADDED
@@ -0,0 +1,561 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # imageio is distributed under the terms of the (new) BSD License.
3
+
4
+ """
5
+ Various utilities for imageio
6
+ """
7
+
8
+
9
+ from collections import OrderedDict
10
+ import numpy as np
11
+ import os
12
+ import re
13
+ import struct
14
+ import sys
15
+ import time
16
+ import logging
17
+
18
+
19
+ logger = logging.getLogger("imageio")
20
+
21
+ IS_PYPY = "__pypy__" in sys.builtin_module_names
22
+ THIS_DIR = os.path.abspath(os.path.dirname(__file__))
23
+
24
+
25
+ def urlopen(*args, **kwargs):
26
+ """Compatibility function for the urlopen function. Raises an
27
+ RuntimeError if urlopen could not be imported (which can occur in
28
+ frozen applications.
29
+ """
30
+ try:
31
+ from urllib.request import urlopen
32
+ except ImportError:
33
+ raise RuntimeError("Could not import urlopen.")
34
+ return urlopen(*args, **kwargs)
35
+
36
+
37
+ def _precision_warn(p1, p2, extra=""):
38
+ t = (
39
+ "Lossy conversion from {} to {}. {} Convert image to {} prior to "
40
+ "saving to suppress this warning."
41
+ )
42
+ logger.warning(t.format(p1, p2, extra, p2))
43
+
44
+
45
+ def image_as_uint(im, bitdepth=None):
46
+ """Convert the given image to uint (default: uint8)
47
+
48
+ If the dtype already matches the desired format, it is returned
49
+ as-is. If the image is float, and all values are between 0 and 1,
50
+ the values are multiplied by np.power(2.0, bitdepth). In all other
51
+ situations, the values are scaled such that the minimum value
52
+ becomes 0 and the maximum value becomes np.power(2.0, bitdepth)-1
53
+ (255 for 8-bit and 65535 for 16-bit).
54
+ """
55
+ if not bitdepth:
56
+ bitdepth = 8
57
+ if not isinstance(im, np.ndarray):
58
+ raise ValueError("Image must be a numpy array")
59
+ if bitdepth == 8:
60
+ out_type = np.uint8
61
+ elif bitdepth == 16:
62
+ out_type = np.uint16
63
+ else:
64
+ raise ValueError("Bitdepth must be either 8 or 16")
65
+ dtype_str1 = str(im.dtype)
66
+ dtype_str2 = out_type.__name__
67
+ if (im.dtype == np.uint8 and bitdepth == 8) or (
68
+ im.dtype == np.uint16 and bitdepth == 16
69
+ ):
70
+ # Already the correct format? Return as-is
71
+ return im
72
+ if dtype_str1.startswith("float") and np.nanmin(im) >= 0 and np.nanmax(im) <= 1:
73
+ _precision_warn(dtype_str1, dtype_str2, "Range [0, 1].")
74
+ im = im.astype(np.float64) * (np.power(2.0, bitdepth) - 1) + 0.499999999
75
+ elif im.dtype == np.uint16 and bitdepth == 8:
76
+ _precision_warn(dtype_str1, dtype_str2, "Losing 8 bits of resolution.")
77
+ im = np.right_shift(im, 8)
78
+ elif im.dtype == np.uint32:
79
+ _precision_warn(
80
+ dtype_str1,
81
+ dtype_str2,
82
+ "Losing {} bits of resolution.".format(32 - bitdepth),
83
+ )
84
+ im = np.right_shift(im, 32 - bitdepth)
85
+ elif im.dtype == np.uint64:
86
+ _precision_warn(
87
+ dtype_str1,
88
+ dtype_str2,
89
+ "Losing {} bits of resolution.".format(64 - bitdepth),
90
+ )
91
+ im = np.right_shift(im, 64 - bitdepth)
92
+ else:
93
+ mi = np.nanmin(im)
94
+ ma = np.nanmax(im)
95
+ if not np.isfinite(mi):
96
+ raise ValueError("Minimum image value is not finite")
97
+ if not np.isfinite(ma):
98
+ raise ValueError("Maximum image value is not finite")
99
+ if ma == mi:
100
+ return im.astype(out_type)
101
+ _precision_warn(dtype_str1, dtype_str2, "Range [{}, {}].".format(mi, ma))
102
+ # Now make float copy before we scale
103
+ im = im.astype("float64")
104
+ # Scale the values between 0 and 1 then multiply by the max value
105
+ im = (im - mi) / (ma - mi) * (np.power(2.0, bitdepth) - 1) + 0.499999999
106
+ assert np.nanmin(im) >= 0
107
+ assert np.nanmax(im) < np.power(2.0, bitdepth)
108
+ return im.astype(out_type)
109
+
110
+
111
+ class Array(np.ndarray):
112
+ """Array(array, meta=None)
113
+
114
+ A subclass of np.ndarray that has a meta attribute. Get the dictionary
115
+ that contains the meta data using ``im.meta``. Convert to a plain numpy
116
+ array using ``np.asarray(im)``.
117
+
118
+ """
119
+
120
+ def __new__(cls, array, meta=None):
121
+ # Check
122
+ if not isinstance(array, np.ndarray):
123
+ raise ValueError("Array expects a numpy array.")
124
+ if not (meta is None or isinstance(meta, dict)):
125
+ raise ValueError("Array expects meta data to be a dict.")
126
+ # Convert and return
127
+ meta = meta if meta is not None else getattr(array, "meta", {})
128
+ try:
129
+ ob = array.view(cls)
130
+ except AttributeError: # pragma: no cover
131
+ # Just return the original; no metadata on the array in Pypy!
132
+ return array
133
+ ob._copy_meta(meta)
134
+ return ob
135
+
136
+ def _copy_meta(self, meta):
137
+ """Make a 2-level deep copy of the meta dictionary."""
138
+ self._meta = Dict()
139
+ for key, val in meta.items():
140
+ if isinstance(val, dict):
141
+ val = Dict(val) # Copy this level
142
+ self._meta[key] = val
143
+
144
+ @property
145
+ def meta(self):
146
+ """The dict with the meta data of this image."""
147
+ return self._meta
148
+
149
+ def __array_finalize__(self, ob):
150
+ """So the meta info is maintained when doing calculations with
151
+ the array.
152
+ """
153
+ if isinstance(ob, Array):
154
+ self._copy_meta(ob.meta)
155
+ else:
156
+ self._copy_meta({})
157
+
158
+ def __array_wrap__(self, out, context=None):
159
+ """So that we return a native numpy array (or scalar) when a
160
+ reducting ufunc is applied (such as sum(), std(), etc.)
161
+ """
162
+ if not out.shape:
163
+ return out.dtype.type(out) # Scalar
164
+ elif out.shape != self.shape:
165
+ return out.view(type=np.ndarray)
166
+ elif not isinstance(out, Array):
167
+ return Array(out, self.meta)
168
+ else:
169
+ return out # Type Array
170
+
171
+
172
+ Image = Array # Alias for backwards compatibility
173
+
174
+
175
+ def asarray(a):
176
+ """Pypy-safe version of np.asarray. Pypy's np.asarray consumes a
177
+ *lot* of memory if the given array is an ndarray subclass. This
178
+ function does not.
179
+ """
180
+ if isinstance(a, np.ndarray):
181
+ if IS_PYPY: # pragma: no cover
182
+ a = a.copy() # pypy has issues with base views
183
+ plain = a.view(type=np.ndarray)
184
+ return plain
185
+ return np.asarray(a)
186
+
187
+
188
+ class Dict(OrderedDict):
189
+ """A dict in which the keys can be get and set as if they were
190
+ attributes. Very convenient in combination with autocompletion.
191
+
192
+ This Dict still behaves as much as possible as a normal dict, and
193
+ keys can be anything that are otherwise valid keys. However,
194
+ keys that are not valid identifiers or that are names of the dict
195
+ class (such as 'items' and 'copy') cannot be get/set as attributes.
196
+ """
197
+
198
+ __reserved_names__ = dir(OrderedDict()) # Also from OrderedDict
199
+ __pure_names__ = dir(dict())
200
+
201
+ def __getattribute__(self, key):
202
+ try:
203
+ return object.__getattribute__(self, key)
204
+ except AttributeError:
205
+ if key in self:
206
+ return self[key]
207
+ else:
208
+ raise
209
+
210
+ def __setattr__(self, key, val):
211
+ if key in Dict.__reserved_names__:
212
+ # Either let OrderedDict do its work, or disallow
213
+ if key not in Dict.__pure_names__:
214
+ return OrderedDict.__setattr__(self, key, val)
215
+ else:
216
+ raise AttributeError(
217
+ "Reserved name, this key can only "
218
+ + "be set via ``d[%r] = X``" % key
219
+ )
220
+ else:
221
+ # if isinstance(val, dict): val = Dict(val) -> no, makes a copy!
222
+ self[key] = val
223
+
224
+ def __dir__(self):
225
+ def isidentifier(x):
226
+ return bool(re.match(r"[a-z_]\w*$", x, re.I))
227
+
228
+ names = [k for k in self.keys() if (isinstance(k, str) and isidentifier(k))]
229
+ return Dict.__reserved_names__ + names
230
+
231
+
232
+ class BaseProgressIndicator(object):
233
+ """BaseProgressIndicator(name)
234
+
235
+ A progress indicator helps display the progress of a task to the
236
+ user. Progress can be pending, running, finished or failed.
237
+
238
+ Each task has:
239
+ * a name - a short description of what needs to be done.
240
+ * an action - the current action in performing the task (e.g. a subtask)
241
+ * progress - how far the task is completed
242
+ * max - max number of progress units. If 0, the progress is indefinite
243
+ * unit - the units in which the progress is counted
244
+ * status - 0: pending, 1: in progress, 2: finished, 3: failed
245
+
246
+ This class defines an abstract interface. Subclasses should implement
247
+ _start, _stop, _update_progress(progressText), _write(message).
248
+ """
249
+
250
+ def __init__(self, name):
251
+ self._name = name
252
+ self._action = ""
253
+ self._unit = ""
254
+ self._max = 0
255
+ self._status = 0
256
+ self._last_progress_update = 0
257
+
258
+ def start(self, action="", unit="", max=0):
259
+ """start(action='', unit='', max=0)
260
+
261
+ Start the progress. Optionally specify an action, a unit,
262
+ and a maximum progress value.
263
+ """
264
+ if self._status == 1:
265
+ self.finish()
266
+ self._action = action
267
+ self._unit = unit
268
+ self._max = max
269
+ #
270
+ self._progress = 0
271
+ self._status = 1
272
+ self._start()
273
+
274
+ def status(self):
275
+ """status()
276
+
277
+ Get the status of the progress - 0: pending, 1: in progress,
278
+ 2: finished, 3: failed
279
+ """
280
+ return self._status
281
+
282
+ def set_progress(self, progress=0, force=False):
283
+ """set_progress(progress=0, force=False)
284
+
285
+ Set the current progress. To avoid unnecessary progress updates
286
+ this will only have a visual effect if the time since the last
287
+ update is > 0.1 seconds, or if force is True.
288
+ """
289
+ self._progress = progress
290
+ # Update or not?
291
+ if not (force or (time.time() - self._last_progress_update > 0.1)):
292
+ return
293
+ self._last_progress_update = time.time()
294
+ # Compose new string
295
+ unit = self._unit or ""
296
+ progressText = ""
297
+ if unit == "%":
298
+ progressText = "%2.1f%%" % progress
299
+ elif self._max > 0:
300
+ percent = 100 * float(progress) / self._max
301
+ progressText = "%i/%i %s (%2.1f%%)" % (progress, self._max, unit, percent)
302
+ elif progress > 0:
303
+ if isinstance(progress, float):
304
+ progressText = "%0.4g %s" % (progress, unit)
305
+ else:
306
+ progressText = "%i %s" % (progress, unit)
307
+ # Update
308
+ self._update_progress(progressText)
309
+
310
+ def increase_progress(self, extra_progress):
311
+ """increase_progress(extra_progress)
312
+
313
+ Increase the progress by a certain amount.
314
+ """
315
+ self.set_progress(self._progress + extra_progress)
316
+
317
+ def finish(self, message=None):
318
+ """finish(message=None)
319
+
320
+ Finish the progress, optionally specifying a message. This will
321
+ not set the progress to the maximum.
322
+ """
323
+ self.set_progress(self._progress, True) # fore update
324
+ self._status = 2
325
+ self._stop()
326
+ if message is not None:
327
+ self._write(message)
328
+
329
+ def fail(self, message=None):
330
+ """fail(message=None)
331
+
332
+ Stop the progress with a failure, optionally specifying a message.
333
+ """
334
+ self.set_progress(self._progress, True) # fore update
335
+ self._status = 3
336
+ self._stop()
337
+ message = "FAIL " + (message or "")
338
+ self._write(message)
339
+
340
+ def write(self, message):
341
+ """write(message)
342
+
343
+ Write a message during progress (such as a warning).
344
+ """
345
+ if self.__class__ == BaseProgressIndicator:
346
+ # When this class is used as a dummy, print explicit message
347
+ print(message)
348
+ else:
349
+ return self._write(message)
350
+
351
+ # Implementing classes should implement these
352
+
353
+ def _start(self):
354
+ pass
355
+
356
+ def _stop(self):
357
+ pass
358
+
359
+ def _update_progress(self, progressText):
360
+ pass
361
+
362
+ def _write(self, message):
363
+ pass
364
+
365
+
366
+ class StdoutProgressIndicator(BaseProgressIndicator):
367
+ """StdoutProgressIndicator(name)
368
+
369
+ A progress indicator that shows the progress in stdout. It
370
+ assumes that the tty can appropriately deal with backspace
371
+ characters.
372
+ """
373
+
374
+ def _start(self):
375
+ self._chars_prefix, self._chars = "", ""
376
+ # Write message
377
+ if self._action:
378
+ self._chars_prefix = "%s (%s): " % (self._name, self._action)
379
+ else:
380
+ self._chars_prefix = "%s: " % self._name
381
+ sys.stdout.write(self._chars_prefix)
382
+ sys.stdout.flush()
383
+
384
+ def _update_progress(self, progressText):
385
+ # If progress is unknown, at least make something move
386
+ if not progressText:
387
+ i1, i2, i3, i4 = "-\\|/"
388
+ M = {i1: i2, i2: i3, i3: i4, i4: i1}
389
+ progressText = M.get(self._chars, i1)
390
+ # Store new string and write
391
+ delChars = "\b" * len(self._chars)
392
+ self._chars = progressText
393
+ sys.stdout.write(delChars + self._chars)
394
+ sys.stdout.flush()
395
+
396
+ def _stop(self):
397
+ self._chars = self._chars_prefix = ""
398
+ sys.stdout.write("\n")
399
+ sys.stdout.flush()
400
+
401
+ def _write(self, message):
402
+ # Write message
403
+ delChars = "\b" * len(self._chars_prefix + self._chars)
404
+ sys.stdout.write(delChars + " " + message + "\n")
405
+ # Reprint progress text
406
+ sys.stdout.write(self._chars_prefix + self._chars)
407
+ sys.stdout.flush()
408
+
409
+
410
+ # From pyzolib/paths.py (https://bitbucket.org/pyzo/pyzolib/src/tip/paths.py)
411
+ def appdata_dir(appname=None, roaming=False):
412
+ """appdata_dir(appname=None, roaming=False)
413
+
414
+ Get the path to the application directory, where applications are allowed
415
+ to write user specific files (e.g. configurations). For non-user specific
416
+ data, consider using common_appdata_dir().
417
+ If appname is given, a subdir is appended (and created if necessary).
418
+ If roaming is True, will prefer a roaming directory (Windows Vista/7).
419
+ """
420
+
421
+ # Define default user directory
422
+ userDir = os.getenv("IMAGEIO_USERDIR", None)
423
+ if userDir is None:
424
+ userDir = os.path.expanduser("~")
425
+ if not os.path.isdir(userDir): # pragma: no cover
426
+ userDir = "/var/tmp" # issue #54
427
+
428
+ # Get system app data dir
429
+ path = None
430
+ if sys.platform.startswith("win"):
431
+ path1, path2 = os.getenv("LOCALAPPDATA"), os.getenv("APPDATA")
432
+ path = (path2 or path1) if roaming else (path1 or path2)
433
+ elif sys.platform.startswith("darwin"):
434
+ path = os.path.join(userDir, "Library", "Application Support")
435
+ # On Linux and as fallback
436
+ if not (path and os.path.isdir(path)):
437
+ path = userDir
438
+
439
+ # Maybe we should store things local to the executable (in case of a
440
+ # portable distro or a frozen application that wants to be portable)
441
+ prefix = sys.prefix
442
+ if getattr(sys, "frozen", None):
443
+ prefix = os.path.abspath(os.path.dirname(sys.executable))
444
+ for reldir in ("settings", "../settings"):
445
+ localpath = os.path.abspath(os.path.join(prefix, reldir))
446
+ if os.path.isdir(localpath): # pragma: no cover
447
+ try:
448
+ open(os.path.join(localpath, "test.write"), "wb").close()
449
+ os.remove(os.path.join(localpath, "test.write"))
450
+ except IOError:
451
+ pass # We cannot write in this directory
452
+ else:
453
+ path = localpath
454
+ break
455
+
456
+ # Get path specific for this app
457
+ if appname:
458
+ if path == userDir:
459
+ appname = "." + appname.lstrip(".") # Make it a hidden directory
460
+ path = os.path.join(path, appname)
461
+ if not os.path.isdir(path): # pragma: no cover
462
+ os.makedirs(path, exist_ok=True)
463
+
464
+ # Done
465
+ return path
466
+
467
+
468
+ def resource_dirs():
469
+ """resource_dirs()
470
+
471
+ Get a list of directories where imageio resources may be located.
472
+ The first directory in this list is the "resources" directory in
473
+ the package itself. The second directory is the appdata directory
474
+ (~/.imageio on Linux). The list further contains the application
475
+ directory (for frozen apps), and may include additional directories
476
+ in the future.
477
+ """
478
+ dirs = [resource_package_dir()]
479
+ # Resource dir baked in the package.
480
+ # Appdata directory
481
+ try:
482
+ dirs.append(appdata_dir("imageio"))
483
+ except Exception: # pragma: no cover
484
+ pass # The home dir may not be writable
485
+ # Directory where the app is located (mainly for frozen apps)
486
+ if getattr(sys, "frozen", None):
487
+ dirs.append(os.path.abspath(os.path.dirname(sys.executable)))
488
+ elif sys.path and sys.path[0]:
489
+ dirs.append(os.path.abspath(sys.path[0]))
490
+ return dirs
491
+
492
+
493
+ def resource_package_dir():
494
+ """package_dir
495
+
496
+ Get the resources directory in the imageio package installation
497
+ directory.
498
+
499
+ Notes
500
+ -----
501
+ This is a convenience method that is used by `resource_dirs` and
502
+ imageio entry point scripts.
503
+ """
504
+ # Make pkg_resources optional if setuptools is not available
505
+ try:
506
+ # Avoid importing pkg_resources in the top level due to how slow it is
507
+ # https://github.com/pypa/setuptools/issues/510
508
+ import pkg_resources
509
+ except ImportError:
510
+ pkg_resources = None
511
+
512
+ if pkg_resources:
513
+ # The directory returned by `pkg_resources.resource_filename`
514
+ # also works with eggs.
515
+ pdir = pkg_resources.resource_filename("imageio", "resources")
516
+ else:
517
+ # If setuptools is not available, use fallback
518
+ pdir = os.path.abspath(os.path.join(THIS_DIR, "..", "resources"))
519
+ return pdir
520
+
521
+
522
+ def get_platform():
523
+ """get_platform()
524
+
525
+ Get a string that specifies the platform more specific than
526
+ sys.platform does. The result can be: linux32, linux64, win32,
527
+ win64, osx32, osx64. Other platforms may be added in the future.
528
+ """
529
+ # Get platform
530
+ if sys.platform.startswith("linux"):
531
+ plat = "linux%i"
532
+ elif sys.platform.startswith("win"):
533
+ plat = "win%i"
534
+ elif sys.platform.startswith("darwin"):
535
+ plat = "osx%i"
536
+ elif sys.platform.startswith("freebsd"):
537
+ plat = "freebsd%i"
538
+ else: # pragma: no cover
539
+ return None
540
+
541
+ return plat % (struct.calcsize("P") * 8) # 32 or 64 bits
542
+
543
+
544
+ def has_module(module_name):
545
+ """Check to see if a python module is available."""
546
+ if sys.version_info > (3, 4):
547
+ import importlib
548
+
549
+ name_parts = module_name.split(".")
550
+ for i in range(len(name_parts)):
551
+ if importlib.util.find_spec(".".join(name_parts[: i + 1])) is None:
552
+ return False
553
+ return True
554
+ else: # pragma: no cover
555
+ import imp
556
+
557
+ try:
558
+ imp.find_module(module_name)
559
+ except ImportError:
560
+ return False
561
+ return True
parrot/lib/python3.10/site-packages/imageio/plugins/__pycache__/_dicom.cpython-310.pyc ADDED
Binary file (23.1 kB). View file
 
parrot/lib/python3.10/site-packages/imageio/plugins/__pycache__/_swf.cpython-310.pyc ADDED
Binary file (20.6 kB). View file
 
parrot/lib/python3.10/site-packages/imageio/plugins/__pycache__/bsdf.cpython-310.pyc ADDED
Binary file (11.1 kB). View file
 
parrot/lib/python3.10/site-packages/imageio/plugins/__pycache__/feisem.cpython-310.pyc ADDED
Binary file (3.03 kB). View file
 
parrot/lib/python3.10/site-packages/imageio/plugins/__pycache__/fits.cpython-310.pyc ADDED
Binary file (4.72 kB). View file
 
parrot/lib/python3.10/site-packages/imageio/plugins/__pycache__/simpleitk.cpython-310.pyc ADDED
Binary file (3.9 kB). View file
 
parrot/lib/python3.10/site-packages/markdown_it/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ """A Python port of Markdown-It"""
2
+ __all__ = ("MarkdownIt",)
3
+ __version__ = "2.2.0"
4
+
5
+ from .main import MarkdownIt
parrot/lib/python3.10/site-packages/markdown_it/_compat.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Mapping
4
+ import sys
5
+ from typing import Any
6
+
7
+ if sys.version_info >= (3, 10):
8
+ DATACLASS_KWARGS: Mapping[str, Any] = {"slots": True}
9
+ else:
10
+ DATACLASS_KWARGS: Mapping[str, Any] = {}
parrot/lib/python3.10/site-packages/markdown_it/_punycode.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2014 Mathias Bynens <https://mathiasbynens.be/>
2
+ # Copyright 2021 Taneli Hukkinen
3
+ #
4
+ # Permission is hereby granted, free of charge, to any person obtaining
5
+ # a copy of this software and associated documentation files (the
6
+ # "Software"), to deal in the Software without restriction, including
7
+ # without limitation the rights to use, copy, modify, merge, publish,
8
+ # distribute, sublicense, and/or sell copies of the Software, and to
9
+ # permit persons to whom the Software is furnished to do so, subject to
10
+ # the following conditions:
11
+ #
12
+ # The above copyright notice and this permission notice shall be
13
+ # included in all copies or substantial portions of the Software.
14
+ #
15
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18
+ # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19
+ # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20
+ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21
+ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22
+
23
+ import codecs
24
+ import re
25
+
26
+ REGEX_SEPARATORS = re.compile(r"[\x2E\u3002\uFF0E\uFF61]")
27
+ REGEX_NON_ASCII = re.compile(r"[^\0-\x7E]")
28
+
29
+
30
+ def encode(uni: str) -> str:
31
+ return codecs.encode(uni, encoding="punycode").decode()
32
+
33
+
34
+ def decode(ascii: str) -> str:
35
+ return codecs.decode(ascii, encoding="punycode") # type: ignore[call-overload]
36
+
37
+
38
+ def map_domain(string, fn):
39
+ parts = string.split("@")
40
+ result = ""
41
+ if len(parts) > 1:
42
+ # In email addresses, only the domain name should be punycoded. Leave
43
+ # the local part (i.e. everything up to `@`) intact.
44
+ result = parts[0] + "@"
45
+ string = parts[1]
46
+ labels = REGEX_SEPARATORS.split(string)
47
+ encoded = ".".join(fn(label) for label in labels)
48
+ return result + encoded
49
+
50
+
51
+ def to_unicode(obj: str) -> str:
52
+ def mapping(obj: str) -> str:
53
+ if obj.startswith("xn--"):
54
+ return decode(obj[4:].lower())
55
+ return obj
56
+
57
+ return map_domain(obj, mapping)
58
+
59
+
60
+ def to_ascii(obj: str) -> str:
61
+ def mapping(obj: str) -> str:
62
+ if REGEX_NON_ASCII.search(obj):
63
+ return "xn--" + encode(obj)
64
+ return obj
65
+
66
+ return map_domain(obj, mapping)
parrot/lib/python3.10/site-packages/markdown_it/main.py ADDED
@@ -0,0 +1,331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Callable, Generator, Iterable, Mapping, MutableMapping
4
+ from contextlib import contextmanager
5
+ from typing import Any
6
+
7
+ from . import helpers, presets # noqa F401
8
+ from .common import normalize_url, utils # noqa F401
9
+ from .parser_block import ParserBlock # noqa F401
10
+ from .parser_core import ParserCore # noqa F401
11
+ from .parser_inline import ParserInline # noqa F401
12
+ from .renderer import RendererHTML, RendererProtocol
13
+ from .rules_core.state_core import StateCore
14
+ from .token import Token
15
+ from .utils import OptionsDict
16
+
17
+ try:
18
+ import linkify_it
19
+ except ModuleNotFoundError:
20
+ linkify_it = None
21
+
22
+
23
+ _PRESETS = {
24
+ "default": presets.default.make(),
25
+ "js-default": presets.js_default.make(),
26
+ "zero": presets.zero.make(),
27
+ "commonmark": presets.commonmark.make(),
28
+ "gfm-like": presets.gfm_like.make(),
29
+ }
30
+
31
+
32
+ class MarkdownIt:
33
+ def __init__(
34
+ self,
35
+ config: str | Mapping = "commonmark",
36
+ options_update: Mapping | None = None,
37
+ *,
38
+ renderer_cls: Callable[[MarkdownIt], RendererProtocol] = RendererHTML,
39
+ ):
40
+ """Main parser class
41
+
42
+ :param config: name of configuration to load or a pre-defined dictionary
43
+ :param options_update: dictionary that will be merged into ``config["options"]``
44
+ :param renderer_cls: the class to load as the renderer:
45
+ ``self.renderer = renderer_cls(self)
46
+ """
47
+ # add modules
48
+ self.utils = utils
49
+ self.helpers: Any = helpers
50
+
51
+ # initialise classes
52
+ self.inline = ParserInline()
53
+ self.block = ParserBlock()
54
+ self.core = ParserCore()
55
+ self.renderer = renderer_cls(self)
56
+ self.linkify = linkify_it.LinkifyIt() if linkify_it else None
57
+
58
+ # set the configuration
59
+ if options_update and not isinstance(options_update, Mapping):
60
+ # catch signature change where renderer_cls was not used as a key-word
61
+ raise TypeError(
62
+ f"options_update should be a mapping: {options_update}"
63
+ "\n(Perhaps you intended this to be the renderer_cls?)"
64
+ )
65
+ self.configure(config, options_update=options_update)
66
+
67
+ def __repr__(self) -> str:
68
+ return f"{self.__class__.__module__}.{self.__class__.__name__}()"
69
+
70
+ def __getitem__(self, name: str) -> Any:
71
+ return {
72
+ "inline": self.inline,
73
+ "block": self.block,
74
+ "core": self.core,
75
+ "renderer": self.renderer,
76
+ }[name]
77
+
78
+ def set(self, options: MutableMapping) -> None:
79
+ """Set parser options (in the same format as in constructor).
80
+ Probably, you will never need it, but you can change options after constructor call.
81
+
82
+ __Note:__ To achieve the best possible performance, don't modify a
83
+ `markdown-it` instance options on the fly. If you need multiple configurations
84
+ it's best to create multiple instances and initialize each with separate config.
85
+ """
86
+ self.options = OptionsDict(options)
87
+
88
+ def configure(
89
+ self, presets: str | Mapping, options_update: Mapping | None = None
90
+ ) -> MarkdownIt:
91
+ """Batch load of all options and component settings.
92
+ This is an internal method, and you probably will not need it.
93
+ But if you will - see available presets and data structure
94
+ [here](https://github.com/markdown-it/markdown-it/tree/master/lib/presets)
95
+
96
+ We strongly recommend to use presets instead of direct config loads.
97
+ That will give better compatibility with next versions.
98
+ """
99
+ if isinstance(presets, str):
100
+ if presets not in _PRESETS:
101
+ raise KeyError(f"Wrong `markdown-it` preset '{presets}', check name")
102
+ config = _PRESETS[presets]
103
+ else:
104
+ config = presets
105
+
106
+ if not config:
107
+ raise ValueError("Wrong `markdown-it` config, can't be empty")
108
+
109
+ options = config.get("options", {}) or {}
110
+ if options_update:
111
+ options = {**options, **options_update}
112
+
113
+ self.set(options)
114
+
115
+ if "components" in config:
116
+ for name, component in config["components"].items():
117
+ rules = component.get("rules", None)
118
+ if rules:
119
+ self[name].ruler.enableOnly(rules)
120
+ rules2 = component.get("rules2", None)
121
+ if rules2:
122
+ self[name].ruler2.enableOnly(rules2)
123
+
124
+ return self
125
+
126
+ def get_all_rules(self) -> dict[str, list[str]]:
127
+ """Return the names of all active rules."""
128
+ rules = {
129
+ chain: self[chain].ruler.get_all_rules()
130
+ for chain in ["core", "block", "inline"]
131
+ }
132
+ rules["inline2"] = self.inline.ruler2.get_all_rules()
133
+ return rules
134
+
135
+ def get_active_rules(self) -> dict[str, list[str]]:
136
+ """Return the names of all active rules."""
137
+ rules = {
138
+ chain: self[chain].ruler.get_active_rules()
139
+ for chain in ["core", "block", "inline"]
140
+ }
141
+ rules["inline2"] = self.inline.ruler2.get_active_rules()
142
+ return rules
143
+
144
+ def enable(
145
+ self, names: str | Iterable[str], ignoreInvalid: bool = False
146
+ ) -> MarkdownIt:
147
+ """Enable list or rules. (chainable)
148
+
149
+ :param names: rule name or list of rule names to enable.
150
+ :param ignoreInvalid: set `true` to ignore errors when rule not found.
151
+
152
+ It will automatically find appropriate components,
153
+ containing rules with given names. If rule not found, and `ignoreInvalid`
154
+ not set - throws exception.
155
+
156
+ Example::
157
+
158
+ md = MarkdownIt().enable(['sub', 'sup']).disable('smartquotes')
159
+
160
+ """
161
+ result = []
162
+
163
+ if isinstance(names, str):
164
+ names = [names]
165
+
166
+ for chain in ["core", "block", "inline"]:
167
+ result.extend(self[chain].ruler.enable(names, True))
168
+ result.extend(self.inline.ruler2.enable(names, True))
169
+
170
+ missed = [name for name in names if name not in result]
171
+ if missed and not ignoreInvalid:
172
+ raise ValueError(f"MarkdownIt. Failed to enable unknown rule(s): {missed}")
173
+
174
+ return self
175
+
176
+ def disable(
177
+ self, names: str | Iterable[str], ignoreInvalid: bool = False
178
+ ) -> MarkdownIt:
179
+ """The same as [[MarkdownIt.enable]], but turn specified rules off. (chainable)
180
+
181
+ :param names: rule name or list of rule names to disable.
182
+ :param ignoreInvalid: set `true` to ignore errors when rule not found.
183
+
184
+ """
185
+ result = []
186
+
187
+ if isinstance(names, str):
188
+ names = [names]
189
+
190
+ for chain in ["core", "block", "inline"]:
191
+ result.extend(self[chain].ruler.disable(names, True))
192
+ result.extend(self.inline.ruler2.disable(names, True))
193
+
194
+ missed = [name for name in names if name not in result]
195
+ if missed and not ignoreInvalid:
196
+ raise ValueError(f"MarkdownIt. Failed to disable unknown rule(s): {missed}")
197
+ return self
198
+
199
+ @contextmanager
200
+ def reset_rules(self) -> Generator[None, None, None]:
201
+ """A context manager, that will reset the current enabled rules on exit."""
202
+ chain_rules = self.get_active_rules()
203
+ yield
204
+ for chain, rules in chain_rules.items():
205
+ if chain != "inline2":
206
+ self[chain].ruler.enableOnly(rules)
207
+ self.inline.ruler2.enableOnly(chain_rules["inline2"])
208
+
209
+ def add_render_rule(self, name: str, function: Callable, fmt: str = "html") -> None:
210
+ """Add a rule for rendering a particular Token type.
211
+
212
+ Only applied when ``renderer.__output__ == fmt``
213
+ """
214
+ if self.renderer.__output__ == fmt:
215
+ self.renderer.rules[name] = function.__get__(self.renderer) # type: ignore
216
+
217
+ def use(self, plugin: Callable, *params, **options) -> MarkdownIt:
218
+ """Load specified plugin with given params into current parser instance. (chainable)
219
+
220
+ It's just a sugar to call `plugin(md, params)` with curring.
221
+
222
+ Example::
223
+
224
+ def func(tokens, idx):
225
+ tokens[idx].content = tokens[idx].content.replace('foo', 'bar')
226
+ md = MarkdownIt().use(plugin, 'foo_replace', 'text', func)
227
+
228
+ """
229
+ plugin(self, *params, **options)
230
+ return self
231
+
232
+ def parse(self, src: str, env: MutableMapping | None = None) -> list[Token]:
233
+ """Parse the source string to a token stream
234
+
235
+ :param src: source string
236
+ :param env: environment sandbox
237
+
238
+ Parse input string and return list of block tokens (special token type
239
+ "inline" will contain list of inline tokens).
240
+
241
+ `env` is used to pass data between "distributed" rules and return additional
242
+ metadata like reference info, needed for the renderer. It also can be used to
243
+ inject data in specific cases. Usually, you will be ok to pass `{}`,
244
+ and then pass updated object to renderer.
245
+ """
246
+ env = {} if env is None else env
247
+ if not isinstance(env, MutableMapping):
248
+ raise TypeError(f"Input data should be a MutableMapping, not {type(env)}")
249
+ if not isinstance(src, str):
250
+ raise TypeError(f"Input data should be a string, not {type(src)}")
251
+ state = StateCore(src, self, env)
252
+ self.core.process(state)
253
+ return state.tokens
254
+
255
+ def render(self, src: str, env: MutableMapping | None = None) -> Any:
256
+ """Render markdown string into html. It does all magic for you :).
257
+
258
+ :param src: source string
259
+ :param env: environment sandbox
260
+ :returns: The output of the loaded renderer
261
+
262
+ `env` can be used to inject additional metadata (`{}` by default).
263
+ But you will not need it with high probability. See also comment
264
+ in [[MarkdownIt.parse]].
265
+ """
266
+ env = {} if env is None else env
267
+ return self.renderer.render(self.parse(src, env), self.options, env)
268
+
269
+ def parseInline(self, src: str, env: MutableMapping | None = None) -> list[Token]:
270
+ """The same as [[MarkdownIt.parse]] but skip all block rules.
271
+
272
+ :param src: source string
273
+ :param env: environment sandbox
274
+
275
+ It returns the
276
+ block tokens list with the single `inline` element, containing parsed inline
277
+ tokens in `children` property. Also updates `env` object.
278
+ """
279
+ env = {} if env is None else env
280
+ if not isinstance(env, MutableMapping):
281
+ raise TypeError(f"Input data should be an MutableMapping, not {type(env)}")
282
+ if not isinstance(src, str):
283
+ raise TypeError(f"Input data should be a string, not {type(src)}")
284
+ state = StateCore(src, self, env)
285
+ state.inlineMode = True
286
+ self.core.process(state)
287
+ return state.tokens
288
+
289
+ def renderInline(self, src: str, env: MutableMapping | None = None) -> Any:
290
+ """Similar to [[MarkdownIt.render]] but for single paragraph content.
291
+
292
+ :param src: source string
293
+ :param env: environment sandbox
294
+
295
+ Similar to [[MarkdownIt.render]] but for single paragraph content. Result
296
+ will NOT be wrapped into `<p>` tags.
297
+ """
298
+ env = {} if env is None else env
299
+ return self.renderer.render(self.parseInline(src, env), self.options, env)
300
+
301
+ # link methods
302
+
303
+ def validateLink(self, url: str) -> bool:
304
+ """Validate if the URL link is allowed in output.
305
+
306
+ This validator can prohibit more than really needed to prevent XSS.
307
+ It's a tradeoff to keep code simple and to be secure by default.
308
+
309
+ Note: the url should be normalized at this point, and existing entities decoded.
310
+ """
311
+ return normalize_url.validateLink(url)
312
+
313
+ def normalizeLink(self, url: str) -> str:
314
+ """Normalize destination URLs in links
315
+
316
+ ::
317
+
318
+ [label]: destination 'title'
319
+ ^^^^^^^^^^^
320
+ """
321
+ return normalize_url.normalizeLink(url)
322
+
323
+ def normalizeLinkText(self, link: str) -> str:
324
+ """Normalize autolink content
325
+
326
+ ::
327
+
328
+ <destination>
329
+ ~~~~~~~~~~~
330
+ """
331
+ return normalize_url.normalizeLinkText(link)
parrot/lib/python3.10/site-packages/markdown_it/parser_block.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Block-level tokenizer."""
2
+ from __future__ import annotations
3
+
4
+ import logging
5
+
6
+ from . import rules_block
7
+ from .ruler import Ruler
8
+ from .rules_block.state_block import StateBlock
9
+ from .token import Token
10
+
11
+ LOGGER = logging.getLogger(__name__)
12
+
13
+
14
+ _rules: list[tuple] = [
15
+ # First 2 params - rule name & source. Secondary array - list of rules,
16
+ # which can be terminated by this one.
17
+ ("table", rules_block.table, ["paragraph", "reference"]),
18
+ ("code", rules_block.code),
19
+ ("fence", rules_block.fence, ["paragraph", "reference", "blockquote", "list"]),
20
+ (
21
+ "blockquote",
22
+ rules_block.blockquote,
23
+ ["paragraph", "reference", "blockquote", "list"],
24
+ ),
25
+ ("hr", rules_block.hr, ["paragraph", "reference", "blockquote", "list"]),
26
+ ("list", rules_block.list_block, ["paragraph", "reference", "blockquote"]),
27
+ ("reference", rules_block.reference),
28
+ ("html_block", rules_block.html_block, ["paragraph", "reference", "blockquote"]),
29
+ ("heading", rules_block.heading, ["paragraph", "reference", "blockquote"]),
30
+ ("lheading", rules_block.lheading),
31
+ ("paragraph", rules_block.paragraph),
32
+ ]
33
+
34
+
35
+ class ParserBlock:
36
+ """
37
+ ParserBlock#ruler -> Ruler
38
+
39
+ [[Ruler]] instance. Keep configuration of block rules.
40
+ """
41
+
42
+ def __init__(self):
43
+ self.ruler = Ruler()
44
+ for data in _rules:
45
+ name = data[0]
46
+ rule = data[1]
47
+ self.ruler.push(name, rule, {"alt": data[2] if len(data) > 2 else []})
48
+
49
+ def tokenize(
50
+ self, state: StateBlock, startLine: int, endLine: int, silent: bool = False
51
+ ) -> None:
52
+ """Generate tokens for input range."""
53
+ rules = self.ruler.getRules("")
54
+ line = startLine
55
+ maxNesting = state.md.options.maxNesting
56
+ hasEmptyLines = False
57
+
58
+ while line < endLine:
59
+ state.line = line = state.skipEmptyLines(line)
60
+ if line >= endLine:
61
+ break
62
+ if state.sCount[line] < state.blkIndent:
63
+ # Termination condition for nested calls.
64
+ # Nested calls currently used for blockquotes & lists
65
+ break
66
+ if state.level >= maxNesting:
67
+ # If nesting level exceeded - skip tail to the end.
68
+ # That's not ordinary situation and we should not care about content.
69
+ state.line = endLine
70
+ break
71
+
72
+ # Try all possible rules.
73
+ # On success, rule should:
74
+ # - update `state.line`
75
+ # - update `state.tokens`
76
+ # - return True
77
+ for rule in rules:
78
+ if rule(state, line, endLine, False):
79
+ break
80
+
81
+ # set state.tight if we had an empty line before current tag
82
+ # i.e. latest empty line should not count
83
+ state.tight = not hasEmptyLines
84
+
85
+ line = state.line
86
+
87
+ # paragraph might "eat" one newline after it in nested lists
88
+ if (line - 1) < endLine and state.isEmpty(line - 1):
89
+ hasEmptyLines = True
90
+
91
+ if line < endLine and state.isEmpty(line):
92
+ hasEmptyLines = True
93
+ line += 1
94
+ state.line = line
95
+
96
+ def parse(
97
+ self,
98
+ src: str,
99
+ md,
100
+ env,
101
+ outTokens: list[Token],
102
+ ords: tuple[int, ...] | None = None,
103
+ ) -> list[Token] | None:
104
+ """Process input string and push block tokens into `outTokens`."""
105
+ if not src:
106
+ return None
107
+ state = StateBlock(src, md, env, outTokens, ords)
108
+ self.tokenize(state, state.line, state.lineMax)
109
+ return state.tokens
parrot/lib/python3.10/site-packages/markdown_it/parser_core.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ * class Core
3
+ *
4
+ * Top-level rules executor. Glues block/inline parsers and does intermediate
5
+ * transformations.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ from .ruler import RuleFunc, Ruler
10
+ from .rules_core import block, inline, linkify, normalize, replace, smartquotes
11
+ from .rules_core.state_core import StateCore
12
+
13
+ _rules: list[tuple[str, RuleFunc]] = [
14
+ ("normalize", normalize),
15
+ ("block", block),
16
+ ("inline", inline),
17
+ ("linkify", linkify),
18
+ ("replacements", replace),
19
+ ("smartquotes", smartquotes),
20
+ ]
21
+
22
+
23
+ class ParserCore:
24
+ def __init__(self):
25
+ self.ruler = Ruler()
26
+ for name, rule in _rules:
27
+ self.ruler.push(name, rule)
28
+
29
+ def process(self, state: StateCore) -> None:
30
+ """Executes core chain rules."""
31
+ for rule in self.ruler.getRules(""):
32
+ rule(state)
parrot/lib/python3.10/site-packages/markdown_it/parser_inline.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tokenizes paragraph content.
2
+ """
3
+ from __future__ import annotations
4
+
5
+ from . import rules_inline
6
+ from .ruler import RuleFunc, Ruler
7
+ from .rules_inline.state_inline import StateInline
8
+ from .token import Token
9
+
10
+ # Parser rules
11
+ _rules: list[tuple[str, RuleFunc]] = [
12
+ ("text", rules_inline.text),
13
+ ("newline", rules_inline.newline),
14
+ ("escape", rules_inline.escape),
15
+ ("backticks", rules_inline.backtick),
16
+ ("strikethrough", rules_inline.strikethrough.tokenize),
17
+ ("emphasis", rules_inline.emphasis.tokenize),
18
+ ("link", rules_inline.link),
19
+ ("image", rules_inline.image),
20
+ ("autolink", rules_inline.autolink),
21
+ ("html_inline", rules_inline.html_inline),
22
+ ("entity", rules_inline.entity),
23
+ ]
24
+
25
+ _rules2: list[tuple[str, RuleFunc]] = [
26
+ ("balance_pairs", rules_inline.link_pairs),
27
+ ("strikethrough", rules_inline.strikethrough.postProcess),
28
+ ("emphasis", rules_inline.emphasis.postProcess),
29
+ ("text_collapse", rules_inline.text_collapse),
30
+ ]
31
+
32
+
33
+ class ParserInline:
34
+ def __init__(self):
35
+ self.ruler = Ruler()
36
+ for name, rule in _rules:
37
+ self.ruler.push(name, rule)
38
+ # Second ruler used for post-processing (e.g. in emphasis-like rules)
39
+ self.ruler2 = Ruler()
40
+ for name, rule2 in _rules2:
41
+ self.ruler2.push(name, rule2)
42
+
43
+ def skipToken(self, state: StateInline) -> None:
44
+ """Skip single token by running all rules in validation mode;
45
+ returns `True` if any rule reported success
46
+ """
47
+ ok = False
48
+ pos = state.pos
49
+ rules = self.ruler.getRules("")
50
+ maxNesting = state.md.options["maxNesting"]
51
+ cache = state.cache
52
+
53
+ if pos in cache:
54
+ state.pos = cache[pos]
55
+ return
56
+
57
+ if state.level < maxNesting:
58
+ for rule in rules:
59
+ # Increment state.level and decrement it later to limit recursion.
60
+ # It's harmless to do here, because no tokens are created.
61
+ # But ideally, we'd need a separate private state variable for this purpose.
62
+ state.level += 1
63
+ ok = rule(state, True)
64
+ state.level -= 1
65
+ if ok:
66
+ break
67
+ else:
68
+ # Too much nesting, just skip until the end of the paragraph.
69
+ #
70
+ # NOTE: this will cause links to behave incorrectly in the following case,
71
+ # when an amount of `[` is exactly equal to `maxNesting + 1`:
72
+ #
73
+ # [[[[[[[[[[[[[[[[[[[[[foo]()
74
+ #
75
+ # TODO: remove this workaround when CM standard will allow nested links
76
+ # (we can replace it by preventing links from being parsed in
77
+ # validation mode)
78
+ #
79
+ state.pos = state.posMax
80
+
81
+ if not ok:
82
+ state.pos += 1
83
+ cache[pos] = state.pos
84
+
85
+ def tokenize(self, state: StateInline) -> None:
86
+ """Generate tokens for input range."""
87
+ ok = False
88
+ rules = self.ruler.getRules("")
89
+ end = state.posMax
90
+ maxNesting = state.md.options["maxNesting"]
91
+
92
+ while state.pos < end:
93
+ # Try all possible rules.
94
+ # On success, rule should:
95
+ #
96
+ # - update `state.pos`
97
+ # - update `state.tokens`
98
+ # - return true
99
+
100
+ if state.level < maxNesting:
101
+ for rule in rules:
102
+ ok = rule(state, False)
103
+ if ok:
104
+ break
105
+
106
+ if ok:
107
+ if state.pos >= end:
108
+ break
109
+ continue
110
+
111
+ state.pending += state.src[state.pos]
112
+ state.pos += 1
113
+
114
+ if state.pending:
115
+ state.pushPending()
116
+
117
+ def parse(self, src: str, md, env, tokens: list[Token]) -> list[Token]:
118
+ """Process input string and push inline tokens into `tokens`"""
119
+ state = StateInline(src, md, env, tokens)
120
+ self.tokenize(state)
121
+ rules2 = self.ruler2.getRules("")
122
+ for rule in rules2:
123
+ rule(state)
124
+ return state.tokens
parrot/lib/python3.10/site-packages/markdown_it/port.yaml ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ - package: markdown-it/markdown-it
2
+ version: 12.2.0
3
+ commit: 6e2de08a0b03d3d0dcc524b89710ce05f83a0283
4
+ date: Aug 2, 2021
5
+ notes:
6
+ - Rename variables that use python built-in names, e.g.
7
+ - `max` -> `maximum`
8
+ - `len` -> `length`
9
+ - `str` -> `string`
10
+ - |
11
+ Convert JS `for` loops to `while` loops
12
+ this is generally the main difference between the codes,
13
+ because in python you can't do e.g. `for {i=1;i<x;i++} {}`
14
+ - |
15
+ `env` is a common Python dictionary, and so does not have attribute access to keys,
16
+ as with JavaScript dictionaries.
17
+ `options` have attribute access only to core markdownit configuration options
18
+ - |
19
+ `Token.attrs` is a dictionary, instead of a list of lists.
20
+ Upstream the list format is only used to guarantee order: https://github.com/markdown-it/markdown-it/issues/142,
21
+ but in Python 3.7+ order of dictionaries is guaranteed.
22
+ One should anyhow use the `attrGet`, `attrSet`, `attrPush` and `attrJoin` methods
23
+ to manipulate `Token.attrs`, which have an identical signature to those upstream.
24
+ - Use python version of `charCodeAt`
25
+ - |
26
+ Reduce use of charCodeAt() by storing char codes in a srcCharCodes attribute for state
27
+ objects and sharing those whenever possible
28
+ This provides a significant performance boost
29
+ - |
30
+ In markdown_it/rules_block/reference.py,
31
+ record line range in state.env["references"] and add state.env["duplicate_refs"]
32
+ This is to allow renderers to report on issues regarding references
33
+ - |
34
+ The `MarkdownIt.__init__` signature is slightly different for updating options,
35
+ since you must always specify the config first, e.g.
36
+ use `MarkdownIt("commonmark", {"html": False})` instead of `MarkdownIt({"html": False})`
37
+ - The default configuration preset for `MarkdownIt` is "commonmark" not "default"
38
+ - Allow custom renderer to be passed to `MarkdownIt`
39
+ - |
40
+ change render method signatures
41
+ `func(tokens, idx, options, env, slf)` to
42
+ `func(self, tokens, idx, options, env)`
43
+ - |
44
+ Extensions add render methods by format
45
+ `MarkdownIt.add_render_rule(name, function, fmt="html")`,
46
+ rather than `MarkdownIt.renderer.rules[name] = function`
47
+ and renderers should declare a class property `__output__ = "html"`.
48
+ This allows for extensibility to more than just HTML renderers
49
+ - inline tokens in tables are assigned a map (this is helpful for propagation to children)
parrot/lib/python3.10/site-packages/markdown_it/presets/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __all__ = ("commonmark", "default", "zero", "js_default", "gfm_like")
2
+
3
+ from . import commonmark, default, zero
4
+
5
+ js_default = default
6
+
7
+
8
+ class gfm_like:
9
+ """GitHub Flavoured Markdown (GFM) like.
10
+
11
+ This adds the linkify, table and strikethrough components to CommmonMark.
12
+
13
+ Note, it lacks task-list items and raw HTML filtering,
14
+ to meet the the full GFM specification
15
+ (see https://github.github.com/gfm/#autolinks-extension-).
16
+ """
17
+
18
+ @staticmethod
19
+ def make():
20
+ config = commonmark.make()
21
+ config["components"]["core"]["rules"].append("linkify")
22
+ config["components"]["block"]["rules"].append("table")
23
+ config["components"]["inline"]["rules"].append("strikethrough")
24
+ config["components"]["inline"]["rules2"].append("strikethrough")
25
+ config["options"]["linkify"] = True
26
+ config["options"]["html"] = True
27
+ return config
parrot/lib/python3.10/site-packages/markdown_it/presets/__pycache__/default.cpython-310.pyc ADDED
Binary file (536 Bytes). View file
 
parrot/lib/python3.10/site-packages/markdown_it/presets/commonmark.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Commonmark default options.
2
+
3
+ This differs to presets.default,
4
+ primarily in that it allows HTML and does not enable components:
5
+
6
+ - block: table
7
+ - inline: strikethrough
8
+ """
9
+
10
+
11
+ def make():
12
+ return {
13
+ "options": {
14
+ "maxNesting": 20, # Internal protection, recursion limit
15
+ "html": True, # Enable HTML tags in source,
16
+ # this is just a shorthand for .enable(["html_inline", "html_block"])
17
+ # used by the linkify rule:
18
+ "linkify": False, # autoconvert URL-like texts to links
19
+ # used by the replacements and smartquotes rules
20
+ # Enable some language-neutral replacements + quotes beautification
21
+ "typographer": False,
22
+ # used by the smartquotes rule:
23
+ # Double + single quotes replacement pairs, when typographer enabled,
24
+ # and smartquotes on. Could be either a String or an Array.
25
+ #
26
+ # For example, you can use '«»„“' for Russian, '„“‚‘' for German,
27
+ # and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp).
28
+ "quotes": "\u201c\u201d\u2018\u2019", # /* “”‘’ */
29
+ # Renderer specific; these options are used directly in the HTML renderer
30
+ "xhtmlOut": True, # Use '/' to close single tags (<br />)
31
+ "breaks": False, # Convert '\n' in paragraphs into <br>
32
+ "langPrefix": "language-", # CSS language prefix for fenced blocks
33
+ # Highlighter function. Should return escaped HTML,
34
+ # or '' if the source string is not changed and should be escaped externally.
35
+ # If result starts with <pre... internal wrapper is skipped.
36
+ #
37
+ # function (/*str, lang, attrs*/) { return ''; }
38
+ #
39
+ "highlight": None,
40
+ },
41
+ "components": {
42
+ "core": {"rules": ["normalize", "block", "inline"]},
43
+ "block": {
44
+ "rules": [
45
+ "blockquote",
46
+ "code",
47
+ "fence",
48
+ "heading",
49
+ "hr",
50
+ "html_block",
51
+ "lheading",
52
+ "list",
53
+ "reference",
54
+ "paragraph",
55
+ ]
56
+ },
57
+ "inline": {
58
+ "rules": [
59
+ "autolink",
60
+ "backticks",
61
+ "emphasis",
62
+ "entity",
63
+ "escape",
64
+ "html_inline",
65
+ "image",
66
+ "link",
67
+ "newline",
68
+ "text",
69
+ ],
70
+ "rules2": ["balance_pairs", "emphasis", "text_collapse"],
71
+ },
72
+ },
73
+ }
parrot/lib/python3.10/site-packages/markdown_it/presets/default.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """markdown-it default options."""
2
+
3
+
4
+ def make():
5
+ return {
6
+ "options": {
7
+ "maxNesting": 100, # Internal protection, recursion limit
8
+ "html": False, # Enable HTML tags in source
9
+ # this is just a shorthand for .disable(["html_inline", "html_block"])
10
+ # used by the linkify rule:
11
+ "linkify": False, # autoconvert URL-like texts to links
12
+ # used by the replacements and smartquotes rules:
13
+ # Enable some language-neutral replacements + quotes beautification
14
+ "typographer": False,
15
+ # used by the smartquotes rule:
16
+ # Double + single quotes replacement pairs, when typographer enabled,
17
+ # and smartquotes on. Could be either a String or an Array.
18
+ # For example, you can use '«»„“' for Russian, '„“‚‘' for German,
19
+ # and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp).
20
+ "quotes": "\u201c\u201d\u2018\u2019", # /* “”‘’ */
21
+ # Renderer specific; these options are used directly in the HTML renderer
22
+ "xhtmlOut": False, # Use '/' to close single tags (<br />)
23
+ "breaks": False, # Convert '\n' in paragraphs into <br>
24
+ "langPrefix": "language-", # CSS language prefix for fenced blocks
25
+ # Highlighter function. Should return escaped HTML,
26
+ # or '' if the source string is not changed and should be escaped externally.
27
+ # If result starts with <pre... internal wrapper is skipped.
28
+ #
29
+ # function (/*str, lang, attrs*/) { return ''; }
30
+ #
31
+ "highlight": None,
32
+ },
33
+ "components": {"core": {}, "block": {}, "inline": {}},
34
+ }
parrot/lib/python3.10/site-packages/markdown_it/presets/zero.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ "Zero" preset, with nothing enabled. Useful for manual configuring of simple
3
+ modes. For example, to parse bold/italic only.
4
+ """
5
+
6
+
7
+ def make():
8
+ return {
9
+ "options": {
10
+ "maxNesting": 20, # Internal protection, recursion limit
11
+ "html": False, # Enable HTML tags in source
12
+ # this is just a shorthand for .disable(["html_inline", "html_block"])
13
+ # used by the linkify rule:
14
+ "linkify": False, # autoconvert URL-like texts to links
15
+ # used by the replacements and smartquotes rules:
16
+ # Enable some language-neutral replacements + quotes beautification
17
+ "typographer": False,
18
+ # used by the smartquotes rule:
19
+ # Double + single quotes replacement pairs, when typographer enabled,
20
+ # and smartquotes on. Could be either a String or an Array.
21
+ # For example, you can use '«»„“' for Russian, '„“‚‘' for German,
22
+ # and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp).
23
+ "quotes": "\u201c\u201d\u2018\u2019", # /* “”‘’ */
24
+ # Renderer specific; these options are used directly in the HTML renderer
25
+ "xhtmlOut": False, # Use '/' to close single tags (<br />)
26
+ "breaks": False, # Convert '\n' in paragraphs into <br>
27
+ "langPrefix": "language-", # CSS language prefix for fenced blocks
28
+ # Highlighter function. Should return escaped HTML,
29
+ # or '' if the source string is not changed and should be escaped externally.
30
+ # If result starts with <pre... internal wrapper is skipped.
31
+ # function (/*str, lang, attrs*/) { return ''; }
32
+ "highlight": None,
33
+ },
34
+ "components": {
35
+ "core": {"rules": ["normalize", "block", "inline"]},
36
+ "block": {"rules": ["paragraph"]},
37
+ "inline": {"rules": ["text"], "rules2": ["balance_pairs", "text_collapse"]},
38
+ },
39
+ }
parrot/lib/python3.10/site-packages/markdown_it/py.typed ADDED
@@ -0,0 +1 @@
 
 
1
+ # Marker file for PEP 561
parrot/lib/python3.10/site-packages/markdown_it/renderer.py ADDED
@@ -0,0 +1,334 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ class Renderer
3
+
4
+ Generates HTML from parsed token stream. Each instance has independent
5
+ copy of rules. Those can be rewritten with ease. Also, you can add new
6
+ rules if you create plugin and adds new token types.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import MutableMapping, Sequence
11
+ import inspect
12
+ from typing import Any, ClassVar
13
+
14
+ from .common.utils import escapeHtml, unescapeAll
15
+ from .token import Token
16
+ from .utils import OptionsDict
17
+
18
+ try:
19
+ from typing import Protocol
20
+ except ImportError: # Python <3.8 doesn't have `Protocol` in the stdlib
21
+ from typing_extensions import Protocol # type: ignore
22
+
23
+
24
+ class RendererProtocol(Protocol):
25
+ __output__: ClassVar[str]
26
+
27
+ def render(
28
+ self, tokens: Sequence[Token], options: OptionsDict, env: MutableMapping
29
+ ) -> Any:
30
+ ...
31
+
32
+
33
+ class RendererHTML(RendererProtocol):
34
+ """Contains render rules for tokens. Can be updated and extended.
35
+
36
+ Example:
37
+
38
+ Each rule is called as independent static function with fixed signature:
39
+
40
+ ::
41
+
42
+ class Renderer:
43
+ def token_type_name(self, tokens, idx, options, env) {
44
+ # ...
45
+ return renderedHTML
46
+
47
+ ::
48
+
49
+ class CustomRenderer(RendererHTML):
50
+ def strong_open(self, tokens, idx, options, env):
51
+ return '<b>'
52
+ def strong_close(self, tokens, idx, options, env):
53
+ return '</b>'
54
+
55
+ md = MarkdownIt(renderer_cls=CustomRenderer)
56
+
57
+ result = md.render(...)
58
+
59
+ See https://github.com/markdown-it/markdown-it/blob/master/lib/renderer.js
60
+ for more details and examples.
61
+ """
62
+
63
+ __output__ = "html"
64
+
65
+ def __init__(self, parser=None):
66
+ self.rules = {
67
+ k: v
68
+ for k, v in inspect.getmembers(self, predicate=inspect.ismethod)
69
+ if not (k.startswith("render") or k.startswith("_"))
70
+ }
71
+
72
+ def render(
73
+ self, tokens: Sequence[Token], options: OptionsDict, env: MutableMapping
74
+ ) -> str:
75
+ """Takes token stream and generates HTML.
76
+
77
+ :param tokens: list on block tokens to render
78
+ :param options: params of parser instance
79
+ :param env: additional data from parsed input
80
+
81
+ """
82
+ result = ""
83
+
84
+ for i, token in enumerate(tokens):
85
+ if token.type == "inline":
86
+ if token.children:
87
+ result += self.renderInline(token.children, options, env)
88
+ elif token.type in self.rules:
89
+ result += self.rules[token.type](tokens, i, options, env)
90
+ else:
91
+ result += self.renderToken(tokens, i, options, env)
92
+
93
+ return result
94
+
95
+ def renderInline(
96
+ self, tokens: Sequence[Token], options: OptionsDict, env: MutableMapping
97
+ ) -> str:
98
+ """The same as ``render``, but for single token of `inline` type.
99
+
100
+ :param tokens: list on block tokens to render
101
+ :param options: params of parser instance
102
+ :param env: additional data from parsed input (references, for example)
103
+ """
104
+ result = ""
105
+
106
+ for i, token in enumerate(tokens):
107
+ if token.type in self.rules:
108
+ result += self.rules[token.type](tokens, i, options, env)
109
+ else:
110
+ result += self.renderToken(tokens, i, options, env)
111
+
112
+ return result
113
+
114
+ def renderToken(
115
+ self,
116
+ tokens: Sequence[Token],
117
+ idx: int,
118
+ options: OptionsDict,
119
+ env: MutableMapping,
120
+ ) -> str:
121
+ """Default token renderer.
122
+
123
+ Can be overridden by custom function
124
+
125
+ :param idx: token index to render
126
+ :param options: params of parser instance
127
+ """
128
+ result = ""
129
+ needLf = False
130
+ token = tokens[idx]
131
+
132
+ # Tight list paragraphs
133
+ if token.hidden:
134
+ return ""
135
+
136
+ # Insert a newline between hidden paragraph and subsequent opening
137
+ # block-level tag.
138
+ #
139
+ # For example, here we should insert a newline before blockquote:
140
+ # - a
141
+ # >
142
+ #
143
+ if token.block and token.nesting != -1 and idx and tokens[idx - 1].hidden:
144
+ result += "\n"
145
+
146
+ # Add token name, e.g. `<img`
147
+ result += ("</" if token.nesting == -1 else "<") + token.tag
148
+
149
+ # Encode attributes, e.g. `<img src="foo"`
150
+ result += self.renderAttrs(token)
151
+
152
+ # Add a slash for self-closing tags, e.g. `<img src="foo" /`
153
+ if token.nesting == 0 and options["xhtmlOut"]:
154
+ result += " /"
155
+
156
+ # Check if we need to add a newline after this tag
157
+ if token.block:
158
+ needLf = True
159
+
160
+ if token.nesting == 1:
161
+ if idx + 1 < len(tokens):
162
+ nextToken = tokens[idx + 1]
163
+
164
+ if nextToken.type == "inline" or nextToken.hidden:
165
+ # Block-level tag containing an inline tag.
166
+ #
167
+ needLf = False
168
+
169
+ elif nextToken.nesting == -1 and nextToken.tag == token.tag:
170
+ # Opening tag + closing tag of the same type. E.g. `<li></li>`.
171
+ #
172
+ needLf = False
173
+
174
+ result += ">\n" if needLf else ">"
175
+
176
+ return result
177
+
178
+ @staticmethod
179
+ def renderAttrs(token: Token) -> str:
180
+ """Render token attributes to string."""
181
+ result = ""
182
+
183
+ for key, value in token.attrItems():
184
+ result += " " + escapeHtml(key) + '="' + escapeHtml(str(value)) + '"'
185
+
186
+ return result
187
+
188
+ def renderInlineAsText(
189
+ self,
190
+ tokens: Sequence[Token] | None,
191
+ options: OptionsDict,
192
+ env: MutableMapping,
193
+ ) -> str:
194
+ """Special kludge for image `alt` attributes to conform CommonMark spec.
195
+
196
+ Don't try to use it! Spec requires to show `alt` content with stripped markup,
197
+ instead of simple escaping.
198
+
199
+ :param tokens: list on block tokens to render
200
+ :param options: params of parser instance
201
+ :param env: additional data from parsed input
202
+ """
203
+ result = ""
204
+
205
+ for token in tokens or []:
206
+ if token.type == "text":
207
+ result += token.content
208
+ elif token.type == "image":
209
+ if token.children:
210
+ result += self.renderInlineAsText(token.children, options, env)
211
+ elif token.type == "softbreak":
212
+ result += "\n"
213
+
214
+ return result
215
+
216
+ ###################################################
217
+
218
+ def code_inline(self, tokens: Sequence[Token], idx: int, options, env) -> str:
219
+ token = tokens[idx]
220
+ return (
221
+ "<code"
222
+ + self.renderAttrs(token)
223
+ + ">"
224
+ + escapeHtml(tokens[idx].content)
225
+ + "</code>"
226
+ )
227
+
228
+ def code_block(
229
+ self,
230
+ tokens: Sequence[Token],
231
+ idx: int,
232
+ options: OptionsDict,
233
+ env: MutableMapping,
234
+ ) -> str:
235
+ token = tokens[idx]
236
+
237
+ return (
238
+ "<pre"
239
+ + self.renderAttrs(token)
240
+ + "><code>"
241
+ + escapeHtml(tokens[idx].content)
242
+ + "</code></pre>\n"
243
+ )
244
+
245
+ def fence(
246
+ self,
247
+ tokens: Sequence[Token],
248
+ idx: int,
249
+ options: OptionsDict,
250
+ env: MutableMapping,
251
+ ) -> str:
252
+ token = tokens[idx]
253
+ info = unescapeAll(token.info).strip() if token.info else ""
254
+ langName = ""
255
+ langAttrs = ""
256
+
257
+ if info:
258
+ arr = info.split(maxsplit=1)
259
+ langName = arr[0]
260
+ if len(arr) == 2:
261
+ langAttrs = arr[1]
262
+
263
+ if options.highlight:
264
+ highlighted = options.highlight(
265
+ token.content, langName, langAttrs
266
+ ) or escapeHtml(token.content)
267
+ else:
268
+ highlighted = escapeHtml(token.content)
269
+
270
+ if highlighted.startswith("<pre"):
271
+ return highlighted + "\n"
272
+
273
+ # If language exists, inject class gently, without modifying original token.
274
+ # May be, one day we will add .deepClone() for token and simplify this part, but
275
+ # now we prefer to keep things local.
276
+ if info:
277
+ # Fake token just to render attributes
278
+ tmpToken = Token(type="", tag="", nesting=0, attrs=token.attrs.copy())
279
+ tmpToken.attrJoin("class", options.langPrefix + langName)
280
+
281
+ return (
282
+ "<pre><code"
283
+ + self.renderAttrs(tmpToken)
284
+ + ">"
285
+ + highlighted
286
+ + "</code></pre>\n"
287
+ )
288
+
289
+ return (
290
+ "<pre><code"
291
+ + self.renderAttrs(token)
292
+ + ">"
293
+ + highlighted
294
+ + "</code></pre>\n"
295
+ )
296
+
297
+ def image(
298
+ self,
299
+ tokens: Sequence[Token],
300
+ idx: int,
301
+ options: OptionsDict,
302
+ env: MutableMapping,
303
+ ) -> str:
304
+ token = tokens[idx]
305
+
306
+ # "alt" attr MUST be set, even if empty. Because it's mandatory and
307
+ # should be placed on proper position for tests.
308
+ if token.children:
309
+ token.attrSet("alt", self.renderInlineAsText(token.children, options, env))
310
+ else:
311
+ token.attrSet("alt", "")
312
+
313
+ return self.renderToken(tokens, idx, options, env)
314
+
315
+ def hardbreak(
316
+ self, tokens: Sequence[Token], idx: int, options: OptionsDict, *args
317
+ ) -> str:
318
+ return "<br />\n" if options.xhtmlOut else "<br>\n"
319
+
320
+ def softbreak(
321
+ self, tokens: Sequence[Token], idx: int, options: OptionsDict, *args
322
+ ) -> str:
323
+ return (
324
+ ("<br />\n" if options.xhtmlOut else "<br>\n") if options.breaks else "\n"
325
+ )
326
+
327
+ def text(self, tokens: Sequence[Token], idx: int, *args) -> str:
328
+ return escapeHtml(tokens[idx].content)
329
+
330
+ def html_block(self, tokens: Sequence[Token], idx: int, *args) -> str:
331
+ return tokens[idx].content
332
+
333
+ def html_inline(self, tokens: Sequence[Token], idx: int, *args) -> str:
334
+ return tokens[idx].content
parrot/lib/python3.10/site-packages/markdown_it/ruler.py ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ class Ruler
3
+
4
+ Helper class, used by [[MarkdownIt#core]], [[MarkdownIt#block]] and
5
+ [[MarkdownIt#inline]] to manage sequences of functions (rules):
6
+
7
+ - keep rules in defined order
8
+ - assign the name to each rule
9
+ - enable/disable rules
10
+ - add/replace rules
11
+ - allow assign rules to additional named chains (in the same)
12
+ - caching lists of active rules
13
+
14
+ You will not need use this class directly until write plugins. For simple
15
+ rules control use [[MarkdownIt.disable]], [[MarkdownIt.enable]] and
16
+ [[MarkdownIt.use]].
17
+ """
18
+ from __future__ import annotations
19
+
20
+ from collections.abc import Callable, Iterable, MutableMapping
21
+ from dataclasses import dataclass, field
22
+ from typing import TYPE_CHECKING
23
+
24
+ from markdown_it._compat import DATACLASS_KWARGS
25
+
26
+ if TYPE_CHECKING:
27
+ from markdown_it import MarkdownIt
28
+
29
+
30
+ class StateBase:
31
+ srcCharCode: tuple[int, ...]
32
+
33
+ def __init__(self, src: str, md: MarkdownIt, env: MutableMapping):
34
+ self.src = src
35
+ self.env = env
36
+ self.md = md
37
+
38
+ @property
39
+ def src(self) -> str:
40
+ return self._src
41
+
42
+ @src.setter
43
+ def src(self, value: str) -> None:
44
+ self._src = value
45
+ self.srcCharCode = tuple(ord(c) for c in self.src)
46
+
47
+
48
+ # The first positional arg is always a subtype of `StateBase`. Other
49
+ # arguments may or may not exist, based on the rule's type (block,
50
+ # core, inline). Return type is either `None` or `bool` based on the
51
+ # rule's type.
52
+ RuleFunc = Callable
53
+
54
+
55
+ @dataclass(**DATACLASS_KWARGS)
56
+ class Rule:
57
+ name: str
58
+ enabled: bool
59
+ fn: RuleFunc = field(repr=False)
60
+ alt: list[str]
61
+
62
+
63
+ class Ruler:
64
+ def __init__(self):
65
+ # List of added rules.
66
+ self.__rules__: list[Rule] = []
67
+ # Cached rule chains.
68
+ # First level - chain name, '' for default.
69
+ # Second level - diginal anchor for fast filtering by charcodes.
70
+ self.__cache__: dict[str, list[RuleFunc]] | None = None
71
+
72
+ def __find__(self, name: str) -> int:
73
+ """Find rule index by name"""
74
+ for i, rule in enumerate(self.__rules__):
75
+ if rule.name == name:
76
+ return i
77
+ return -1
78
+
79
+ def __compile__(self) -> None:
80
+ """Build rules lookup cache"""
81
+ chains = {""}
82
+ # collect unique names
83
+ for rule in self.__rules__:
84
+ if not rule.enabled:
85
+ continue
86
+ for name in rule.alt:
87
+ chains.add(name)
88
+ self.__cache__ = {}
89
+ for chain in chains:
90
+ self.__cache__[chain] = []
91
+ for rule in self.__rules__:
92
+ if not rule.enabled:
93
+ continue
94
+ if chain and (chain not in rule.alt):
95
+ continue
96
+ self.__cache__[chain].append(rule.fn)
97
+
98
+ def at(self, ruleName: str, fn: RuleFunc, options=None):
99
+ """Replace rule by name with new function & options.
100
+
101
+ :param ruleName: rule name to replace.
102
+ :param fn: new rule function.
103
+ :param options: new rule options (not mandatory).
104
+ :raises: KeyError if name not found
105
+ """
106
+ index = self.__find__(ruleName)
107
+ options = options or {}
108
+ if index == -1:
109
+ raise KeyError(f"Parser rule not found: {ruleName}")
110
+ self.__rules__[index].fn = fn
111
+ self.__rules__[index].alt = options.get("alt", [])
112
+ self.__cache__ = None
113
+
114
+ def before(self, beforeName: str, ruleName: str, fn: RuleFunc, options=None):
115
+ """Add new rule to chain before one with given name.
116
+
117
+ :param beforeName: new rule will be added before this one.
118
+ :param ruleName: new rule will be added before this one.
119
+ :param fn: new rule function.
120
+ :param options: new rule options (not mandatory).
121
+ :raises: KeyError if name not found
122
+ """
123
+ index = self.__find__(beforeName)
124
+ options = options or {}
125
+ if index == -1:
126
+ raise KeyError(f"Parser rule not found: {beforeName}")
127
+ self.__rules__.insert(index, Rule(ruleName, True, fn, options.get("alt", [])))
128
+ self.__cache__ = None
129
+
130
+ def after(self, afterName: str, ruleName: str, fn: RuleFunc, options=None):
131
+ """Add new rule to chain after one with given name.
132
+
133
+ :param afterName: new rule will be added after this one.
134
+ :param ruleName: new rule will be added after this one.
135
+ :param fn: new rule function.
136
+ :param options: new rule options (not mandatory).
137
+ :raises: KeyError if name not found
138
+ """
139
+ index = self.__find__(afterName)
140
+ options = options or {}
141
+ if index == -1:
142
+ raise KeyError(f"Parser rule not found: {afterName}")
143
+ self.__rules__.insert(
144
+ index + 1, Rule(ruleName, True, fn, options.get("alt", []))
145
+ )
146
+ self.__cache__ = None
147
+
148
+ def push(self, ruleName: str, fn: RuleFunc, options=None):
149
+ """Push new rule to the end of chain.
150
+
151
+ :param ruleName: new rule will be added to the end of chain.
152
+ :param fn: new rule function.
153
+ :param options: new rule options (not mandatory).
154
+
155
+ """
156
+ self.__rules__.append(Rule(ruleName, True, fn, (options or {}).get("alt", [])))
157
+ self.__cache__ = None
158
+
159
+ def enable(self, names: str | Iterable[str], ignoreInvalid: bool = False):
160
+ """Enable rules with given names.
161
+
162
+ :param names: name or list of rule names to enable.
163
+ :param ignoreInvalid: ignore errors when rule not found
164
+ :raises: KeyError if name not found and not ignoreInvalid
165
+ :return: list of found rule names
166
+ """
167
+ if isinstance(names, str):
168
+ names = [names]
169
+ result = []
170
+ for name in names:
171
+ idx = self.__find__(name)
172
+ if (idx < 0) and ignoreInvalid:
173
+ continue
174
+ if (idx < 0) and not ignoreInvalid:
175
+ raise KeyError(f"Rules manager: invalid rule name {name}")
176
+ self.__rules__[idx].enabled = True
177
+ result.append(name)
178
+ self.__cache__ = None
179
+ return result
180
+
181
+ def enableOnly(self, names: str | Iterable[str], ignoreInvalid: bool = False):
182
+ """Enable rules with given names, and disable everything else.
183
+
184
+ :param names: name or list of rule names to enable.
185
+ :param ignoreInvalid: ignore errors when rule not found
186
+ :raises: KeyError if name not found and not ignoreInvalid
187
+ :return: list of found rule names
188
+ """
189
+ if isinstance(names, str):
190
+ names = [names]
191
+ for rule in self.__rules__:
192
+ rule.enabled = False
193
+ self.enable(names, ignoreInvalid)
194
+
195
+ def disable(self, names: str | Iterable[str], ignoreInvalid: bool = False):
196
+ """Disable rules with given names.
197
+
198
+ :param names: name or list of rule names to enable.
199
+ :param ignoreInvalid: ignore errors when rule not found
200
+ :raises: KeyError if name not found and not ignoreInvalid
201
+ :return: list of found rule names
202
+ """
203
+ if isinstance(names, str):
204
+ names = [names]
205
+ result = []
206
+ for name in names:
207
+ idx = self.__find__(name)
208
+ if (idx < 0) and ignoreInvalid:
209
+ continue
210
+ if (idx < 0) and not ignoreInvalid:
211
+ raise KeyError(f"Rules manager: invalid rule name {name}")
212
+ self.__rules__[idx].enabled = False
213
+ result.append(name)
214
+ self.__cache__ = None
215
+ return result
216
+
217
+ def getRules(self, chainName: str) -> list[RuleFunc]:
218
+ """Return array of active functions (rules) for given chain name.
219
+ It analyzes rules configuration, compiles caches if not exists and returns result.
220
+
221
+ Default chain name is `''` (empty string). It can't be skipped.
222
+ That's done intentionally, to keep signature monomorphic for high speed.
223
+
224
+ """
225
+ if self.__cache__ is None:
226
+ self.__compile__()
227
+ assert self.__cache__ is not None
228
+ # Chain can be empty, if rules disabled. But we still have to return Array.
229
+ return self.__cache__.get(chainName, []) or []
230
+
231
+ def get_all_rules(self) -> list[str]:
232
+ """Return all available rule names."""
233
+ return [r.name for r in self.__rules__]
234
+
235
+ def get_active_rules(self) -> list[str]:
236
+ """Return the active rule names."""
237
+ return [r.name for r in self.__rules__ if r.enabled]
parrot/lib/python3.10/site-packages/markdown_it/rules_inline/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __all__ = (
2
+ "StateInline",
3
+ "text",
4
+ "text_collapse",
5
+ "link_pairs",
6
+ "escape",
7
+ "newline",
8
+ "backtick",
9
+ "emphasis",
10
+ "image",
11
+ "link",
12
+ "autolink",
13
+ "entity",
14
+ "html_inline",
15
+ "strikethrough",
16
+ )
17
+ from . import emphasis, strikethrough
18
+ from .autolink import autolink
19
+ from .backticks import backtick
20
+ from .balance_pairs import link_pairs
21
+ from .entity import entity
22
+ from .escape import escape
23
+ from .html_inline import html_inline
24
+ from .image import image
25
+ from .link import link
26
+ from .newline import newline
27
+ from .state_inline import StateInline
28
+ from .text import text
29
+ from .text_collapse import text_collapse
parrot/lib/python3.10/site-packages/markdown_it/rules_inline/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (729 Bytes). View file
 
parrot/lib/python3.10/site-packages/markdown_it/rules_inline/__pycache__/autolink.cpython-310.pyc ADDED
Binary file (1.46 kB). View file
 
parrot/lib/python3.10/site-packages/markdown_it/rules_inline/__pycache__/backticks.cpython-310.pyc ADDED
Binary file (1.3 kB). View file