diff --git a/parrot/lib/python3.10/site-packages/imageio/__pycache__/__init__.cpython-310.pyc b/parrot/lib/python3.10/site-packages/imageio/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..524da5794611b913ce0bc129ce114814ddc502aa Binary files /dev/null and b/parrot/lib/python3.10/site-packages/imageio/__pycache__/__init__.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/imageio/__pycache__/__main__.cpython-310.pyc b/parrot/lib/python3.10/site-packages/imageio/__pycache__/__main__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..45c8eb5963ea10c6aca0f2c932ab357eb91bbde0 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/imageio/__pycache__/__main__.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/imageio/__pycache__/freeze.cpython-310.pyc b/parrot/lib/python3.10/site-packages/imageio/__pycache__/freeze.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..99c03985f1b53ad77d406704bd753d219b4eb29a Binary files /dev/null and b/parrot/lib/python3.10/site-packages/imageio/__pycache__/freeze.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/imageio/__pycache__/testing.cpython-310.pyc b/parrot/lib/python3.10/site-packages/imageio/__pycache__/testing.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bda1be5294b2ec766e52aea30edcb9b40bb79946 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/imageio/__pycache__/testing.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/imageio/__pycache__/typing.cpython-310.pyc b/parrot/lib/python3.10/site-packages/imageio/__pycache__/typing.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..49a4fa1ed0dd3f192a65798ae016db293ceb7ff9 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/imageio/__pycache__/typing.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/imageio/__pycache__/v2.cpython-310.pyc b/parrot/lib/python3.10/site-packages/imageio/__pycache__/v2.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a76b3c775729c14bc5cc9d0106c39e8a48bc2766 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/imageio/__pycache__/v2.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/imageio/__pycache__/v3.cpython-310.pyc b/parrot/lib/python3.10/site-packages/imageio/__pycache__/v3.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e3530db32bb33b36834b3c2fceb5db5c6ceddd5 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/imageio/__pycache__/v3.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/imageio/core/__pycache__/__init__.cpython-310.pyc b/parrot/lib/python3.10/site-packages/imageio/core/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e4ec7e976b90f6fac3300d0f48cff51efc51799a Binary files /dev/null and b/parrot/lib/python3.10/site-packages/imageio/core/__pycache__/__init__.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/imageio/core/__pycache__/fetching.cpython-310.pyc b/parrot/lib/python3.10/site-packages/imageio/core/__pycache__/fetching.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6aa35583bc634e9d9c004f8aea8d21c243a3688b Binary files /dev/null and b/parrot/lib/python3.10/site-packages/imageio/core/__pycache__/fetching.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/imageio/core/__pycache__/findlib.cpython-310.pyc b/parrot/lib/python3.10/site-packages/imageio/core/__pycache__/findlib.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7bb9cef78d537634607bda3eeea15f07c13c8931 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/imageio/core/__pycache__/findlib.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/imageio/core/__pycache__/format.cpython-310.pyc b/parrot/lib/python3.10/site-packages/imageio/core/__pycache__/format.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..14f0a99f969ee00eb78aa9b22fd099ae9ac31f52 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/imageio/core/__pycache__/format.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/imageio/core/__pycache__/imopen.cpython-310.pyc b/parrot/lib/python3.10/site-packages/imageio/core/__pycache__/imopen.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee0c335e69646a574f118f44cb46b6be65cd1a04 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/imageio/core/__pycache__/imopen.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/imageio/core/__pycache__/legacy_plugin_wrapper.cpython-310.pyc b/parrot/lib/python3.10/site-packages/imageio/core/__pycache__/legacy_plugin_wrapper.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0fb8fdbed55fb33acb0f55bbc5e293685af811fb Binary files /dev/null and b/parrot/lib/python3.10/site-packages/imageio/core/__pycache__/legacy_plugin_wrapper.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/imageio/core/__pycache__/request.cpython-310.pyc b/parrot/lib/python3.10/site-packages/imageio/core/__pycache__/request.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2c546d29e6b20978e07dccb30f60c6137ffd9fc8 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/imageio/core/__pycache__/request.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/imageio/core/__pycache__/util.cpython-310.pyc b/parrot/lib/python3.10/site-packages/imageio/core/__pycache__/util.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e5d1519ccf9f592413da910d2860004a6f0e657c Binary files /dev/null and b/parrot/lib/python3.10/site-packages/imageio/core/__pycache__/util.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/imageio/core/__pycache__/v3_plugin_api.cpython-310.pyc b/parrot/lib/python3.10/site-packages/imageio/core/__pycache__/v3_plugin_api.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1bfeed2d298f2fe6cfb19cfe954903211f474d37 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/imageio/core/__pycache__/v3_plugin_api.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/imageio/core/fetching.py b/parrot/lib/python3.10/site-packages/imageio/core/fetching.py new file mode 100644 index 0000000000000000000000000000000000000000..0380bc793b6c708a579aa333955e74ad18f6e484 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/imageio/core/fetching.py @@ -0,0 +1,247 @@ +# -*- coding: utf-8 -*- +# Based on code from the vispy project +# Distributed under the (new) BSD License. See LICENSE.txt for more info. + +"""Data downloading and reading functions +""" + +from math import log +import os +from os import path as op +import sys +import shutil +import time + +from . import appdata_dir, resource_dirs +from . import StdoutProgressIndicator, urlopen + + +class InternetNotAllowedError(IOError): + """Plugins that need resources can just use get_remote_file(), but + should catch this error and silently ignore it. + """ + + pass + + +class NeedDownloadError(IOError): + """Is raised when a remote file is requested that is not locally + available, but which needs to be explicitly downloaded by the user. + """ + + +def get_remote_file(fname, directory=None, force_download=False, auto=True): + """Get a the filename for the local version of a file from the web + + Parameters + ---------- + fname : str + The relative filename on the remote data repository to download. + These correspond to paths on + ``https://github.com/imageio/imageio-binaries/``. + directory : str | None + The directory where the file will be cached if a download was + required to obtain the file. By default, the appdata directory + is used. This is also the first directory that is checked for + a local version of the file. If the directory does not exist, + it will be created. + force_download : bool | str + If True, the file will be downloaded even if a local copy exists + (and this copy will be overwritten). Can also be a YYYY-MM-DD date + to ensure a file is up-to-date (modified date of a file on disk, + if present, is checked). + auto : bool + Whether to auto-download the file if its not present locally. Default + True. If False and a download is needed, raises NeedDownloadError. + + Returns + ------- + fname : str + The path to the file on the local system. + """ + _url_root = "https://github.com/imageio/imageio-binaries/raw/master/" + url = _url_root + fname + nfname = op.normcase(fname) # convert to native + # Get dirs to look for the resource + given_directory = directory + directory = given_directory or appdata_dir("imageio") + dirs = resource_dirs() + dirs.insert(0, directory) # Given dir has preference + # Try to find the resource locally + for dir in dirs: + filename = op.join(dir, nfname) + if op.isfile(filename): + if not force_download: # we're done + if given_directory and given_directory != dir: + filename2 = os.path.join(given_directory, nfname) + # Make sure the output directory exists + if not op.isdir(op.dirname(filename2)): + os.makedirs(op.abspath(op.dirname(filename2))) + shutil.copy(filename, filename2) + return filename2 + return filename + if isinstance(force_download, str): + ntime = time.strptime(force_download, "%Y-%m-%d") + ftime = time.gmtime(op.getctime(filename)) + if ftime >= ntime: + if given_directory and given_directory != dir: + filename2 = os.path.join(given_directory, nfname) + # Make sure the output directory exists + if not op.isdir(op.dirname(filename2)): + os.makedirs(op.abspath(op.dirname(filename2))) + shutil.copy(filename, filename2) + return filename2 + return filename + else: + print("File older than %s, updating..." % force_download) + break + + # If we get here, we're going to try to download the file + if os.getenv("IMAGEIO_NO_INTERNET", "").lower() in ("1", "true", "yes"): + raise InternetNotAllowedError( + "Will not download resource from the " + "internet because environment variable " + "IMAGEIO_NO_INTERNET is set." + ) + + # Can we proceed with auto-download? + if not auto: + raise NeedDownloadError() + + # Get filename to store to and make sure the dir exists + filename = op.join(directory, nfname) + if not op.isdir(op.dirname(filename)): + os.makedirs(op.abspath(op.dirname(filename))) + # let's go get the file + if os.getenv("CONTINUOUS_INTEGRATION", False): # pragma: no cover + # On CI, we retry a few times ... + for i in range(2): + try: + _fetch_file(url, filename) + return filename + except IOError: + time.sleep(0.5) + else: + _fetch_file(url, filename) + return filename + else: # pragma: no cover + _fetch_file(url, filename) + return filename + + +def _fetch_file(url, file_name, print_destination=True): + """Load requested file, downloading it if needed or requested + + Parameters + ---------- + url: string + The url of file to be downloaded. + file_name: string + Name, along with the path, of where downloaded file will be saved. + print_destination: bool, optional + If true, destination of where file was saved will be printed after + download finishes. + resume: bool, optional + If true, try to resume partially downloaded files. + """ + # Adapted from NISL: + # https://github.com/nisl/tutorial/blob/master/nisl/datasets.py + + print( + "Imageio: %r was not found on your computer; " + "downloading it now." % os.path.basename(file_name) + ) + + temp_file_name = file_name + ".part" + local_file = None + initial_size = 0 + errors = [] + for tries in range(4): + try: + # Checking file size and displaying it alongside the download url + remote_file = urlopen(url, timeout=5.0) + file_size = int(remote_file.headers["Content-Length"].strip()) + size_str = _sizeof_fmt(file_size) + print("Try %i. Download from %s (%s)" % (tries + 1, url, size_str)) + # Downloading data (can be extended to resume if need be) + local_file = open(temp_file_name, "wb") + _chunk_read(remote_file, local_file, initial_size=initial_size) + # temp file must be closed prior to the move + if not local_file.closed: + local_file.close() + shutil.move(temp_file_name, file_name) + if print_destination is True: + sys.stdout.write("File saved as %s.\n" % file_name) + break + except Exception as e: + errors.append(e) + print("Error while fetching file: %s." % str(e)) + finally: + if local_file is not None: + if not local_file.closed: + local_file.close() + else: + raise IOError( + "Unable to download %r. Perhaps there is no internet " + "connection? If there is, please report this problem." + % os.path.basename(file_name) + ) + + +def _chunk_read(response, local_file, chunk_size=8192, initial_size=0): + """Download a file chunk by chunk and show advancement + + Can also be used when resuming downloads over http. + + Parameters + ---------- + response: urllib.response.addinfourl + Response to the download request in order to get file size. + local_file: file + Hard disk file where data should be written. + chunk_size: integer, optional + Size of downloaded chunks. Default: 8192 + initial_size: int, optional + If resuming, indicate the initial size of the file. + """ + # Adapted from NISL: + # https://github.com/nisl/tutorial/blob/master/nisl/datasets.py + + bytes_so_far = initial_size + # Returns only amount left to download when resuming, not the size of the + # entire file + total_size = int(response.headers["Content-Length"].strip()) + total_size += initial_size + + progress = StdoutProgressIndicator("Downloading") + progress.start("", "bytes", total_size) + + while True: + chunk = response.read(chunk_size) + bytes_so_far += len(chunk) + if not chunk: + break + _chunk_write(chunk, local_file, progress) + progress.finish("Done") + + +def _chunk_write(chunk, local_file, progress): + """Write a chunk to file and update the progress bar""" + local_file.write(chunk) + progress.increase_progress(len(chunk)) + time.sleep(0) # Give other threads a chance, e.g. those that handle stdout pipes + + +def _sizeof_fmt(num): + """Turn number of bytes into human-readable str""" + units = ["bytes", "kB", "MB", "GB", "TB", "PB"] + decimals = [0, 0, 1, 2, 2, 2] + """Human friendly file size""" + if num > 1: + exponent = min(int(log(num, 1024)), len(units) - 1) + quotient = float(num) / 1024**exponent + unit = units[exponent] + num_decimals = decimals[exponent] + format_string = "{0:.%sf} {1}" % num_decimals + return format_string.format(quotient, unit) + return "0 bytes" if num == 0 else "1 byte" diff --git a/parrot/lib/python3.10/site-packages/imageio/core/format.py b/parrot/lib/python3.10/site-packages/imageio/core/format.py new file mode 100644 index 0000000000000000000000000000000000000000..109cd8e77fe3111378e6dd196f73b16cd197a436 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/imageio/core/format.py @@ -0,0 +1,881 @@ +# -*- coding: utf-8 -*- +# imageio is distributed under the terms of the (new) BSD License. + +""" + +.. note:: + imageio is under construction, some details with regard to the + Reader and Writer classes may change. + +These are the main classes of imageio. They expose an interface for +advanced users and plugin developers. A brief overview: + + * imageio.FormatManager - for keeping track of registered formats. + * imageio.Format - representation of a file format reader/writer + * imageio.Format.Reader - object used during the reading of a file. + * imageio.Format.Writer - object used during saving a file. + * imageio.Request - used to store the filename and other info. + +Plugins need to implement a Format class and register +a format object using ``imageio.formats.add_format()``. + +""" + +# todo: do we even use the known extensions? + +# Some notes: +# +# The classes in this module use the Request object to pass filename and +# related info around. This request object is instantiated in +# imageio.get_reader and imageio.get_writer. + +import sys +import warnings +import contextlib + +import numpy as np +from pathlib import Path + +from . import Array, asarray +from .request import ImageMode +from ..config import known_plugins, known_extensions, PluginConfig, FileExtension +from ..config.plugins import _original_order +from .imopen import imopen + + +# survived for backwards compatibility +# I don't know if external plugin code depends on it existing +# We no longer do +MODENAMES = ImageMode + + +def _get_config(plugin): + """Old Plugin resolution logic. + + Remove once we remove the old format manager. + """ + + extension_name = None + + if Path(plugin).suffix.lower() in known_extensions: + extension_name = Path(plugin).suffix.lower() + elif plugin in known_plugins: + pass + elif plugin.lower() in known_extensions: + extension_name = plugin.lower() + elif "." + plugin.lower() in known_extensions: + extension_name = "." + plugin.lower() + else: + raise IndexError(f"No format known by name `{plugin}`.") + + if extension_name is not None: + for plugin_name in [ + x + for file_extension in known_extensions[extension_name] + for x in file_extension.priority + ]: + if known_plugins[plugin_name].is_legacy: + plugin = plugin_name + break + + return known_plugins[plugin] + + +class Format(object): + """Represents an implementation to read/write a particular file format + + A format instance is responsible for 1) providing information about + a format; 2) determining whether a certain file can be read/written + with this format; 3) providing a reader/writer class. + + Generally, imageio will select the right format and use that to + read/write an image. A format can also be explicitly chosen in all + read/write functions. Use ``print(format)``, or ``help(format_name)`` + to see its documentation. + + To implement a specific format, one should create a subclass of + Format and the Format.Reader and Format.Writer classes. See + :class:`imageio.plugins` for details. + + Parameters + ---------- + name : str + A short name of this format. Users can select a format using its name. + description : str + A one-line description of the format. + extensions : str | list | None + List of filename extensions that this format supports. If a + string is passed it should be space or comma separated. The + extensions are used in the documentation and to allow users to + select a format by file extension. It is not used to determine + what format to use for reading/saving a file. + modes : str + A string containing the modes that this format can handle ('iIvV'), + “i” for an image, “I” for multiple images, “v” for a volume, + “V” for multiple volumes. + This attribute is used in the documentation and to select the + formats when reading/saving a file. + """ + + def __init__(self, name, description, extensions=None, modes=None): + """Initialize the Plugin. + + Parameters + ---------- + name : str + A short name of this format. Users can select a format using its name. + description : str + A one-line description of the format. + extensions : str | list | None + List of filename extensions that this format supports. If a + string is passed it should be space or comma separated. The + extensions are used in the documentation and to allow users to + select a format by file extension. It is not used to determine + what format to use for reading/saving a file. + modes : str + A string containing the modes that this format can handle ('iIvV'), + “i” for an image, “I” for multiple images, “v” for a volume, + “V” for multiple volumes. + This attribute is used in the documentation and to select the + formats when reading/saving a file. + """ + + # Store name and description + self._name = name.upper() + self._description = description + + # Store extensions, do some effort to normalize them. + # They are stored as a list of lowercase strings without leading dots. + if extensions is None: + extensions = [] + elif isinstance(extensions, str): + extensions = extensions.replace(",", " ").split(" ") + # + if isinstance(extensions, (tuple, list)): + self._extensions = tuple( + ["." + e.strip(".").lower() for e in extensions if e] + ) + else: + raise ValueError("Invalid value for extensions given.") + + # Store mode + self._modes = modes or "" + if not isinstance(self._modes, str): + raise ValueError("Invalid value for modes given.") + for m in self._modes: + if m not in "iIvV?": + raise ValueError("Invalid value for mode given.") + + def __repr__(self): + # Short description + return "" % (self.name, self.description) + + def __str__(self): + return self.doc + + @property + def doc(self): + """The documentation for this format (name + description + docstring).""" + # Our docsring is assumed to be indented by four spaces. The + # first line needs special attention. + return "%s - %s\n\n %s\n" % ( + self.name, + self.description, + self.__doc__.strip(), + ) + + @property + def name(self): + """The name of this format.""" + return self._name + + @property + def description(self): + """A short description of this format.""" + return self._description + + @property + def extensions(self): + """A list of file extensions supported by this plugin. + These are all lowercase with a leading dot. + """ + return self._extensions + + @property + def modes(self): + """A string specifying the modes that this format can handle.""" + return self._modes + + def get_reader(self, request): + """get_reader(request) + + Return a reader object that can be used to read data and info + from the given file. Users are encouraged to use + imageio.get_reader() instead. + """ + select_mode = request.mode[1] if request.mode[1] in "iIvV" else "" + if select_mode not in self.modes: + raise RuntimeError( + f"Format {self.name} cannot read in {request.mode.image_mode} mode" + ) + return self.Reader(self, request) + + def get_writer(self, request): + """get_writer(request) + + Return a writer object that can be used to write data and info + to the given file. Users are encouraged to use + imageio.get_writer() instead. + """ + select_mode = request.mode[1] if request.mode[1] in "iIvV" else "" + if select_mode not in self.modes: + raise RuntimeError( + f"Format {self.name} cannot write in {request.mode.image_mode} mode" + ) + return self.Writer(self, request) + + def can_read(self, request): + """can_read(request) + + Get whether this format can read data from the specified uri. + """ + return self._can_read(request) + + def can_write(self, request): + """can_write(request) + + Get whether this format can write data to the speciefed uri. + """ + return self._can_write(request) + + def _can_read(self, request): # pragma: no cover + """Check if Plugin can read from ImageResource. + + This method is called when the format manager is searching for a format + to read a certain image. Return True if this format can do it. + + The format manager is aware of the extensions and the modes that each + format can handle. It will first ask all formats that *seem* to be able + to read it whether they can. If none can, it will ask the remaining + formats if they can: the extension might be missing, and this allows + formats to provide functionality for certain extensions, while giving + preference to other plugins. + + If a format says it can, it should live up to it. The format would + ideally check the request.firstbytes and look for a header of some kind. + + Parameters + ---------- + request : Request + A request that can be used to access the ImageResource and obtain + metadata about it. + + Returns + ------- + can_read : bool + True if the plugin can read from the ImageResource, False otherwise. + + """ + return None # Plugins must implement this + + def _can_write(self, request): # pragma: no cover + """Check if Plugin can write to ImageResource. + + Parameters + ---------- + request : Request + A request that can be used to access the ImageResource and obtain + metadata about it. + + Returns + ------- + can_read : bool + True if the plugin can write to the ImageResource, False otherwise. + + """ + return None # Plugins must implement this + + # ----- + + class _BaseReaderWriter(object): + """Base class for the Reader and Writer class to implement common + functionality. It implements a similar approach for opening/closing + and context management as Python's file objects. + """ + + def __init__(self, format, request): + self.__closed = False + self._BaseReaderWriter_last_index = -1 + self._format = format + self._request = request + # Open the reader/writer + self._open(**self.request.kwargs.copy()) + + @property + def format(self): + """The :class:`.Format` object corresponding to the current + read/write operation. + """ + return self._format + + @property + def request(self): + """The :class:`.Request` object corresponding to the + current read/write operation. + """ + return self._request + + def __enter__(self): + self._checkClosed() + return self + + def __exit__(self, type, value, traceback): + if value is None: + # Otherwise error in close hide the real error. + self.close() + + def __del__(self): + try: + self.close() + except Exception: # pragma: no cover + pass # Suppress noise when called during interpreter shutdown + + def close(self): + """Flush and close the reader/writer. + This method has no effect if it is already closed. + """ + if self.__closed: + return + self.__closed = True + self._close() + # Process results and clean request object + self.request.finish() + + @property + def closed(self): + """Whether the reader/writer is closed.""" + return self.__closed + + def _checkClosed(self, msg=None): + """Internal: raise an ValueError if reader/writer is closed""" + if self.closed: + what = self.__class__.__name__ + msg = msg or ("I/O operation on closed %s." % what) + raise RuntimeError(msg) + + # To implement + + def _open(self, **kwargs): + """_open(**kwargs) + + Plugins should probably implement this. + + It is called when reader/writer is created. Here the + plugin can do its initialization. The given keyword arguments + are those that were given by the user at imageio.read() or + imageio.write(). + """ + raise NotImplementedError() + + def _close(self): + """_close() + + Plugins should probably implement this. + + It is called when the reader/writer is closed. Here the plugin + can do a cleanup, flush, etc. + + """ + raise NotImplementedError() + + # ----- + + class Reader(_BaseReaderWriter): + """ + The purpose of a reader object is to read data from an image + resource, and should be obtained by calling :func:`.get_reader`. + + A reader can be used as an iterator to read multiple images, + and (if the format permits) only reads data from the file when + new data is requested (i.e. streaming). A reader can also be + used as a context manager so that it is automatically closed. + + Plugins implement Reader's for different formats. Though rare, + plugins may provide additional functionality (beyond what is + provided by the base reader class). + """ + + def get_length(self): + """get_length() + + Get the number of images in the file. (Note: you can also + use ``len(reader_object)``.) + + The result can be: + * 0 for files that only have meta data + * 1 for singleton images (e.g. in PNG, JPEG, etc.) + * N for image series + * inf for streams (series of unknown length) + """ + return self._get_length() + + def get_data(self, index, **kwargs): + """get_data(index, **kwargs) + + Read image data from the file, using the image index. The + returned image has a 'meta' attribute with the meta data. + Raises IndexError if the index is out of range. + + Some formats may support additional keyword arguments. These are + listed in the documentation of those formats. + """ + self._checkClosed() + self._BaseReaderWriter_last_index = index + try: + im, meta = self._get_data(index, **kwargs) + except StopIteration: + raise IndexError(index) + return Array(im, meta) # Array tests im and meta + + def get_next_data(self, **kwargs): + """get_next_data(**kwargs) + + Read the next image from the series. + + Some formats may support additional keyword arguments. These are + listed in the documentation of those formats. + """ + return self.get_data(self._BaseReaderWriter_last_index + 1, **kwargs) + + def set_image_index(self, index, **kwargs): + """set_image_index(index) + + Set the internal pointer such that the next call to + get_next_data() returns the image specified by the index + """ + self._checkClosed() + n = self.get_length() + self._BaseReaderWriter_last_index = min(max(index - 1, -1), n) + + def get_meta_data(self, index=None): + """get_meta_data(index=None) + + Read meta data from the file. using the image index. If the + index is omitted or None, return the file's (global) meta data. + + Note that ``get_data`` also provides the meta data for the returned + image as an attribute of that image. + + The meta data is a dict, which shape depends on the format. + E.g. for JPEG, the dict maps group names to subdicts and each + group is a dict with name-value pairs. The groups represent + the different metadata formats (EXIF, XMP, etc.). + """ + self._checkClosed() + meta = self._get_meta_data(index) + if not isinstance(meta, dict): + raise ValueError( + "Meta data must be a dict, not %r" % meta.__class__.__name__ + ) + return meta + + def iter_data(self): + """iter_data() + + Iterate over all images in the series. (Note: you can also + iterate over the reader object.) + + """ + self._checkClosed() + n = self.get_length() + i = 0 + while i < n: + try: + im, meta = self._get_data(i) + except StopIteration: + return + except IndexError: + if n == float("inf"): + return + raise + yield Array(im, meta) + i += 1 + + # Compatibility + + def __iter__(self): + return self.iter_data() + + def __len__(self): + n = self.get_length() + if n == float("inf"): + n = sys.maxsize + return n + + # To implement + + def _get_length(self): + """_get_length() + + Plugins must implement this. + + The returned scalar specifies the number of images in the series. + See Reader.get_length for more information. + """ + raise NotImplementedError() + + def _get_data(self, index): + """_get_data() + + Plugins must implement this, but may raise an IndexError in + case the plugin does not support random access. + + It should return the image and meta data: (ndarray, dict). + """ + raise NotImplementedError() + + def _get_meta_data(self, index): + """_get_meta_data(index) + + Plugins must implement this. + + It should return the meta data as a dict, corresponding to the + given index, or to the file's (global) meta data if index is + None. + """ + raise NotImplementedError() + + # ----- + + class Writer(_BaseReaderWriter): + """ + The purpose of a writer object is to write data to an image + resource, and should be obtained by calling :func:`.get_writer`. + + A writer will (if the format permits) write data to the file + as soon as new data is provided (i.e. streaming). A writer can + also be used as a context manager so that it is automatically + closed. + + Plugins implement Writer's for different formats. Though rare, + plugins may provide additional functionality (beyond what is + provided by the base writer class). + """ + + def append_data(self, im, meta=None): + """append_data(im, meta={}) + + Append an image (and meta data) to the file. The final meta + data that is used consists of the meta data on the given + image (if applicable), updated with the given meta data. + """ + self._checkClosed() + # Check image data + if not isinstance(im, np.ndarray): + raise ValueError("append_data requires ndarray as first arg") + # Get total meta dict + total_meta = {} + if hasattr(im, "meta") and isinstance(im.meta, dict): + total_meta.update(im.meta) + if meta is None: + pass + elif not isinstance(meta, dict): + raise ValueError("Meta must be a dict.") + else: + total_meta.update(meta) + + # Decouple meta info + im = asarray(im) + # Call + return self._append_data(im, total_meta) + + def set_meta_data(self, meta): + """set_meta_data(meta) + + Sets the file's (global) meta data. The meta data is a dict which + shape depends on the format. E.g. for JPEG the dict maps + group names to subdicts, and each group is a dict with + name-value pairs. The groups represents the different + metadata formats (EXIF, XMP, etc.). + + Note that some meta formats may not be supported for + writing, and individual fields may be ignored without + warning if they are invalid. + """ + self._checkClosed() + if not isinstance(meta, dict): + raise ValueError("Meta must be a dict.") + else: + return self._set_meta_data(meta) + + # To implement + + def _append_data(self, im, meta): + # Plugins must implement this + raise NotImplementedError() + + def _set_meta_data(self, meta): + # Plugins must implement this + raise NotImplementedError() + + +class FormatManager(object): + """ + The FormatManager is a singleton plugin factory. + + The format manager supports getting a format object using indexing (by + format name or extension). When used as an iterator, this object + yields all registered format objects. + + See also :func:`.help`. + """ + + @property + def _formats(self): + available_formats = list() + + for config in known_plugins.values(): + with contextlib.suppress(ImportError): + # if an exception is raised, then format not installed + if config.is_legacy and config.format is not None: + available_formats.append(config) + + return available_formats + + def __repr__(self): + return f"" + + def __iter__(self): + return iter(x.format for x in self._formats) + + def __len__(self): + return len(self._formats) + + def __str__(self): + ss = [] + for config in self._formats: + ext = config.legacy_args["extensions"] + desc = config.legacy_args["description"] + s = f"{config.name} - {desc} [{ext}]" + ss.append(s) + return "\n".join(ss) + + def __getitem__(self, name): + warnings.warn( + "The usage of `FormatManager` is deprecated and it will be " + "removed in Imageio v3. Use `iio.imopen` instead.", + DeprecationWarning, + stacklevel=2, + ) + + if not isinstance(name, str): + raise ValueError( + "Looking up a format should be done by name or by extension." + ) + + if name == "": + raise ValueError("No format matches the empty string.") + + # Test if name is existing file + if Path(name).is_file(): + # legacy compatibility - why test reading here?? + try: + return imopen(name, "r", legacy_mode=True)._format + except ValueError: + # no plugin can read the file + pass + + config = _get_config(name.upper()) + + try: + return config.format + except ImportError: + raise ImportError( + f"The `{config.name}` format is not installed. " + f"Use `pip install imageio[{config.install_name}]` to install it." + ) + + def sort(self, *names): + """sort(name1, name2, name3, ...) + + Sort the formats based on zero or more given names; a format with + a name that matches one of the given names will take precedence + over other formats. A match means an equal name, or ending with + that name (though the former counts higher). Case insensitive. + + Format preference will match the order of the given names: using + ``sort('TIFF', '-FI', '-PIL')`` would prefer the FreeImage formats + over the Pillow formats, but prefer TIFF even more. Each time + this is called, the starting point is the default format order, + and calling ``sort()`` with no arguments will reset the order. + + Be aware that using the function can affect the behavior of + other code that makes use of imageio. + + Also see the ``IMAGEIO_FORMAT_ORDER`` environment variable. + """ + + warnings.warn( + "`FormatManager` is deprecated and it will be removed in ImageIO v3." + " Migrating `FormatManager.sort` depends on your use-case:\n" + "\t- modify `iio.config.known_plugins` to specify the search order for " + "unrecognized formats.\n" + "\t- modify `iio.config.known_extensions[].priority`" + " to control a specific extension.", + DeprecationWarning, + stacklevel=2, + ) + + # Check and sanitize input + for name in names: + if not isinstance(name, str): + raise TypeError("formats.sort() accepts only string names.") + if any(c in name for c in ".,"): + raise ValueError( + "Names given to formats.sort() should not " + "contain dots `.` or commas `,`." + ) + + should_reset = len(names) == 0 + if should_reset: + names = _original_order + + sane_names = [name.strip().upper() for name in names if name != ""] + + # enforce order for every extension that uses it + flat_extensions = [ + ext for ext_list in known_extensions.values() for ext in ext_list + ] + for extension in flat_extensions: + if should_reset: + extension.reset() + continue + + for name in reversed(sane_names): + for plugin in [x for x in extension.default_priority]: + if plugin.endswith(name): + extension.priority.remove(plugin) + extension.priority.insert(0, plugin) + + old_order = known_plugins.copy() + known_plugins.clear() + + for name in sane_names: + plugin = old_order.pop(name, None) + if plugin is not None: + known_plugins[name] = plugin + + known_plugins.update(old_order) + + def add_format(self, iio_format, overwrite=False): + """add_format(format, overwrite=False) + + Register a format, so that imageio can use it. If a format with the + same name already exists, an error is raised, unless overwrite is True, + in which case the current format is replaced. + """ + + warnings.warn( + "`FormatManager` is deprecated and it will be removed in ImageIO v3." + "To migrate `FormatManager.add_format` add the plugin directly to " + "`iio.config.known_plugins`.", + DeprecationWarning, + stacklevel=2, + ) + + if not isinstance(iio_format, Format): + raise ValueError("add_format needs argument to be a Format object") + elif not overwrite and iio_format.name in self.get_format_names(): + raise ValueError( + f"A Format named {iio_format.name} is already registered, use" + " `overwrite=True` to replace." + ) + + config = PluginConfig( + name=iio_format.name.upper(), + class_name=iio_format.__class__.__name__, + module_name=iio_format.__class__.__module__, + is_legacy=True, + install_name="unknown", + legacy_args={ + "name": iio_format.name, + "description": iio_format.description, + "extensions": " ".join(iio_format.extensions), + "modes": iio_format.modes, + }, + ) + + known_plugins[config.name] = config + + for extension in iio_format.extensions: + # be conservative and always treat it as a unique file format + ext = FileExtension( + extension=extension, + priority=[config.name], + name="Unique Format", + description="A format inserted at runtime." + f" It is being read by the `{config.name}` plugin.", + ) + known_extensions.setdefault(extension, list()).append(ext) + + def search_read_format(self, request): + """search_read_format(request) + + Search a format that can read a file according to the given request. + Returns None if no appropriate format was found. (used internally) + """ + + try: + # in legacy_mode imopen returns a LegacyPlugin + return imopen(request, request.mode.io_mode, legacy_mode=True)._format + except AttributeError: + warnings.warn( + "ImageIO now uses a v3 plugin when reading this format." + " Please migrate to the v3 API (preferred) or use imageio.v2.", + DeprecationWarning, + stacklevel=2, + ) + return None + except ValueError: + # no plugin can read this request + # but the legacy API doesn't raise + return None + + def search_write_format(self, request): + """search_write_format(request) + + Search a format that can write a file according to the given request. + Returns None if no appropriate format was found. (used internally) + """ + + try: + # in legacy_mode imopen returns a LegacyPlugin + return imopen(request, request.mode.io_mode, legacy_mode=True)._format + except AttributeError: + warnings.warn( + "ImageIO now uses a v3 plugin when writing this format." + " Please migrate to the v3 API (preferred) or use imageio.v2.", + DeprecationWarning, + stacklevel=2, + ) + return None + except ValueError: + # no plugin can write this request + # but the legacy API doesn't raise + return None + + def get_format_names(self): + """Get the names of all registered formats.""" + + warnings.warn( + "`FormatManager` is deprecated and it will be removed in ImageIO v3." + "To migrate `FormatManager.get_format_names` use `iio.config.known_plugins.keys()` instead.", + DeprecationWarning, + stacklevel=2, + ) + + return [f.name for f in self._formats] + + def show(self): + """Show a nicely formatted list of available formats""" + print(self) diff --git a/parrot/lib/python3.10/site-packages/imageio/core/imopen.py b/parrot/lib/python3.10/site-packages/imageio/core/imopen.py new file mode 100644 index 0000000000000000000000000000000000000000..a84b2a90a21d74500582e478eee41178a1f955f6 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/imageio/core/imopen.py @@ -0,0 +1,281 @@ +from pathlib import Path +import warnings + +from ..config import known_plugins +from ..config.extensions import known_extensions +from .request import ( + SPECIAL_READ_URIS, + URI_FILENAME, + InitializationError, + IOMode, + Request, +) + + +def imopen( + uri, + io_mode, + *, + plugin=None, + extension=None, + format_hint=None, + legacy_mode=False, + **kwargs, +): + """Open an ImageResource. + + .. warning:: + This warning is for pypy users. If you are not using a context manager, + remember to deconstruct the returned plugin to avoid leaking the file + handle to an unclosed file. + + Parameters + ---------- + uri : str or pathlib.Path or bytes or file or Request + The :doc:`ImageResource <../../user_guide/requests>` to load the + image from. + io_mode : str + The mode in which the file is opened. Possible values are:: + + ``r`` - open the file for reading + ``w`` - open the file for writing + + Depreciated since v2.9: + A second character can be added to give the reader a hint on what + the user expects. This will be ignored by new plugins and will + only have an effect on legacy plugins. Possible values are:: + + ``i`` for a single image, + ``I`` for multiple images, + ``v`` for a single volume, + ``V`` for multiple volumes, + ``?`` for don't care + + plugin : str, Plugin, or None + The plugin to use. If set to None imopen will perform a + search for a matching plugin. If not None, this takes priority over + the provided format hint. + extension : str + If not None, treat the provided ImageResource as if it had the given + extension. This affects the order in which backends are considered, and + when writing this may also influence the format used when encoding. + format_hint : str + Deprecated. Use `extension` instead. + legacy_mode : bool + If true use the v2 behavior when searching for a suitable + plugin. This will ignore v3 plugins and will check ``plugin`` + against known extensions if no plugin with the given name can be found. + **kwargs : Any + Additional keyword arguments will be passed to the plugin upon + construction. + + Notes + ----- + Registered plugins are controlled via the ``known_plugins`` dict in + ``imageio.config``. + + Passing a ``Request`` as the uri is only supported if ``legacy_mode`` + is ``True``. In this case ``io_mode`` is ignored. + + Using the kwarg ``format_hint`` does not enforce the given format. It merely + provides a `hint` to the selection process and plugin. The selection + processes uses this hint for optimization; however, a plugin's decision how + to read a ImageResource will - typically - still be based on the content of + the resource. + + + Examples + -------- + + >>> import imageio.v3 as iio + >>> with iio.imopen("/path/to/image.png", "r") as file: + >>> im = file.read() + + >>> with iio.imopen("/path/to/output.jpg", "w") as file: + >>> file.write(im) + + """ + + if isinstance(uri, Request) and legacy_mode: + warnings.warn( + "`iio.core.Request` is a low-level object and using it" + " directly as input to `imopen` is discouraged. This will raise" + " an exception in ImageIO v3.", + DeprecationWarning, + stacklevel=2, + ) + + request = uri + uri = request.raw_uri + io_mode = request.mode.io_mode + request.format_hint = format_hint + else: + request = Request(uri, io_mode, format_hint=format_hint, extension=extension) + + source = "" if isinstance(uri, bytes) else uri + + # fast-path based on plugin + # (except in legacy mode) + if plugin is not None: + if isinstance(plugin, str): + try: + config = known_plugins[plugin] + except KeyError: + request.finish() + raise ValueError( + f"`{plugin}` is not a registered plugin name." + ) from None + + def loader(request, **kwargs): + return config.plugin_class(request, **kwargs) + + else: + + def loader(request, **kwargs): + return plugin(request, **kwargs) + + try: + return loader(request, **kwargs) + except InitializationError as class_specific: + err_from = class_specific + err_type = RuntimeError if legacy_mode else IOError + err_msg = f"`{plugin}` can not handle the given uri." + except ImportError: + err_from = None + err_type = ImportError + err_msg = ( + f"The `{config.name}` plugin is not installed. " + f"Use `pip install imageio[{config.install_name}]` to install it." + ) + except Exception as generic_error: + err_from = generic_error + err_type = IOError + err_msg = f"An unknown error occurred while initializing plugin `{plugin}`." + + request.finish() + raise err_type(err_msg) from err_from + + # fast-path based on format_hint + if request.format_hint is not None: + for candidate_format in known_extensions[format_hint]: + for plugin_name in candidate_format.priority: + config = known_plugins[plugin_name] + + try: + candidate_plugin = config.plugin_class + except ImportError: + # not installed + continue + + try: + plugin_instance = candidate_plugin(request, **kwargs) + except InitializationError: + # file extension doesn't match file type + continue + + return plugin_instance + else: + resource = ( + "" if isinstance(request.raw_uri, bytes) else request.raw_uri + ) + warnings.warn(f"`{resource}` can not be opened as a `{format_hint}` file.") + + # fast-path based on file extension + if request.extension in known_extensions: + for candidate_format in known_extensions[request.extension]: + for plugin_name in candidate_format.priority: + config = known_plugins[plugin_name] + + try: + candidate_plugin = config.plugin_class + except ImportError: + # not installed + continue + + try: + plugin_instance = candidate_plugin(request, **kwargs) + except InitializationError: + # file extension doesn't match file type + continue + + return plugin_instance + + # error out for read-only special targets + # this is hacky; can we come up with a better solution for this? + if request.mode.io_mode == IOMode.write: + if isinstance(uri, str) and uri.startswith(SPECIAL_READ_URIS): + request.finish() + err_type = ValueError if legacy_mode else IOError + err_msg = f"`{source}` is read-only." + raise err_type(err_msg) + + # error out for directories + # this is a bit hacky and should be cleaned once we decide + # how to gracefully handle DICOM + if request._uri_type == URI_FILENAME and Path(request.raw_uri).is_dir(): + request.finish() + err_type = ValueError if legacy_mode else IOError + err_msg = ( + "ImageIO does not generally support reading folders. " + "Limited support may be available via specific plugins. " + "Specify the plugin explicitly using the `plugin` kwarg, e.g. `plugin='DICOM'`" + ) + raise err_type(err_msg) + + # close the current request here and use fresh/new ones while trying each + # plugin This is slow (means potentially reopening a resource several + # times), but should only happen rarely because this is the fallback if all + # else fails. + request.finish() + + # fallback option: try all plugins + for config in known_plugins.values(): + # each plugin gets its own request + request = Request(uri, io_mode, format_hint=format_hint) + + try: + plugin_instance = config.plugin_class(request, **kwargs) + except InitializationError: + continue + except ImportError: + continue + else: + return plugin_instance + + err_type = ValueError if legacy_mode else IOError + err_msg = f"Could not find a backend to open `{source}`` with iomode `{io_mode}`." + + # check if a missing plugin could help + if request.extension in known_extensions: + missing_plugins = list() + + formats = known_extensions[request.extension] + plugin_names = [ + plugin for file_format in formats for plugin in file_format.priority + ] + for name in plugin_names: + config = known_plugins[name] + + try: + config.plugin_class + continue + except ImportError: + missing_plugins.append(config) + + if len(missing_plugins) > 0: + install_candidates = "\n".join( + [ + ( + f" {config.name}: " + f"pip install imageio[{config.install_name}]" + ) + for config in missing_plugins + ] + ) + err_msg += ( + "\nBased on the extension, the following plugins might add capable backends:\n" + f"{install_candidates}" + ) + + request.finish() + raise err_type(err_msg) diff --git a/parrot/lib/python3.10/site-packages/imageio/core/legacy_plugin_wrapper.py b/parrot/lib/python3.10/site-packages/imageio/core/legacy_plugin_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..71d2a0ac426a5811143f1e75eff8e3dd8e0c94b9 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/imageio/core/legacy_plugin_wrapper.py @@ -0,0 +1,363 @@ +from pathlib import Path + +import numpy as np + +from ..config import known_extensions +from .request import InitializationError, IOMode +from .v3_plugin_api import ImageProperties, PluginV3 + + +def _legacy_default_index(format): + if format._name == "FFMPEG": + index = Ellipsis + elif format._name == "GIF-PIL": + index = Ellipsis + else: + index = 0 + + return index + + +class LegacyPlugin(PluginV3): + """A plugin to make old (v2.9) plugins compatible with v3.0 + + .. depreciated:: 2.9 + `legacy_get_reader` will be removed in a future version of imageio. + `legacy_get_writer` will be removed in a future version of imageio. + + This plugin is a wrapper around the old FormatManager class and exposes + all the old plugins via the new API. On top of this it has + ``legacy_get_reader`` and ``legacy_get_writer`` methods to allow using + it with the v2.9 API. + + Methods + ------- + read(index=None, **kwargs) + Read the image at position ``index``. + write(image, **kwargs) + Write image to the URI. + iter(**kwargs) + Iteratively yield images from the given URI. + get_meta(index=None) + Return the metadata for the image at position ``index``. + legacy_get_reader(**kwargs) + Returns the v2.9 image reader. (depreciated) + legacy_get_writer(**kwargs) + Returns the v2.9 image writer. (depreciated) + + Examples + -------- + + >>> import imageio.v3 as iio + >>> with iio.imopen("/path/to/image.tiff", "r", legacy_mode=True) as file: + >>> reader = file.legacy_get_reader() # depreciated + >>> for im in file.iter(): + >>> print(im.shape) + + """ + + def __init__(self, request, legacy_plugin): + """Instantiate a new Legacy Plugin + + Parameters + ---------- + uri : {str, pathlib.Path, bytes, file} + The resource to load the image from, e.g. a filename, pathlib.Path, + http address or file object, see the docs for more info. + legacy_plugin : Format + The (legacy) format to use to interface with the URI. + + """ + self._request = request + self._format = legacy_plugin + + source = ( + "" + if isinstance(self._request.raw_uri, bytes) + else self._request.raw_uri + ) + if self._request.mode.io_mode == IOMode.read: + if not self._format.can_read(request): + raise InitializationError( + f"`{self._format.name}`" f" can not read `{source}`." + ) + else: + if not self._format.can_write(request): + raise InitializationError( + f"`{self._format.name}`" f" can not write to `{source}`." + ) + + def legacy_get_reader(self, **kwargs): + """legacy_get_reader(**kwargs) + + a utility method to provide support vor the V2.9 API + + Parameters + ---------- + kwargs : ... + Further keyword arguments are passed to the reader. See :func:`.help` + to see what arguments are available for a particular format. + """ + + # Note: this will break thread-safety + self._request._kwargs = kwargs + + # safeguard for DICOM plugin reading from folders + try: + assert Path(self._request.filename).is_dir() + except OSError: + pass # not a valid path on this OS + except AssertionError: + pass # not a folder + else: + return self._format.get_reader(self._request) + + self._request.get_file().seek(0) + return self._format.get_reader(self._request) + + def read(self, *, index=None, **kwargs): + """ + Parses the given URI and creates a ndarray from it. + + Parameters + ---------- + index : {integer, None} + If the URI contains a list of ndimages return the index-th + image. If None, stack all images into an ndimage along the + 0-th dimension (equivalent to np.stack(imgs, axis=0)). + kwargs : ... + Further keyword arguments are passed to the reader. See + :func:`.help` to see what arguments are available for a particular + format. + + Returns + ------- + ndimage : np.ndarray + A numpy array containing the decoded image data. + + """ + + if index is None: + index = _legacy_default_index(self._format) + + if index is Ellipsis: + img = np.stack([im for im in self.iter(**kwargs)]) + return img + + reader = self.legacy_get_reader(**kwargs) + return reader.get_data(index) + + def legacy_get_writer(self, **kwargs): + """legacy_get_writer(**kwargs) + + Returns a :class:`.Writer` object which can be used to write data + and meta data to the specified file. + + Parameters + ---------- + kwargs : ... + Further keyword arguments are passed to the writer. See :func:`.help` + to see what arguments are available for a particular format. + """ + + # Note: this will break thread-safety + self._request._kwargs = kwargs + return self._format.get_writer(self._request) + + def write(self, ndimage, *, is_batch=None, metadata=None, **kwargs): + """ + Write an ndimage to the URI specified in path. + + If the URI points to a file on the current host and the file does not + yet exist it will be created. If the file exists already, it will be + appended if possible; otherwise, it will be replaced. + + Parameters + ---------- + ndimage : numpy.ndarray + The ndimage or list of ndimages to write. + is_batch : bool + If True, treat the supplied ndimage as a batch of images. If False, + treat the supplied ndimage as a single image. If None, try to + determine ``is_batch`` from the ndimage's shape and ndim. + metadata : dict + The metadata passed to write alongside the image. + kwargs : ... + Further keyword arguments are passed to the writer. See + :func:`.help` to see what arguments are available for a + particular format. + + + Returns + ------- + buffer : bytes + When writing to the special target "", this function will + return the encoded image data as a bytes string. Otherwise it + returns None. + + Notes + ----- + Automatically determining ``is_batch`` may fail for some images due to + shape aliasing. For example, it may classify a channel-first color image + as a batch of gray images. In most cases this automatic deduction works + fine (it has for almost a decade), but if you do have one of those edge + cases (or are worried that you might) consider explicitly setting + ``is_batch``. + + """ + + if is_batch or isinstance(ndimage, (list, tuple)): + pass # ndimage is list of images + elif is_batch is False: + ndimage = [ndimage] + else: + # Write the largest possible block by guessing the meaning of each + # dimension from the shape/ndim and then checking if any batch + # dimensions are left. + ndimage = np.asanyarray(ndimage) + batch_dims = ndimage.ndim + + # two spatial dimensions + batch_dims = max(batch_dims - 2, 0) + + # packed (channel-last) image + if ndimage.ndim >= 3 and ndimage.shape[-1] < 5: + batch_dims = max(batch_dims - 1, 0) + + # format supports volumetric images + ext_infos = known_extensions.get(self._request.extension, list()) + for ext_info in ext_infos: + if self._format.name in ext_info.priority and ext_info.volume_support: + batch_dims = max(batch_dims - 1, 0) + break + + if batch_dims == 0: + ndimage = [ndimage] + + with self.legacy_get_writer(**kwargs) as writer: + for image in ndimage: + image = np.asanyarray(image) + + if image.ndim < 2: + raise ValueError( + "The image must have at least two spatial dimensions." + ) + + if not np.issubdtype(image.dtype, np.number) and not np.issubdtype( + image.dtype, bool + ): + raise ValueError( + f"All images have to be numeric, and not `{image.dtype}`." + ) + + writer.append_data(image, metadata) + + return writer.request.get_result() + + def iter(self, **kwargs): + """Iterate over a list of ndimages given by the URI + + Parameters + ---------- + kwargs : ... + Further keyword arguments are passed to the reader. See + :func:`.help` to see what arguments are available for a particular + format. + """ + + reader = self.legacy_get_reader(**kwargs) + for image in reader: + yield image + + def properties(self, index=None): + """Standardized ndimage metadata. + + Parameters + ---------- + index : int + The index of the ndimage for which to return properties. If the + index is out of bounds a ``ValueError`` is raised. If ``None``, + return the properties for the ndimage stack. If this is impossible, + e.g., due to shape mismatch, an exception will be raised. + + Returns + ------- + properties : ImageProperties + A dataclass filled with standardized image metadata. + + """ + + if index is None: + index = _legacy_default_index(self._format) + + # for backwards compatibility ... actually reads pixel data :( + if index is Ellipsis: + image = self.read(index=0) + n_images = self.legacy_get_reader().get_length() + return ImageProperties( + shape=(n_images, *image.shape), + dtype=image.dtype, + n_images=n_images, + is_batch=True, + ) + + image = self.read(index=index) + return ImageProperties( + shape=image.shape, + dtype=image.dtype, + is_batch=False, + ) + + def get_meta(self, *, index=None): + """Read ndimage metadata from the URI + + Parameters + ---------- + index : {integer, None} + If the URI contains a list of ndimages return the metadata + corresponding to the index-th image. If None, behavior depends on + the used api + + Legacy-style API: return metadata of the first element (index=0) + New-style API: Behavior depends on the used Plugin. + + Returns + ------- + metadata : dict + A dictionary of metadata. + + """ + + return self.metadata(index=index, exclude_applied=False) + + def metadata(self, index=None, exclude_applied: bool = True): + """Format-Specific ndimage metadata. + + Parameters + ---------- + index : int + The index of the ndimage to read. If the index is out of bounds a + ``ValueError`` is raised. If ``None``, global metadata is returned. + exclude_applied : bool + This parameter exists for compatibility and has no effect. Legacy + plugins always report all metadata they find. + + Returns + ------- + metadata : dict + A dictionary filled with format-specific metadata fields and their + values. + + """ + + if index is None: + index = _legacy_default_index(self._format) + + return self.legacy_get_reader().get_meta_data(index=index) + + def __del__(self) -> None: + pass + # turns out we can't close the file here for LegacyPlugin + # because it would break backwards compatibility + # with legacy_get_writer and legacy_get_reader + # self._request.finish() diff --git a/parrot/lib/python3.10/site-packages/imageio/core/legacy_plugin_wrapper.pyi b/parrot/lib/python3.10/site-packages/imageio/core/legacy_plugin_wrapper.pyi new file mode 100644 index 0000000000000000000000000000000000000000..52e3ec52db2c2d7b77de400faaefb6c4969381c7 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/imageio/core/legacy_plugin_wrapper.pyi @@ -0,0 +1,27 @@ +import numpy as np +from typing import Optional, Dict, Any, Union, List, Iterator + +from .request import Request +from .v3_plugin_api import PluginV3, ImageProperties +from .format import Format +from ..typing import ArrayLike + +class LegacyPlugin(PluginV3): + def __init__(self, request: Request, legacy_plugin: Format) -> None: ... + def legacy_get_reader(self, **kwargs) -> Format.Reader: ... + def read(self, *, index: Optional[int] = 0, **kwargs) -> np.ndarray: ... + def legacy_get_writer(self, **kwargs) -> Format.Writer: ... + def write( + self, + ndimage: Union[ArrayLike, List[ArrayLike]], + *, + is_batch: bool = None, + **kwargs + ) -> Optional[bytes]: ... + def iter(self, **kwargs) -> Iterator[np.ndarray]: ... + def properties(self, index: Optional[int] = 0) -> ImageProperties: ... + def get_meta(self, *, index: Optional[int] = 0) -> Dict[str, Any]: ... + def metadata( + self, index: Optional[int] = 0, exclude_applied: bool = True + ) -> Dict[str, Any]: ... + def __del__(self) -> None: ... diff --git a/parrot/lib/python3.10/site-packages/imageio/core/request.py b/parrot/lib/python3.10/site-packages/imageio/core/request.py new file mode 100644 index 0000000000000000000000000000000000000000..47b7c95ca2550c8efbd78f68b9c36ff704235986 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/imageio/core/request.py @@ -0,0 +1,754 @@ +# -*- coding: utf-8 -*- +# imageio is distributed under the terms of the (new) BSD License. + +""" +Definition of the Request object, which acts as a kind of bridge between +what the user wants and what the plugins can. +""" + +import os +from io import BytesIO +import zipfile +import tempfile +import shutil +import enum +import warnings + +from ..core import urlopen, get_remote_file + +from pathlib import Path +from urllib.parse import urlparse +from typing import Optional + +# URI types +URI_BYTES = 1 +URI_FILE = 2 +URI_FILENAME = 3 +URI_ZIPPED = 4 +URI_HTTP = 5 +URI_FTP = 6 + + +class IOMode(str, enum.Enum): + """Available Image modes + + This is a helper enum for ``Request.Mode`` which is a composite of a + ``Request.ImageMode`` and ``Request.IOMode``. The IOMode that tells the + plugin if the resource should be read from or written to. Available values are + + - read ("r"): Read from the specified resource + - write ("w"): Write to the specified resource + + """ + + read = "r" + write = "w" + + +class ImageMode(str, enum.Enum): + """Available Image modes + + This is a helper enum for ``Request.Mode`` which is a composite of a + ``Request.ImageMode`` and ``Request.IOMode``. The image mode that tells the + plugin the desired (and expected) image shape. Available values are + + - single_image ("i"): Return a single image extending in two spacial + dimensions + - multi_image ("I"): Return a list of images extending in two spacial + dimensions + - single_volume ("v"): Return an image extending into multiple dimensions. + E.g. three spacial dimensions for image stacks, or two spatial and one + time dimension for videos + - multi_volume ("V"): Return a list of images extending into multiple + dimensions. + - any_mode ("?"): Return an image in any format (the plugin decides the + appropriate action). + + """ + + single_image = "i" + multi_image = "I" + single_volume = "v" + multi_volume = "V" + any_mode = "?" + + +@enum.unique +class Mode(str, enum.Enum): + """The mode to use when interacting with the resource + + ``Request.Mode`` is a composite of ``Request.ImageMode`` and + ``Request.IOMode``. The image mode that tells the plugin the desired (and + expected) image shape and the ``Request.IOMode`` tells the plugin the way + the resource should be interacted with. For a detailed description of the + available modes, see the documentation for ``Request.ImageMode`` and + ``Request.IOMode`` respectively. + + Available modes are all combinations of ``Request.IOMode`` and ``Request.ImageMode``: + + - read_single_image ("ri") + - read_multi_image ("rI") + - read_single_volume ("rv") + - read_multi_volume ("rV") + - read_any ("r?") + - write_single_image ("wi") + - write_multi_image ("wI") + - write_single_volume ("wv") + - write_multi_volume ("wV") + - write_any ("w?") + + Examples + -------- + >>> Request.Mode("rI") # a list of simple images should be read from the resource + >>> Request.Mode("wv") # a single volume should be written to the resource + + """ + + read_single_image = "ri" + read_multi_image = "rI" + read_single_volume = "rv" + read_multi_volume = "rV" + read_any = "r?" + write_single_image = "wi" + write_multi_image = "wI" + write_single_volume = "wv" + write_multi_volume = "wV" + write_any = "w?" + + @classmethod + def _missing_(cls, value): + """Enable Mode("r") and Mode("w") + + The sunder method ``_missing_`` is called whenever the constructor fails + to directly look up the corresponding enum value from the given input. + In our case, we use it to convert the modes "r" and "w" (from the v3 + API) into their legacy versions "r?" and "w?". + + More info on _missing_: + https://docs.python.org/3/library/enum.html#supported-sunder-names + """ + + if value == "r": + return cls("r?") + elif value == "w": + return cls("w?") + else: + raise ValueError(f"{value} is no valid Mode.") + + @property + def io_mode(self) -> IOMode: + return IOMode(self.value[0]) + + @property + def image_mode(self) -> ImageMode: + return ImageMode(self.value[1]) + + def __getitem__(self, key): + """For backwards compatibility with the old non-enum modes""" + if key == 0: + return self.io_mode + elif key == 1: + return self.image_mode + else: + raise IndexError(f"Mode has no item {key}") + + +SPECIAL_READ_URIS = "", "" + +# The user can use this string in a write call to get the data back as bytes. +RETURN_BYTES = "" + +# Example images that will be auto-downloaded +EXAMPLE_IMAGES = { + "astronaut.png": "Image of the astronaut Eileen Collins", + "camera.png": "A grayscale image of a photographer", + "checkerboard.png": "Black and white image of a chekerboard", + "wood.jpg": "A (repeatable) texture of wooden planks", + "bricks.jpg": "A (repeatable) texture of stone bricks", + "clock.png": "Photo of a clock with motion blur (Stefan van der Walt)", + "coffee.png": "Image of a cup of coffee (Rachel Michetti)", + "chelsea.png": "Image of Stefan's cat", + "wikkie.png": "Image of Almar's cat", + "coins.png": "Image showing greek coins from Pompeii", + "horse.png": "Image showing the silhouette of a horse (Andreas Preuss)", + "hubble_deep_field.png": "Photograph taken by Hubble telescope (NASA)", + "immunohistochemistry.png": "Immunohistochemical (IHC) staining", + "moon.png": "Image showing a portion of the surface of the moon", + "page.png": "A scanned page of text", + "text.png": "A photograph of handdrawn text", + "chelsea.zip": "The chelsea.png in a zipfile (for testing)", + "chelsea.bsdf": "The chelsea.png in a BSDF file(for testing)", + "newtonscradle.gif": "Animated GIF of a newton's cradle", + "cockatoo.mp4": "Video file of a cockatoo", + "stent.npz": "Volumetric image showing a stented abdominal aorta", + "meadow_cube.jpg": "A cubemap image of a meadow, e.g. to render a skybox.", +} + + +class Request(object): + """ImageResource handling utility. + + Represents a request for reading or saving an image resource. This + object wraps information to that request and acts as an interface + for the plugins to several resources; it allows the user to read + from filenames, files, http, zipfiles, raw bytes, etc., but offer + a simple interface to the plugins via ``get_file()`` and + ``get_local_filename()``. + + For each read/write operation a single Request instance is used and passed + to the can_read/can_write method of a format, and subsequently to + the Reader/Writer class. This allows rudimentary passing of + information between different formats and between a format and + associated reader/writer. + + Parameters + ---------- + uri : {str, bytes, file} + The resource to load the image from. + mode : str + The first character is "r" or "w", indicating a read or write + request. The second character is used to indicate the kind of data: + "i" for an image, "I" for multiple images, "v" for a volume, + "V" for multiple volumes, "?" for don't care. + + """ + + def __init__(self, uri, mode, *, extension=None, format_hint: str = None, **kwargs): + # General + self.raw_uri = uri + self._uri_type = None + self._filename = None + self._extension = None + self._format_hint = None + self._kwargs = kwargs + self._result = None # Some write actions may have a result + + # To handle the user-side + self._filename_zip = None # not None if a zipfile is used + self._bytes = None # Incoming bytes + self._zipfile = None # To store a zipfile instance (if used) + + # To handle the plugin side + self._file = None # To store the file instance + self._file_is_local = False # whether the data needs to be copied at end + self._filename_local = None # not None if using tempfile on this FS + self._firstbytes = None # For easy header parsing + + # To store formats that may be able to fulfil this request + # self._potential_formats = [] + + # Check mode + try: + self._mode = Mode(mode) + except ValueError: + raise ValueError(f"Invalid Request.Mode: {mode}") + + # Parse what was given + self._parse_uri(uri) + + # Set extension + if extension is not None: + if extension[0] != ".": + raise ValueError( + "`extension` should be a file extension starting with a `.`," + f" but is `{extension}`." + ) + self._extension = extension + elif self._filename is not None: + if self._uri_type in (URI_FILENAME, URI_ZIPPED): + path = self._filename + else: + path = urlparse(self._filename).path + ext = Path(path).suffix.lower() + self._extension = ext if ext != "" else None + + if format_hint is not None: + warnings.warn( + "The usage of `format_hint` is deprecated and will be removed " + "in ImageIO v3. Use `extension` instead.", + DeprecationWarning, + ) + + if format_hint is not None and format_hint[0] != ".": + raise ValueError( + "`format_hint` should be a file extension starting with a `.`," + f" but is `{format_hint}`." + ) + + self.format_hint = format_hint + + def _parse_uri(self, uri): + """Try to figure our what we were given""" + is_read_request = self.mode.io_mode is IOMode.read + is_write_request = self.mode.io_mode is IOMode.write + + if isinstance(uri, str): + # Explicit + if uri.startswith("imageio:"): + if is_write_request: + raise RuntimeError("Cannot write to the standard images.") + fn = uri.split(":", 1)[-1].lower() + fn, _, zip_part = fn.partition(".zip/") + if zip_part: + fn += ".zip" + if fn not in EXAMPLE_IMAGES: + raise ValueError("Unknown standard image %r." % fn) + self._uri_type = URI_FILENAME + self._filename = get_remote_file("images/" + fn, auto=True) + if zip_part: + self._filename += "/" + zip_part + elif uri.startswith("http://") or uri.startswith("https://"): + self._uri_type = URI_HTTP + self._filename = uri + elif uri.startswith("ftp://") or uri.startswith("ftps://"): + self._uri_type = URI_FTP + self._filename = uri + elif uri.startswith("file://"): + self._uri_type = URI_FILENAME + self._filename = uri[7:] + elif uri.startswith(SPECIAL_READ_URIS) and is_read_request: + self._uri_type = URI_BYTES + self._filename = uri + elif uri.startswith(RETURN_BYTES) and is_write_request: + self._uri_type = URI_BYTES + self._filename = uri + else: + self._uri_type = URI_FILENAME + self._filename = uri + + elif isinstance(uri, memoryview) and is_read_request: + self._uri_type = URI_BYTES + self._filename = "" + self._bytes = uri.tobytes() + elif isinstance(uri, bytes) and is_read_request: + self._uri_type = URI_BYTES + self._filename = "" + self._bytes = uri + elif isinstance(uri, Path): + self._uri_type = URI_FILENAME + self._filename = str(uri) + # Files + elif is_read_request: + if hasattr(uri, "read") and hasattr(uri, "close"): + self._uri_type = URI_FILE + self._filename = "" + self._file = uri # Data must be read from here + elif is_write_request: + if hasattr(uri, "write") and hasattr(uri, "close"): + self._uri_type = URI_FILE + self._filename = "" + self._file = uri # Data must be written here + + # Expand user dir + if self._uri_type == URI_FILENAME and self._filename.startswith("~"): + self._filename = os.path.expanduser(self._filename) + + # Check if a zipfile + if self._uri_type == URI_FILENAME: + # Search for zip extension followed by a path separator + for needle in [".zip/", ".zip\\"]: + zip_i = self._filename.lower().find(needle) + if zip_i > 0: + zip_i += 4 + zip_path = self._filename[:zip_i] + if os.path.isdir(zip_path): + pass # is an existing dir (see #548) + elif is_write_request or os.path.isfile(zip_path): + self._uri_type = URI_ZIPPED + self._filename_zip = ( + zip_path, + self._filename[zip_i:].lstrip("/\\"), + ) + break + + # Check if we could read it + if self._uri_type is None: + uri_r = repr(uri) + if len(uri_r) > 60: + uri_r = uri_r[:57] + "..." + raise IOError("Cannot understand given URI: %s." % uri_r) + + # Check if this is supported + noWriting = [URI_HTTP, URI_FTP] + if is_write_request and self._uri_type in noWriting: + raise IOError("imageio does not support writing to http/ftp.") + + # Deprecated way to load standard images, give a sensible error message + if is_read_request and self._uri_type in [URI_FILENAME, URI_ZIPPED]: + fn = self._filename + if self._filename_zip: + fn = self._filename_zip[0] + if (not os.path.exists(fn)) and (fn in EXAMPLE_IMAGES): + raise IOError( + "No such file: %r. This file looks like one of " + "the standard images, but from imageio 2.1, " + "standard images have to be specified using " + '"imageio:%s".' % (fn, fn) + ) + + # Make filename absolute + if self._uri_type in [URI_FILENAME, URI_ZIPPED]: + if self._filename_zip: + self._filename_zip = ( + os.path.abspath(self._filename_zip[0]), + self._filename_zip[1], + ) + else: + self._filename = os.path.abspath(self._filename) + + # Check whether file name is valid + if self._uri_type in [URI_FILENAME, URI_ZIPPED]: + fn = self._filename + if self._filename_zip: + fn = self._filename_zip[0] + if is_read_request: + # Reading: check that the file exists (but is allowed a dir) + if not os.path.exists(fn): + raise FileNotFoundError("No such file: '%s'" % fn) + else: + # Writing: check that the directory to write to does exist + dn = os.path.dirname(fn) + if not os.path.exists(dn): + raise FileNotFoundError("The directory %r does not exist" % dn) + + @property + def filename(self): + """Name of the ImageResource. + + + The uri for which reading/saving was requested. This + can be a filename, an http address, or other resource + identifier. Do not rely on the filename to obtain the data, + but use ``get_file()`` or ``get_local_filename()`` instead. + """ + return self._filename + + @property + def extension(self) -> str: + """The (lowercase) extension of the requested filename. + Suffixes in url's are stripped. Can be None if the request is + not based on a filename. + """ + return self._extension + + @property + def format_hint(self) -> Optional[str]: + return self._format_hint + + @format_hint.setter + def format_hint(self, format: str) -> None: + self._format_hint = format + if self._extension is None: + self._extension = format + + @property + def mode(self): + """The mode of the request. The first character is "r" or "w", + indicating a read or write request. The second character is + used to indicate the kind of data: + "i" for an image, "I" for multiple images, "v" for a volume, + "V" for multiple volumes, "?" for don't care. + """ + return self._mode + + @property + def kwargs(self): + """The dict of keyword arguments supplied by the user.""" + return self._kwargs + + # For obtaining data + + def get_file(self): + """get_file() + Get a file object for the resource associated with this request. + If this is a reading request, the file is in read mode, + otherwise in write mode. This method is not thread safe. Plugins + should not close the file when done. + + This is the preferred way to read/write the data. But if a + format cannot handle file-like objects, they should use + ``get_local_filename()``. + """ + want_to_write = self.mode.io_mode is IOMode.write + + # Is there already a file? + # Either _uri_type == URI_FILE, or we already opened the file, + # e.g. by using firstbytes + if self._file is not None: + return self._file + + if self._uri_type == URI_BYTES: + if want_to_write: + # Create new file object, we catch the bytes in finish() + self._file = BytesIO() + self._file_is_local = True + else: + self._file = BytesIO(self._bytes) + + elif self._uri_type == URI_FILENAME: + if want_to_write: + self._file = open(self.filename, "wb") + else: + self._file = open(self.filename, "rb") + + elif self._uri_type == URI_ZIPPED: + # Get the correct filename + filename, name = self._filename_zip + if want_to_write: + # Create new file object, we catch the bytes in finish() + self._file = BytesIO() + self._file_is_local = True + else: + # Open zipfile and open new file object for specific file + self._zipfile = zipfile.ZipFile(filename, "r") + self._file = self._zipfile.open(name, "r") + self._file = SeekableFileObject(self._file) + + elif self._uri_type in [URI_HTTP or URI_FTP]: + assert not want_to_write # This should have been tested in init + timeout = os.getenv("IMAGEIO_REQUEST_TIMEOUT") + if timeout is None or not timeout.isdigit(): + timeout = 5 + self._file = urlopen(self.filename, timeout=float(timeout)) + self._file = SeekableFileObject(self._file) + + return self._file + + def get_local_filename(self): + """get_local_filename() + If the filename is an existing file on this filesystem, return + that. Otherwise a temporary file is created on the local file + system which can be used by the format to read from or write to. + """ + + if self._uri_type == URI_FILENAME: + return self._filename + else: + # Get filename + if self.extension is not None: + ext = self.extension + else: + ext = os.path.splitext(self._filename)[1] + fd, self._filename_local = tempfile.mkstemp(ext, "imageio_") + os.close(fd) + # Write stuff to it? + if self.mode.io_mode == IOMode.read: + with open(self._filename_local, "wb") as file: + shutil.copyfileobj(self.get_file(), file) + return self._filename_local + + def finish(self) -> None: + """Wrap up this request. + + Finishes any pending reads or writes, closes any open files and frees + any resources allocated by this request. + """ + + if self.mode.io_mode == IOMode.write: + # See if we "own" the data and must put it somewhere + bytes = None + if self._filename_local: + bytes = Path(self._filename_local).read_bytes() + elif self._file_is_local: + self._file_is_local = False + bytes = self._file.getvalue() + + # Put the data in the right place + if bytes is not None: + if self._uri_type == URI_BYTES: + self._result = bytes # Picked up by imread function + elif self._uri_type == URI_FILE: + self._file.write(bytes) + elif self._uri_type == URI_ZIPPED: + zf = zipfile.ZipFile(self._filename_zip[0], "a") + zf.writestr(self._filename_zip[1], bytes) + zf.close() + # elif self._uri_type == URI_FILENAME: -> is always direct + # elif self._uri_type == URI_FTP/HTTP: -> write not supported + + # Close open files that we know of (and are responsible for) + if self._file and self._uri_type != URI_FILE: + self._file.close() + self._file = None + if self._zipfile: + self._zipfile.close() + self._zipfile = None + + # Remove temp file + if self._filename_local: + try: + os.remove(self._filename_local) + except Exception: # pragma: no cover + warnings.warn( + "Failed to delete the temporary file at " + f"`{self._filename_local}`. Please report this issue." + ) + self._filename_local = None + + # Detach so gc can clean even if a reference of self lingers + self._bytes = None + + def get_result(self): + """For internal use. In some situations a write action can have + a result (bytes data). That is obtained with this function. + """ + # Is there a reason to disallow reading multiple times? + self._result, res = None, self._result + return res + + @property + def firstbytes(self): + """The first 256 bytes of the file. These can be used to + parse the header to determine the file-format. + """ + if self._firstbytes is None: + self._read_first_bytes() + return self._firstbytes + + def _read_first_bytes(self, N=256): + if self._bytes is not None: + self._firstbytes = self._bytes[:N] + else: + # Prepare + try: + f = self.get_file() + except IOError: + if os.path.isdir(self.filename): # A directory, e.g. for DICOM + self._firstbytes = bytes() + return + raise + try: + i = f.tell() + except Exception: + i = None + # Read + self._firstbytes = read_n_bytes(f, N) + # Set back + try: + if i is None: + raise Exception("cannot seek with None") + f.seek(i) + except Exception: + # Prevent get_file() from reusing the file + self._file = None + # If the given URI was a file object, we have a problem, + if self._uri_type == URI_FILE: + raise IOError("Cannot seek back after getting firstbytes!") + + +def read_n_bytes(f, N): + """read_n_bytes(file, n) + + Read n bytes from the given file, or less if the file has less + bytes. Returns zero bytes if the file is closed. + """ + bb = bytes() + while len(bb) < N: + extra_bytes = f.read(N - len(bb)) + if not extra_bytes: + break + bb += extra_bytes + return bb + + +class SeekableFileObject: + """A readonly wrapper file object that add support for seeking, even if + the wrapped file object does not. The allows us to stream from http and + still use Pillow. + """ + + def __init__(self, f): + self.f = f + self._i = 0 # >=0 but can exceed buffer + self._buffer = b"" + self._have_all = False + self.closed = False + + def read(self, n=None): + # Fix up n + if n is None: + pass + else: + n = int(n) + if n < 0: + n = None + + # Can and must we read more? + if not self._have_all: + more = b"" + if n is None: + more = self.f.read() + self._have_all = True + else: + want_i = self._i + n + want_more = want_i - len(self._buffer) + if want_more > 0: + more = self.f.read(want_more) + if len(more) < want_more: + self._have_all = True + self._buffer += more + + # Read data from buffer and update pointer + if n is None: + res = self._buffer[self._i :] + else: + res = self._buffer[self._i : self._i + n] + self._i += len(res) + + return res + + def readline(self): + yield from self._file.readline() + + def tell(self): + return self._i + + def seek(self, i, mode=0): + # Mimic BytesIO behavior + + # Get the absolute new position + i = int(i) + if mode == 0: + if i < 0: + raise ValueError("negative seek value " + str(i)) + real_i = i + elif mode == 1: + real_i = max(0, self._i + i) # negative ok here + elif mode == 2: + if not self._have_all: + self.read() + real_i = max(0, len(self._buffer) + i) + else: + raise ValueError("invalid whence (%s, should be 0, 1 or 2)" % i) + + # Read some? + if real_i <= len(self._buffer): + pass # no need to read + elif not self._have_all: + assert real_i > self._i # if we don't have all, _i cannot be > _buffer + self.read(real_i - self._i) # sets self._i + + self._i = real_i + return self._i + + def close(self): + self.closed = True + self.f.close() + + def isatty(self): + return False + + def seekable(self): + return True + + +class InitializationError(Exception): + """The plugin could not initialize from the given request. + + This is a _internal_ error that is raised by plugins that fail to handle + a given request. We use this to differentiate incompatibility between + a plugin and a request from an actual error/bug inside a plugin. + + """ + + pass diff --git a/parrot/lib/python3.10/site-packages/imageio/core/request.pyi b/parrot/lib/python3.10/site-packages/imageio/core/request.pyi new file mode 100644 index 0000000000000000000000000000000000000000..8f73a0b4172d164554f810a9a26bb89751b311e0 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/imageio/core/request.pyi @@ -0,0 +1,90 @@ +from typing import BinaryIO, Optional, Dict, Any, Sequence, overload, Literal +from ..typing import ImageResource +import enum + +EXAMPLE_IMAGES: Dict[str, str] +RETURN_BYTES = "" +URI_BYTES = 1 +URI_FILE = 2 +URI_FILENAME = 3 +URI_ZIPPED = 4 +URI_HTTP = 5 +URI_FTP = 6 + +class IOMode(str, enum.Enum): + read = "r" + write = "w" + +class ImageMode(str, enum.Enum): + single_image = "i" + multi_image = "I" + single_volume = "v" + multi_volume = "V" + any_mode = "?" + +@enum.unique +class Mode(str, enum.Enum): + read_single_image = "ri" + read_multi_image = "rI" + read_single_volume = "rv" + read_multi_volume = "rV" + read_any = "r?" + write_single_image = "wi" + write_multi_image = "wI" + write_single_volume = "wv" + write_multi_volume = "wV" + write_any = "w?" + + @classmethod + def _missing_(cls, value: Any) -> Mode: ... + @property + def io_mode(self) -> IOMode: ... + @property + def image_mode(self) -> ImageMode: ... + +class InitializationError(Exception): ... + +class Request(object): + _uri_type: int + raw_uri: ImageResource + + @property + def filename(self) -> str: ... + @property + def extension(self) -> str: ... + @property + def format_hint(self) -> Optional[str]: ... + @format_hint.setter + def format_hint(self, format: str) -> None: ... + @property + def mode(self) -> Mode: ... + @property + def kwargs(self) -> Dict[str, Any]: ... + @property + def firstbytes(self) -> bytes: ... + def __init__( + self, + uri: ImageResource, + mode: str, + *, + extension: str = None, + format_hint: str = None, + **kwargs + ) -> None: ... + def _parse_uri(self, uri: ImageResource) -> None: ... + def get_file(self) -> BinaryIO: ... + def get_local_filename(self) -> str: ... + def finish(self) -> None: ... + def get_result(self) -> Optional[bytes]: ... + def _read_first_bytes(self, N: int = 256) -> bytes: ... + +def read_n_bytes(f: BinaryIO, N: int) -> bytes: ... + +class SeekableFileObject: + def __init__(self, f: BinaryIO) -> None: ... + def read(self, n: int = None) -> bytes: ... + def tell(self) -> int: ... + def seek(self, i: int, mode: int = 0) -> int: ... + def close(self) -> None: ... + def isatty(self) -> bool: ... + def seekable(self) -> bool: ... diff --git a/parrot/lib/python3.10/site-packages/imageio/core/util.py b/parrot/lib/python3.10/site-packages/imageio/core/util.py new file mode 100644 index 0000000000000000000000000000000000000000..bfb7e9fe9efe3110b73c3835fb873e352ffc6df4 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/imageio/core/util.py @@ -0,0 +1,561 @@ +# -*- coding: utf-8 -*- +# imageio is distributed under the terms of the (new) BSD License. + +""" +Various utilities for imageio +""" + + +from collections import OrderedDict +import numpy as np +import os +import re +import struct +import sys +import time +import logging + + +logger = logging.getLogger("imageio") + +IS_PYPY = "__pypy__" in sys.builtin_module_names +THIS_DIR = os.path.abspath(os.path.dirname(__file__)) + + +def urlopen(*args, **kwargs): + """Compatibility function for the urlopen function. Raises an + RuntimeError if urlopen could not be imported (which can occur in + frozen applications. + """ + try: + from urllib.request import urlopen + except ImportError: + raise RuntimeError("Could not import urlopen.") + return urlopen(*args, **kwargs) + + +def _precision_warn(p1, p2, extra=""): + t = ( + "Lossy conversion from {} to {}. {} Convert image to {} prior to " + "saving to suppress this warning." + ) + logger.warning(t.format(p1, p2, extra, p2)) + + +def image_as_uint(im, bitdepth=None): + """Convert the given image to uint (default: uint8) + + If the dtype already matches the desired format, it is returned + as-is. If the image is float, and all values are between 0 and 1, + the values are multiplied by np.power(2.0, bitdepth). In all other + situations, the values are scaled such that the minimum value + becomes 0 and the maximum value becomes np.power(2.0, bitdepth)-1 + (255 for 8-bit and 65535 for 16-bit). + """ + if not bitdepth: + bitdepth = 8 + if not isinstance(im, np.ndarray): + raise ValueError("Image must be a numpy array") + if bitdepth == 8: + out_type = np.uint8 + elif bitdepth == 16: + out_type = np.uint16 + else: + raise ValueError("Bitdepth must be either 8 or 16") + dtype_str1 = str(im.dtype) + dtype_str2 = out_type.__name__ + if (im.dtype == np.uint8 and bitdepth == 8) or ( + im.dtype == np.uint16 and bitdepth == 16 + ): + # Already the correct format? Return as-is + return im + if dtype_str1.startswith("float") and np.nanmin(im) >= 0 and np.nanmax(im) <= 1: + _precision_warn(dtype_str1, dtype_str2, "Range [0, 1].") + im = im.astype(np.float64) * (np.power(2.0, bitdepth) - 1) + 0.499999999 + elif im.dtype == np.uint16 and bitdepth == 8: + _precision_warn(dtype_str1, dtype_str2, "Losing 8 bits of resolution.") + im = np.right_shift(im, 8) + elif im.dtype == np.uint32: + _precision_warn( + dtype_str1, + dtype_str2, + "Losing {} bits of resolution.".format(32 - bitdepth), + ) + im = np.right_shift(im, 32 - bitdepth) + elif im.dtype == np.uint64: + _precision_warn( + dtype_str1, + dtype_str2, + "Losing {} bits of resolution.".format(64 - bitdepth), + ) + im = np.right_shift(im, 64 - bitdepth) + else: + mi = np.nanmin(im) + ma = np.nanmax(im) + if not np.isfinite(mi): + raise ValueError("Minimum image value is not finite") + if not np.isfinite(ma): + raise ValueError("Maximum image value is not finite") + if ma == mi: + return im.astype(out_type) + _precision_warn(dtype_str1, dtype_str2, "Range [{}, {}].".format(mi, ma)) + # Now make float copy before we scale + im = im.astype("float64") + # Scale the values between 0 and 1 then multiply by the max value + im = (im - mi) / (ma - mi) * (np.power(2.0, bitdepth) - 1) + 0.499999999 + assert np.nanmin(im) >= 0 + assert np.nanmax(im) < np.power(2.0, bitdepth) + return im.astype(out_type) + + +class Array(np.ndarray): + """Array(array, meta=None) + + A subclass of np.ndarray that has a meta attribute. Get the dictionary + that contains the meta data using ``im.meta``. Convert to a plain numpy + array using ``np.asarray(im)``. + + """ + + def __new__(cls, array, meta=None): + # Check + if not isinstance(array, np.ndarray): + raise ValueError("Array expects a numpy array.") + if not (meta is None or isinstance(meta, dict)): + raise ValueError("Array expects meta data to be a dict.") + # Convert and return + meta = meta if meta is not None else getattr(array, "meta", {}) + try: + ob = array.view(cls) + except AttributeError: # pragma: no cover + # Just return the original; no metadata on the array in Pypy! + return array + ob._copy_meta(meta) + return ob + + def _copy_meta(self, meta): + """Make a 2-level deep copy of the meta dictionary.""" + self._meta = Dict() + for key, val in meta.items(): + if isinstance(val, dict): + val = Dict(val) # Copy this level + self._meta[key] = val + + @property + def meta(self): + """The dict with the meta data of this image.""" + return self._meta + + def __array_finalize__(self, ob): + """So the meta info is maintained when doing calculations with + the array. + """ + if isinstance(ob, Array): + self._copy_meta(ob.meta) + else: + self._copy_meta({}) + + def __array_wrap__(self, out, context=None): + """So that we return a native numpy array (or scalar) when a + reducting ufunc is applied (such as sum(), std(), etc.) + """ + if not out.shape: + return out.dtype.type(out) # Scalar + elif out.shape != self.shape: + return out.view(type=np.ndarray) + elif not isinstance(out, Array): + return Array(out, self.meta) + else: + return out # Type Array + + +Image = Array # Alias for backwards compatibility + + +def asarray(a): + """Pypy-safe version of np.asarray. Pypy's np.asarray consumes a + *lot* of memory if the given array is an ndarray subclass. This + function does not. + """ + if isinstance(a, np.ndarray): + if IS_PYPY: # pragma: no cover + a = a.copy() # pypy has issues with base views + plain = a.view(type=np.ndarray) + return plain + return np.asarray(a) + + +class Dict(OrderedDict): + """A dict in which the keys can be get and set as if they were + attributes. Very convenient in combination with autocompletion. + + This Dict still behaves as much as possible as a normal dict, and + keys can be anything that are otherwise valid keys. However, + keys that are not valid identifiers or that are names of the dict + class (such as 'items' and 'copy') cannot be get/set as attributes. + """ + + __reserved_names__ = dir(OrderedDict()) # Also from OrderedDict + __pure_names__ = dir(dict()) + + def __getattribute__(self, key): + try: + return object.__getattribute__(self, key) + except AttributeError: + if key in self: + return self[key] + else: + raise + + def __setattr__(self, key, val): + if key in Dict.__reserved_names__: + # Either let OrderedDict do its work, or disallow + if key not in Dict.__pure_names__: + return OrderedDict.__setattr__(self, key, val) + else: + raise AttributeError( + "Reserved name, this key can only " + + "be set via ``d[%r] = X``" % key + ) + else: + # if isinstance(val, dict): val = Dict(val) -> no, makes a copy! + self[key] = val + + def __dir__(self): + def isidentifier(x): + return bool(re.match(r"[a-z_]\w*$", x, re.I)) + + names = [k for k in self.keys() if (isinstance(k, str) and isidentifier(k))] + return Dict.__reserved_names__ + names + + +class BaseProgressIndicator(object): + """BaseProgressIndicator(name) + + A progress indicator helps display the progress of a task to the + user. Progress can be pending, running, finished or failed. + + Each task has: + * a name - a short description of what needs to be done. + * an action - the current action in performing the task (e.g. a subtask) + * progress - how far the task is completed + * max - max number of progress units. If 0, the progress is indefinite + * unit - the units in which the progress is counted + * status - 0: pending, 1: in progress, 2: finished, 3: failed + + This class defines an abstract interface. Subclasses should implement + _start, _stop, _update_progress(progressText), _write(message). + """ + + def __init__(self, name): + self._name = name + self._action = "" + self._unit = "" + self._max = 0 + self._status = 0 + self._last_progress_update = 0 + + def start(self, action="", unit="", max=0): + """start(action='', unit='', max=0) + + Start the progress. Optionally specify an action, a unit, + and a maximum progress value. + """ + if self._status == 1: + self.finish() + self._action = action + self._unit = unit + self._max = max + # + self._progress = 0 + self._status = 1 + self._start() + + def status(self): + """status() + + Get the status of the progress - 0: pending, 1: in progress, + 2: finished, 3: failed + """ + return self._status + + def set_progress(self, progress=0, force=False): + """set_progress(progress=0, force=False) + + Set the current progress. To avoid unnecessary progress updates + this will only have a visual effect if the time since the last + update is > 0.1 seconds, or if force is True. + """ + self._progress = progress + # Update or not? + if not (force or (time.time() - self._last_progress_update > 0.1)): + return + self._last_progress_update = time.time() + # Compose new string + unit = self._unit or "" + progressText = "" + if unit == "%": + progressText = "%2.1f%%" % progress + elif self._max > 0: + percent = 100 * float(progress) / self._max + progressText = "%i/%i %s (%2.1f%%)" % (progress, self._max, unit, percent) + elif progress > 0: + if isinstance(progress, float): + progressText = "%0.4g %s" % (progress, unit) + else: + progressText = "%i %s" % (progress, unit) + # Update + self._update_progress(progressText) + + def increase_progress(self, extra_progress): + """increase_progress(extra_progress) + + Increase the progress by a certain amount. + """ + self.set_progress(self._progress + extra_progress) + + def finish(self, message=None): + """finish(message=None) + + Finish the progress, optionally specifying a message. This will + not set the progress to the maximum. + """ + self.set_progress(self._progress, True) # fore update + self._status = 2 + self._stop() + if message is not None: + self._write(message) + + def fail(self, message=None): + """fail(message=None) + + Stop the progress with a failure, optionally specifying a message. + """ + self.set_progress(self._progress, True) # fore update + self._status = 3 + self._stop() + message = "FAIL " + (message or "") + self._write(message) + + def write(self, message): + """write(message) + + Write a message during progress (such as a warning). + """ + if self.__class__ == BaseProgressIndicator: + # When this class is used as a dummy, print explicit message + print(message) + else: + return self._write(message) + + # Implementing classes should implement these + + def _start(self): + pass + + def _stop(self): + pass + + def _update_progress(self, progressText): + pass + + def _write(self, message): + pass + + +class StdoutProgressIndicator(BaseProgressIndicator): + """StdoutProgressIndicator(name) + + A progress indicator that shows the progress in stdout. It + assumes that the tty can appropriately deal with backspace + characters. + """ + + def _start(self): + self._chars_prefix, self._chars = "", "" + # Write message + if self._action: + self._chars_prefix = "%s (%s): " % (self._name, self._action) + else: + self._chars_prefix = "%s: " % self._name + sys.stdout.write(self._chars_prefix) + sys.stdout.flush() + + def _update_progress(self, progressText): + # If progress is unknown, at least make something move + if not progressText: + i1, i2, i3, i4 = "-\\|/" + M = {i1: i2, i2: i3, i3: i4, i4: i1} + progressText = M.get(self._chars, i1) + # Store new string and write + delChars = "\b" * len(self._chars) + self._chars = progressText + sys.stdout.write(delChars + self._chars) + sys.stdout.flush() + + def _stop(self): + self._chars = self._chars_prefix = "" + sys.stdout.write("\n") + sys.stdout.flush() + + def _write(self, message): + # Write message + delChars = "\b" * len(self._chars_prefix + self._chars) + sys.stdout.write(delChars + " " + message + "\n") + # Reprint progress text + sys.stdout.write(self._chars_prefix + self._chars) + sys.stdout.flush() + + +# From pyzolib/paths.py (https://bitbucket.org/pyzo/pyzolib/src/tip/paths.py) +def appdata_dir(appname=None, roaming=False): + """appdata_dir(appname=None, roaming=False) + + Get the path to the application directory, where applications are allowed + to write user specific files (e.g. configurations). For non-user specific + data, consider using common_appdata_dir(). + If appname is given, a subdir is appended (and created if necessary). + If roaming is True, will prefer a roaming directory (Windows Vista/7). + """ + + # Define default user directory + userDir = os.getenv("IMAGEIO_USERDIR", None) + if userDir is None: + userDir = os.path.expanduser("~") + if not os.path.isdir(userDir): # pragma: no cover + userDir = "/var/tmp" # issue #54 + + # Get system app data dir + path = None + if sys.platform.startswith("win"): + path1, path2 = os.getenv("LOCALAPPDATA"), os.getenv("APPDATA") + path = (path2 or path1) if roaming else (path1 or path2) + elif sys.platform.startswith("darwin"): + path = os.path.join(userDir, "Library", "Application Support") + # On Linux and as fallback + if not (path and os.path.isdir(path)): + path = userDir + + # Maybe we should store things local to the executable (in case of a + # portable distro or a frozen application that wants to be portable) + prefix = sys.prefix + if getattr(sys, "frozen", None): + prefix = os.path.abspath(os.path.dirname(sys.executable)) + for reldir in ("settings", "../settings"): + localpath = os.path.abspath(os.path.join(prefix, reldir)) + if os.path.isdir(localpath): # pragma: no cover + try: + open(os.path.join(localpath, "test.write"), "wb").close() + os.remove(os.path.join(localpath, "test.write")) + except IOError: + pass # We cannot write in this directory + else: + path = localpath + break + + # Get path specific for this app + if appname: + if path == userDir: + appname = "." + appname.lstrip(".") # Make it a hidden directory + path = os.path.join(path, appname) + if not os.path.isdir(path): # pragma: no cover + os.makedirs(path, exist_ok=True) + + # Done + return path + + +def resource_dirs(): + """resource_dirs() + + Get a list of directories where imageio resources may be located. + The first directory in this list is the "resources" directory in + the package itself. The second directory is the appdata directory + (~/.imageio on Linux). The list further contains the application + directory (for frozen apps), and may include additional directories + in the future. + """ + dirs = [resource_package_dir()] + # Resource dir baked in the package. + # Appdata directory + try: + dirs.append(appdata_dir("imageio")) + except Exception: # pragma: no cover + pass # The home dir may not be writable + # Directory where the app is located (mainly for frozen apps) + if getattr(sys, "frozen", None): + dirs.append(os.path.abspath(os.path.dirname(sys.executable))) + elif sys.path and sys.path[0]: + dirs.append(os.path.abspath(sys.path[0])) + return dirs + + +def resource_package_dir(): + """package_dir + + Get the resources directory in the imageio package installation + directory. + + Notes + ----- + This is a convenience method that is used by `resource_dirs` and + imageio entry point scripts. + """ + # Make pkg_resources optional if setuptools is not available + try: + # Avoid importing pkg_resources in the top level due to how slow it is + # https://github.com/pypa/setuptools/issues/510 + import pkg_resources + except ImportError: + pkg_resources = None + + if pkg_resources: + # The directory returned by `pkg_resources.resource_filename` + # also works with eggs. + pdir = pkg_resources.resource_filename("imageio", "resources") + else: + # If setuptools is not available, use fallback + pdir = os.path.abspath(os.path.join(THIS_DIR, "..", "resources")) + return pdir + + +def get_platform(): + """get_platform() + + Get a string that specifies the platform more specific than + sys.platform does. The result can be: linux32, linux64, win32, + win64, osx32, osx64. Other platforms may be added in the future. + """ + # Get platform + if sys.platform.startswith("linux"): + plat = "linux%i" + elif sys.platform.startswith("win"): + plat = "win%i" + elif sys.platform.startswith("darwin"): + plat = "osx%i" + elif sys.platform.startswith("freebsd"): + plat = "freebsd%i" + else: # pragma: no cover + return None + + return plat % (struct.calcsize("P") * 8) # 32 or 64 bits + + +def has_module(module_name): + """Check to see if a python module is available.""" + if sys.version_info > (3, 4): + import importlib + + name_parts = module_name.split(".") + for i in range(len(name_parts)): + if importlib.util.find_spec(".".join(name_parts[: i + 1])) is None: + return False + return True + else: # pragma: no cover + import imp + + try: + imp.find_module(module_name) + except ImportError: + return False + return True diff --git a/parrot/lib/python3.10/site-packages/imageio/plugins/__pycache__/_dicom.cpython-310.pyc b/parrot/lib/python3.10/site-packages/imageio/plugins/__pycache__/_dicom.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..584a40b67a07f8666a7b4b6b594f8cff45aa9af7 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/imageio/plugins/__pycache__/_dicom.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/imageio/plugins/__pycache__/_swf.cpython-310.pyc b/parrot/lib/python3.10/site-packages/imageio/plugins/__pycache__/_swf.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..38d1738a317d1fafe8b6d328d460a806fa11f329 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/imageio/plugins/__pycache__/_swf.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/imageio/plugins/__pycache__/bsdf.cpython-310.pyc b/parrot/lib/python3.10/site-packages/imageio/plugins/__pycache__/bsdf.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6ab31432bd7c809bb8e4091c8f9c0a0029b8f618 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/imageio/plugins/__pycache__/bsdf.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/imageio/plugins/__pycache__/feisem.cpython-310.pyc b/parrot/lib/python3.10/site-packages/imageio/plugins/__pycache__/feisem.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..20b1e00b4d1631965d299b75f192ac791d2a8a27 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/imageio/plugins/__pycache__/feisem.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/imageio/plugins/__pycache__/fits.cpython-310.pyc b/parrot/lib/python3.10/site-packages/imageio/plugins/__pycache__/fits.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a32dfff46302eade03965ae57b68adbc74c59b0b Binary files /dev/null and b/parrot/lib/python3.10/site-packages/imageio/plugins/__pycache__/fits.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/imageio/plugins/__pycache__/simpleitk.cpython-310.pyc b/parrot/lib/python3.10/site-packages/imageio/plugins/__pycache__/simpleitk.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f6ebd3d4ba1df964467ae34be5603ed127f6f377 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/imageio/plugins/__pycache__/simpleitk.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/markdown_it/__init__.py b/parrot/lib/python3.10/site-packages/markdown_it/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..882a0c3edb34dc6df159f1009c4500fbeafeb02a --- /dev/null +++ b/parrot/lib/python3.10/site-packages/markdown_it/__init__.py @@ -0,0 +1,5 @@ +"""A Python port of Markdown-It""" +__all__ = ("MarkdownIt",) +__version__ = "2.2.0" + +from .main import MarkdownIt diff --git a/parrot/lib/python3.10/site-packages/markdown_it/_compat.py b/parrot/lib/python3.10/site-packages/markdown_it/_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..12df1aa6f1e3a516751b8473045579b04f190554 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/markdown_it/_compat.py @@ -0,0 +1,10 @@ +from __future__ import annotations + +from collections.abc import Mapping +import sys +from typing import Any + +if sys.version_info >= (3, 10): + DATACLASS_KWARGS: Mapping[str, Any] = {"slots": True} +else: + DATACLASS_KWARGS: Mapping[str, Any] = {} diff --git a/parrot/lib/python3.10/site-packages/markdown_it/_punycode.py b/parrot/lib/python3.10/site-packages/markdown_it/_punycode.py new file mode 100644 index 0000000000000000000000000000000000000000..9ad24421599c47a56be36daa1d2a5cc62a4a51e4 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/markdown_it/_punycode.py @@ -0,0 +1,66 @@ +# Copyright 2014 Mathias Bynens +# Copyright 2021 Taneli Hukkinen +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +import codecs +import re + +REGEX_SEPARATORS = re.compile(r"[\x2E\u3002\uFF0E\uFF61]") +REGEX_NON_ASCII = re.compile(r"[^\0-\x7E]") + + +def encode(uni: str) -> str: + return codecs.encode(uni, encoding="punycode").decode() + + +def decode(ascii: str) -> str: + return codecs.decode(ascii, encoding="punycode") # type: ignore[call-overload] + + +def map_domain(string, fn): + parts = string.split("@") + result = "" + if len(parts) > 1: + # In email addresses, only the domain name should be punycoded. Leave + # the local part (i.e. everything up to `@`) intact. + result = parts[0] + "@" + string = parts[1] + labels = REGEX_SEPARATORS.split(string) + encoded = ".".join(fn(label) for label in labels) + return result + encoded + + +def to_unicode(obj: str) -> str: + def mapping(obj: str) -> str: + if obj.startswith("xn--"): + return decode(obj[4:].lower()) + return obj + + return map_domain(obj, mapping) + + +def to_ascii(obj: str) -> str: + def mapping(obj: str) -> str: + if REGEX_NON_ASCII.search(obj): + return "xn--" + encode(obj) + return obj + + return map_domain(obj, mapping) diff --git a/parrot/lib/python3.10/site-packages/markdown_it/main.py b/parrot/lib/python3.10/site-packages/markdown_it/main.py new file mode 100644 index 0000000000000000000000000000000000000000..7faac5adac3908909d9f6b9fac330ab9b51bc02f --- /dev/null +++ b/parrot/lib/python3.10/site-packages/markdown_it/main.py @@ -0,0 +1,331 @@ +from __future__ import annotations + +from collections.abc import Callable, Generator, Iterable, Mapping, MutableMapping +from contextlib import contextmanager +from typing import Any + +from . import helpers, presets # noqa F401 +from .common import normalize_url, utils # noqa F401 +from .parser_block import ParserBlock # noqa F401 +from .parser_core import ParserCore # noqa F401 +from .parser_inline import ParserInline # noqa F401 +from .renderer import RendererHTML, RendererProtocol +from .rules_core.state_core import StateCore +from .token import Token +from .utils import OptionsDict + +try: + import linkify_it +except ModuleNotFoundError: + linkify_it = None + + +_PRESETS = { + "default": presets.default.make(), + "js-default": presets.js_default.make(), + "zero": presets.zero.make(), + "commonmark": presets.commonmark.make(), + "gfm-like": presets.gfm_like.make(), +} + + +class MarkdownIt: + def __init__( + self, + config: str | Mapping = "commonmark", + options_update: Mapping | None = None, + *, + renderer_cls: Callable[[MarkdownIt], RendererProtocol] = RendererHTML, + ): + """Main parser class + + :param config: name of configuration to load or a pre-defined dictionary + :param options_update: dictionary that will be merged into ``config["options"]`` + :param renderer_cls: the class to load as the renderer: + ``self.renderer = renderer_cls(self) + """ + # add modules + self.utils = utils + self.helpers: Any = helpers + + # initialise classes + self.inline = ParserInline() + self.block = ParserBlock() + self.core = ParserCore() + self.renderer = renderer_cls(self) + self.linkify = linkify_it.LinkifyIt() if linkify_it else None + + # set the configuration + if options_update and not isinstance(options_update, Mapping): + # catch signature change where renderer_cls was not used as a key-word + raise TypeError( + f"options_update should be a mapping: {options_update}" + "\n(Perhaps you intended this to be the renderer_cls?)" + ) + self.configure(config, options_update=options_update) + + def __repr__(self) -> str: + return f"{self.__class__.__module__}.{self.__class__.__name__}()" + + def __getitem__(self, name: str) -> Any: + return { + "inline": self.inline, + "block": self.block, + "core": self.core, + "renderer": self.renderer, + }[name] + + def set(self, options: MutableMapping) -> None: + """Set parser options (in the same format as in constructor). + Probably, you will never need it, but you can change options after constructor call. + + __Note:__ To achieve the best possible performance, don't modify a + `markdown-it` instance options on the fly. If you need multiple configurations + it's best to create multiple instances and initialize each with separate config. + """ + self.options = OptionsDict(options) + + def configure( + self, presets: str | Mapping, options_update: Mapping | None = None + ) -> MarkdownIt: + """Batch load of all options and component settings. + This is an internal method, and you probably will not need it. + But if you will - see available presets and data structure + [here](https://github.com/markdown-it/markdown-it/tree/master/lib/presets) + + We strongly recommend to use presets instead of direct config loads. + That will give better compatibility with next versions. + """ + if isinstance(presets, str): + if presets not in _PRESETS: + raise KeyError(f"Wrong `markdown-it` preset '{presets}', check name") + config = _PRESETS[presets] + else: + config = presets + + if not config: + raise ValueError("Wrong `markdown-it` config, can't be empty") + + options = config.get("options", {}) or {} + if options_update: + options = {**options, **options_update} + + self.set(options) + + if "components" in config: + for name, component in config["components"].items(): + rules = component.get("rules", None) + if rules: + self[name].ruler.enableOnly(rules) + rules2 = component.get("rules2", None) + if rules2: + self[name].ruler2.enableOnly(rules2) + + return self + + def get_all_rules(self) -> dict[str, list[str]]: + """Return the names of all active rules.""" + rules = { + chain: self[chain].ruler.get_all_rules() + for chain in ["core", "block", "inline"] + } + rules["inline2"] = self.inline.ruler2.get_all_rules() + return rules + + def get_active_rules(self) -> dict[str, list[str]]: + """Return the names of all active rules.""" + rules = { + chain: self[chain].ruler.get_active_rules() + for chain in ["core", "block", "inline"] + } + rules["inline2"] = self.inline.ruler2.get_active_rules() + return rules + + def enable( + self, names: str | Iterable[str], ignoreInvalid: bool = False + ) -> MarkdownIt: + """Enable list or rules. (chainable) + + :param names: rule name or list of rule names to enable. + :param ignoreInvalid: set `true` to ignore errors when rule not found. + + It will automatically find appropriate components, + containing rules with given names. If rule not found, and `ignoreInvalid` + not set - throws exception. + + Example:: + + md = MarkdownIt().enable(['sub', 'sup']).disable('smartquotes') + + """ + result = [] + + if isinstance(names, str): + names = [names] + + for chain in ["core", "block", "inline"]: + result.extend(self[chain].ruler.enable(names, True)) + result.extend(self.inline.ruler2.enable(names, True)) + + missed = [name for name in names if name not in result] + if missed and not ignoreInvalid: + raise ValueError(f"MarkdownIt. Failed to enable unknown rule(s): {missed}") + + return self + + def disable( + self, names: str | Iterable[str], ignoreInvalid: bool = False + ) -> MarkdownIt: + """The same as [[MarkdownIt.enable]], but turn specified rules off. (chainable) + + :param names: rule name or list of rule names to disable. + :param ignoreInvalid: set `true` to ignore errors when rule not found. + + """ + result = [] + + if isinstance(names, str): + names = [names] + + for chain in ["core", "block", "inline"]: + result.extend(self[chain].ruler.disable(names, True)) + result.extend(self.inline.ruler2.disable(names, True)) + + missed = [name for name in names if name not in result] + if missed and not ignoreInvalid: + raise ValueError(f"MarkdownIt. Failed to disable unknown rule(s): {missed}") + return self + + @contextmanager + def reset_rules(self) -> Generator[None, None, None]: + """A context manager, that will reset the current enabled rules on exit.""" + chain_rules = self.get_active_rules() + yield + for chain, rules in chain_rules.items(): + if chain != "inline2": + self[chain].ruler.enableOnly(rules) + self.inline.ruler2.enableOnly(chain_rules["inline2"]) + + def add_render_rule(self, name: str, function: Callable, fmt: str = "html") -> None: + """Add a rule for rendering a particular Token type. + + Only applied when ``renderer.__output__ == fmt`` + """ + if self.renderer.__output__ == fmt: + self.renderer.rules[name] = function.__get__(self.renderer) # type: ignore + + def use(self, plugin: Callable, *params, **options) -> MarkdownIt: + """Load specified plugin with given params into current parser instance. (chainable) + + It's just a sugar to call `plugin(md, params)` with curring. + + Example:: + + def func(tokens, idx): + tokens[idx].content = tokens[idx].content.replace('foo', 'bar') + md = MarkdownIt().use(plugin, 'foo_replace', 'text', func) + + """ + plugin(self, *params, **options) + return self + + def parse(self, src: str, env: MutableMapping | None = None) -> list[Token]: + """Parse the source string to a token stream + + :param src: source string + :param env: environment sandbox + + Parse input string and return list of block tokens (special token type + "inline" will contain list of inline tokens). + + `env` is used to pass data between "distributed" rules and return additional + metadata like reference info, needed for the renderer. It also can be used to + inject data in specific cases. Usually, you will be ok to pass `{}`, + and then pass updated object to renderer. + """ + env = {} if env is None else env + if not isinstance(env, MutableMapping): + raise TypeError(f"Input data should be a MutableMapping, not {type(env)}") + if not isinstance(src, str): + raise TypeError(f"Input data should be a string, not {type(src)}") + state = StateCore(src, self, env) + self.core.process(state) + return state.tokens + + def render(self, src: str, env: MutableMapping | None = None) -> Any: + """Render markdown string into html. It does all magic for you :). + + :param src: source string + :param env: environment sandbox + :returns: The output of the loaded renderer + + `env` can be used to inject additional metadata (`{}` by default). + But you will not need it with high probability. See also comment + in [[MarkdownIt.parse]]. + """ + env = {} if env is None else env + return self.renderer.render(self.parse(src, env), self.options, env) + + def parseInline(self, src: str, env: MutableMapping | None = None) -> list[Token]: + """The same as [[MarkdownIt.parse]] but skip all block rules. + + :param src: source string + :param env: environment sandbox + + It returns the + block tokens list with the single `inline` element, containing parsed inline + tokens in `children` property. Also updates `env` object. + """ + env = {} if env is None else env + if not isinstance(env, MutableMapping): + raise TypeError(f"Input data should be an MutableMapping, not {type(env)}") + if not isinstance(src, str): + raise TypeError(f"Input data should be a string, not {type(src)}") + state = StateCore(src, self, env) + state.inlineMode = True + self.core.process(state) + return state.tokens + + def renderInline(self, src: str, env: MutableMapping | None = None) -> Any: + """Similar to [[MarkdownIt.render]] but for single paragraph content. + + :param src: source string + :param env: environment sandbox + + Similar to [[MarkdownIt.render]] but for single paragraph content. Result + will NOT be wrapped into `

` tags. + """ + env = {} if env is None else env + return self.renderer.render(self.parseInline(src, env), self.options, env) + + # link methods + + def validateLink(self, url: str) -> bool: + """Validate if the URL link is allowed in output. + + This validator can prohibit more than really needed to prevent XSS. + It's a tradeoff to keep code simple and to be secure by default. + + Note: the url should be normalized at this point, and existing entities decoded. + """ + return normalize_url.validateLink(url) + + def normalizeLink(self, url: str) -> str: + """Normalize destination URLs in links + + :: + + [label]: destination 'title' + ^^^^^^^^^^^ + """ + return normalize_url.normalizeLink(url) + + def normalizeLinkText(self, link: str) -> str: + """Normalize autolink content + + :: + + + ~~~~~~~~~~~ + """ + return normalize_url.normalizeLinkText(link) diff --git a/parrot/lib/python3.10/site-packages/markdown_it/parser_block.py b/parrot/lib/python3.10/site-packages/markdown_it/parser_block.py new file mode 100644 index 0000000000000000000000000000000000000000..f331ec54b28c9d9955ccee2ed3f84cc1548be3fe --- /dev/null +++ b/parrot/lib/python3.10/site-packages/markdown_it/parser_block.py @@ -0,0 +1,109 @@ +"""Block-level tokenizer.""" +from __future__ import annotations + +import logging + +from . import rules_block +from .ruler import Ruler +from .rules_block.state_block import StateBlock +from .token import Token + +LOGGER = logging.getLogger(__name__) + + +_rules: list[tuple] = [ + # First 2 params - rule name & source. Secondary array - list of rules, + # which can be terminated by this one. + ("table", rules_block.table, ["paragraph", "reference"]), + ("code", rules_block.code), + ("fence", rules_block.fence, ["paragraph", "reference", "blockquote", "list"]), + ( + "blockquote", + rules_block.blockquote, + ["paragraph", "reference", "blockquote", "list"], + ), + ("hr", rules_block.hr, ["paragraph", "reference", "blockquote", "list"]), + ("list", rules_block.list_block, ["paragraph", "reference", "blockquote"]), + ("reference", rules_block.reference), + ("html_block", rules_block.html_block, ["paragraph", "reference", "blockquote"]), + ("heading", rules_block.heading, ["paragraph", "reference", "blockquote"]), + ("lheading", rules_block.lheading), + ("paragraph", rules_block.paragraph), +] + + +class ParserBlock: + """ + ParserBlock#ruler -> Ruler + + [[Ruler]] instance. Keep configuration of block rules. + """ + + def __init__(self): + self.ruler = Ruler() + for data in _rules: + name = data[0] + rule = data[1] + self.ruler.push(name, rule, {"alt": data[2] if len(data) > 2 else []}) + + def tokenize( + self, state: StateBlock, startLine: int, endLine: int, silent: bool = False + ) -> None: + """Generate tokens for input range.""" + rules = self.ruler.getRules("") + line = startLine + maxNesting = state.md.options.maxNesting + hasEmptyLines = False + + while line < endLine: + state.line = line = state.skipEmptyLines(line) + if line >= endLine: + break + if state.sCount[line] < state.blkIndent: + # Termination condition for nested calls. + # Nested calls currently used for blockquotes & lists + break + if state.level >= maxNesting: + # If nesting level exceeded - skip tail to the end. + # That's not ordinary situation and we should not care about content. + state.line = endLine + break + + # Try all possible rules. + # On success, rule should: + # - update `state.line` + # - update `state.tokens` + # - return True + for rule in rules: + if rule(state, line, endLine, False): + break + + # set state.tight if we had an empty line before current tag + # i.e. latest empty line should not count + state.tight = not hasEmptyLines + + line = state.line + + # paragraph might "eat" one newline after it in nested lists + if (line - 1) < endLine and state.isEmpty(line - 1): + hasEmptyLines = True + + if line < endLine and state.isEmpty(line): + hasEmptyLines = True + line += 1 + state.line = line + + def parse( + self, + src: str, + md, + env, + outTokens: list[Token], + ords: tuple[int, ...] | None = None, + ) -> list[Token] | None: + """Process input string and push block tokens into `outTokens`.""" + if not src: + return None + state = StateBlock(src, md, env, outTokens, ords) + self.tokenize(state, state.line, state.lineMax) + return state.tokens diff --git a/parrot/lib/python3.10/site-packages/markdown_it/parser_core.py b/parrot/lib/python3.10/site-packages/markdown_it/parser_core.py new file mode 100644 index 0000000000000000000000000000000000000000..32209b32a1b3c60e0cf71603b0493a9ffcf72318 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/markdown_it/parser_core.py @@ -0,0 +1,32 @@ +""" + * class Core + * + * Top-level rules executor. Glues block/inline parsers and does intermediate + * transformations. +""" +from __future__ import annotations + +from .ruler import RuleFunc, Ruler +from .rules_core import block, inline, linkify, normalize, replace, smartquotes +from .rules_core.state_core import StateCore + +_rules: list[tuple[str, RuleFunc]] = [ + ("normalize", normalize), + ("block", block), + ("inline", inline), + ("linkify", linkify), + ("replacements", replace), + ("smartquotes", smartquotes), +] + + +class ParserCore: + def __init__(self): + self.ruler = Ruler() + for name, rule in _rules: + self.ruler.push(name, rule) + + def process(self, state: StateCore) -> None: + """Executes core chain rules.""" + for rule in self.ruler.getRules(""): + rule(state) diff --git a/parrot/lib/python3.10/site-packages/markdown_it/parser_inline.py b/parrot/lib/python3.10/site-packages/markdown_it/parser_inline.py new file mode 100644 index 0000000000000000000000000000000000000000..b61c990ba483177c3536b9067a4b2b119414ac87 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/markdown_it/parser_inline.py @@ -0,0 +1,124 @@ +"""Tokenizes paragraph content. +""" +from __future__ import annotations + +from . import rules_inline +from .ruler import RuleFunc, Ruler +from .rules_inline.state_inline import StateInline +from .token import Token + +# Parser rules +_rules: list[tuple[str, RuleFunc]] = [ + ("text", rules_inline.text), + ("newline", rules_inline.newline), + ("escape", rules_inline.escape), + ("backticks", rules_inline.backtick), + ("strikethrough", rules_inline.strikethrough.tokenize), + ("emphasis", rules_inline.emphasis.tokenize), + ("link", rules_inline.link), + ("image", rules_inline.image), + ("autolink", rules_inline.autolink), + ("html_inline", rules_inline.html_inline), + ("entity", rules_inline.entity), +] + +_rules2: list[tuple[str, RuleFunc]] = [ + ("balance_pairs", rules_inline.link_pairs), + ("strikethrough", rules_inline.strikethrough.postProcess), + ("emphasis", rules_inline.emphasis.postProcess), + ("text_collapse", rules_inline.text_collapse), +] + + +class ParserInline: + def __init__(self): + self.ruler = Ruler() + for name, rule in _rules: + self.ruler.push(name, rule) + # Second ruler used for post-processing (e.g. in emphasis-like rules) + self.ruler2 = Ruler() + for name, rule2 in _rules2: + self.ruler2.push(name, rule2) + + def skipToken(self, state: StateInline) -> None: + """Skip single token by running all rules in validation mode; + returns `True` if any rule reported success + """ + ok = False + pos = state.pos + rules = self.ruler.getRules("") + maxNesting = state.md.options["maxNesting"] + cache = state.cache + + if pos in cache: + state.pos = cache[pos] + return + + if state.level < maxNesting: + for rule in rules: + # Increment state.level and decrement it later to limit recursion. + # It's harmless to do here, because no tokens are created. + # But ideally, we'd need a separate private state variable for this purpose. + state.level += 1 + ok = rule(state, True) + state.level -= 1 + if ok: + break + else: + # Too much nesting, just skip until the end of the paragraph. + # + # NOTE: this will cause links to behave incorrectly in the following case, + # when an amount of `[` is exactly equal to `maxNesting + 1`: + # + # [[[[[[[[[[[[[[[[[[[[[foo]() + # + # TODO: remove this workaround when CM standard will allow nested links + # (we can replace it by preventing links from being parsed in + # validation mode) + # + state.pos = state.posMax + + if not ok: + state.pos += 1 + cache[pos] = state.pos + + def tokenize(self, state: StateInline) -> None: + """Generate tokens for input range.""" + ok = False + rules = self.ruler.getRules("") + end = state.posMax + maxNesting = state.md.options["maxNesting"] + + while state.pos < end: + # Try all possible rules. + # On success, rule should: + # + # - update `state.pos` + # - update `state.tokens` + # - return true + + if state.level < maxNesting: + for rule in rules: + ok = rule(state, False) + if ok: + break + + if ok: + if state.pos >= end: + break + continue + + state.pending += state.src[state.pos] + state.pos += 1 + + if state.pending: + state.pushPending() + + def parse(self, src: str, md, env, tokens: list[Token]) -> list[Token]: + """Process input string and push inline tokens into `tokens`""" + state = StateInline(src, md, env, tokens) + self.tokenize(state) + rules2 = self.ruler2.getRules("") + for rule in rules2: + rule(state) + return state.tokens diff --git a/parrot/lib/python3.10/site-packages/markdown_it/port.yaml b/parrot/lib/python3.10/site-packages/markdown_it/port.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a6718fda85ba528fcb3416e8906ffea073c11e76 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/markdown_it/port.yaml @@ -0,0 +1,49 @@ +- package: markdown-it/markdown-it + version: 12.2.0 + commit: 6e2de08a0b03d3d0dcc524b89710ce05f83a0283 + date: Aug 2, 2021 + notes: + - Rename variables that use python built-in names, e.g. + - `max` -> `maximum` + - `len` -> `length` + - `str` -> `string` + - | + Convert JS `for` loops to `while` loops + this is generally the main difference between the codes, + because in python you can't do e.g. `for {i=1;i) + "breaks": False, # Convert '\n' in paragraphs into
+ "langPrefix": "language-", # CSS language prefix for fenced blocks + # Highlighter function. Should return escaped HTML, + # or '' if the source string is not changed and should be escaped externally. + # If result starts with ) + "breaks": False, # Convert '\n' in paragraphs into
+ "langPrefix": "language-", # CSS language prefix for fenced blocks + # Highlighter function. Should return escaped HTML, + # or '' if the source string is not changed and should be escaped externally. + # If result starts with ) + "breaks": False, # Convert '\n' in paragraphs into
+ "langPrefix": "language-", # CSS language prefix for fenced blocks + # Highlighter function. Should return escaped HTML, + # or '' if the source string is not changed and should be escaped externally. + # If result starts with Any: + ... + + +class RendererHTML(RendererProtocol): + """Contains render rules for tokens. Can be updated and extended. + + Example: + + Each rule is called as independent static function with fixed signature: + + :: + + class Renderer: + def token_type_name(self, tokens, idx, options, env) { + # ... + return renderedHTML + + :: + + class CustomRenderer(RendererHTML): + def strong_open(self, tokens, idx, options, env): + return '' + def strong_close(self, tokens, idx, options, env): + return '' + + md = MarkdownIt(renderer_cls=CustomRenderer) + + result = md.render(...) + + See https://github.com/markdown-it/markdown-it/blob/master/lib/renderer.js + for more details and examples. + """ + + __output__ = "html" + + def __init__(self, parser=None): + self.rules = { + k: v + for k, v in inspect.getmembers(self, predicate=inspect.ismethod) + if not (k.startswith("render") or k.startswith("_")) + } + + def render( + self, tokens: Sequence[Token], options: OptionsDict, env: MutableMapping + ) -> str: + """Takes token stream and generates HTML. + + :param tokens: list on block tokens to render + :param options: params of parser instance + :param env: additional data from parsed input + + """ + result = "" + + for i, token in enumerate(tokens): + if token.type == "inline": + if token.children: + result += self.renderInline(token.children, options, env) + elif token.type in self.rules: + result += self.rules[token.type](tokens, i, options, env) + else: + result += self.renderToken(tokens, i, options, env) + + return result + + def renderInline( + self, tokens: Sequence[Token], options: OptionsDict, env: MutableMapping + ) -> str: + """The same as ``render``, but for single token of `inline` type. + + :param tokens: list on block tokens to render + :param options: params of parser instance + :param env: additional data from parsed input (references, for example) + """ + result = "" + + for i, token in enumerate(tokens): + if token.type in self.rules: + result += self.rules[token.type](tokens, i, options, env) + else: + result += self.renderToken(tokens, i, options, env) + + return result + + def renderToken( + self, + tokens: Sequence[Token], + idx: int, + options: OptionsDict, + env: MutableMapping, + ) -> str: + """Default token renderer. + + Can be overridden by custom function + + :param idx: token index to render + :param options: params of parser instance + """ + result = "" + needLf = False + token = tokens[idx] + + # Tight list paragraphs + if token.hidden: + return "" + + # Insert a newline between hidden paragraph and subsequent opening + # block-level tag. + # + # For example, here we should insert a newline before blockquote: + # - a + # > + # + if token.block and token.nesting != -1 and idx and tokens[idx - 1].hidden: + result += "\n" + + # Add token name, e.g. ``. + # + needLf = False + + result += ">\n" if needLf else ">" + + return result + + @staticmethod + def renderAttrs(token: Token) -> str: + """Render token attributes to string.""" + result = "" + + for key, value in token.attrItems(): + result += " " + escapeHtml(key) + '="' + escapeHtml(str(value)) + '"' + + return result + + def renderInlineAsText( + self, + tokens: Sequence[Token] | None, + options: OptionsDict, + env: MutableMapping, + ) -> str: + """Special kludge for image `alt` attributes to conform CommonMark spec. + + Don't try to use it! Spec requires to show `alt` content with stripped markup, + instead of simple escaping. + + :param tokens: list on block tokens to render + :param options: params of parser instance + :param env: additional data from parsed input + """ + result = "" + + for token in tokens or []: + if token.type == "text": + result += token.content + elif token.type == "image": + if token.children: + result += self.renderInlineAsText(token.children, options, env) + elif token.type == "softbreak": + result += "\n" + + return result + + ################################################### + + def code_inline(self, tokens: Sequence[Token], idx: int, options, env) -> str: + token = tokens[idx] + return ( + "" + + escapeHtml(tokens[idx].content) + + "" + ) + + def code_block( + self, + tokens: Sequence[Token], + idx: int, + options: OptionsDict, + env: MutableMapping, + ) -> str: + token = tokens[idx] + + return ( + "" + + escapeHtml(tokens[idx].content) + + "\n" + ) + + def fence( + self, + tokens: Sequence[Token], + idx: int, + options: OptionsDict, + env: MutableMapping, + ) -> str: + token = tokens[idx] + info = unescapeAll(token.info).strip() if token.info else "" + langName = "" + langAttrs = "" + + if info: + arr = info.split(maxsplit=1) + langName = arr[0] + if len(arr) == 2: + langAttrs = arr[1] + + if options.highlight: + highlighted = options.highlight( + token.content, langName, langAttrs + ) or escapeHtml(token.content) + else: + highlighted = escapeHtml(token.content) + + if highlighted.startswith("" + + highlighted + + "\n" + ) + + return ( + "

"
+            + highlighted
+            + "
\n" + ) + + def image( + self, + tokens: Sequence[Token], + idx: int, + options: OptionsDict, + env: MutableMapping, + ) -> str: + token = tokens[idx] + + # "alt" attr MUST be set, even if empty. Because it's mandatory and + # should be placed on proper position for tests. + if token.children: + token.attrSet("alt", self.renderInlineAsText(token.children, options, env)) + else: + token.attrSet("alt", "") + + return self.renderToken(tokens, idx, options, env) + + def hardbreak( + self, tokens: Sequence[Token], idx: int, options: OptionsDict, *args + ) -> str: + return "
\n" if options.xhtmlOut else "
\n" + + def softbreak( + self, tokens: Sequence[Token], idx: int, options: OptionsDict, *args + ) -> str: + return ( + ("
\n" if options.xhtmlOut else "
\n") if options.breaks else "\n" + ) + + def text(self, tokens: Sequence[Token], idx: int, *args) -> str: + return escapeHtml(tokens[idx].content) + + def html_block(self, tokens: Sequence[Token], idx: int, *args) -> str: + return tokens[idx].content + + def html_inline(self, tokens: Sequence[Token], idx: int, *args) -> str: + return tokens[idx].content diff --git a/parrot/lib/python3.10/site-packages/markdown_it/ruler.py b/parrot/lib/python3.10/site-packages/markdown_it/ruler.py new file mode 100644 index 0000000000000000000000000000000000000000..11b937a0d8cab3386996deb90b93d3272097e745 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/markdown_it/ruler.py @@ -0,0 +1,237 @@ +""" +class Ruler + +Helper class, used by [[MarkdownIt#core]], [[MarkdownIt#block]] and +[[MarkdownIt#inline]] to manage sequences of functions (rules): + +- keep rules in defined order +- assign the name to each rule +- enable/disable rules +- add/replace rules +- allow assign rules to additional named chains (in the same) +- caching lists of active rules + +You will not need use this class directly until write plugins. For simple +rules control use [[MarkdownIt.disable]], [[MarkdownIt.enable]] and +[[MarkdownIt.use]]. +""" +from __future__ import annotations + +from collections.abc import Callable, Iterable, MutableMapping +from dataclasses import dataclass, field +from typing import TYPE_CHECKING + +from markdown_it._compat import DATACLASS_KWARGS + +if TYPE_CHECKING: + from markdown_it import MarkdownIt + + +class StateBase: + srcCharCode: tuple[int, ...] + + def __init__(self, src: str, md: MarkdownIt, env: MutableMapping): + self.src = src + self.env = env + self.md = md + + @property + def src(self) -> str: + return self._src + + @src.setter + def src(self, value: str) -> None: + self._src = value + self.srcCharCode = tuple(ord(c) for c in self.src) + + +# The first positional arg is always a subtype of `StateBase`. Other +# arguments may or may not exist, based on the rule's type (block, +# core, inline). Return type is either `None` or `bool` based on the +# rule's type. +RuleFunc = Callable + + +@dataclass(**DATACLASS_KWARGS) +class Rule: + name: str + enabled: bool + fn: RuleFunc = field(repr=False) + alt: list[str] + + +class Ruler: + def __init__(self): + # List of added rules. + self.__rules__: list[Rule] = [] + # Cached rule chains. + # First level - chain name, '' for default. + # Second level - diginal anchor for fast filtering by charcodes. + self.__cache__: dict[str, list[RuleFunc]] | None = None + + def __find__(self, name: str) -> int: + """Find rule index by name""" + for i, rule in enumerate(self.__rules__): + if rule.name == name: + return i + return -1 + + def __compile__(self) -> None: + """Build rules lookup cache""" + chains = {""} + # collect unique names + for rule in self.__rules__: + if not rule.enabled: + continue + for name in rule.alt: + chains.add(name) + self.__cache__ = {} + for chain in chains: + self.__cache__[chain] = [] + for rule in self.__rules__: + if not rule.enabled: + continue + if chain and (chain not in rule.alt): + continue + self.__cache__[chain].append(rule.fn) + + def at(self, ruleName: str, fn: RuleFunc, options=None): + """Replace rule by name with new function & options. + + :param ruleName: rule name to replace. + :param fn: new rule function. + :param options: new rule options (not mandatory). + :raises: KeyError if name not found + """ + index = self.__find__(ruleName) + options = options or {} + if index == -1: + raise KeyError(f"Parser rule not found: {ruleName}") + self.__rules__[index].fn = fn + self.__rules__[index].alt = options.get("alt", []) + self.__cache__ = None + + def before(self, beforeName: str, ruleName: str, fn: RuleFunc, options=None): + """Add new rule to chain before one with given name. + + :param beforeName: new rule will be added before this one. + :param ruleName: new rule will be added before this one. + :param fn: new rule function. + :param options: new rule options (not mandatory). + :raises: KeyError if name not found + """ + index = self.__find__(beforeName) + options = options or {} + if index == -1: + raise KeyError(f"Parser rule not found: {beforeName}") + self.__rules__.insert(index, Rule(ruleName, True, fn, options.get("alt", []))) + self.__cache__ = None + + def after(self, afterName: str, ruleName: str, fn: RuleFunc, options=None): + """Add new rule to chain after one with given name. + + :param afterName: new rule will be added after this one. + :param ruleName: new rule will be added after this one. + :param fn: new rule function. + :param options: new rule options (not mandatory). + :raises: KeyError if name not found + """ + index = self.__find__(afterName) + options = options or {} + if index == -1: + raise KeyError(f"Parser rule not found: {afterName}") + self.__rules__.insert( + index + 1, Rule(ruleName, True, fn, options.get("alt", [])) + ) + self.__cache__ = None + + def push(self, ruleName: str, fn: RuleFunc, options=None): + """Push new rule to the end of chain. + + :param ruleName: new rule will be added to the end of chain. + :param fn: new rule function. + :param options: new rule options (not mandatory). + + """ + self.__rules__.append(Rule(ruleName, True, fn, (options or {}).get("alt", []))) + self.__cache__ = None + + def enable(self, names: str | Iterable[str], ignoreInvalid: bool = False): + """Enable rules with given names. + + :param names: name or list of rule names to enable. + :param ignoreInvalid: ignore errors when rule not found + :raises: KeyError if name not found and not ignoreInvalid + :return: list of found rule names + """ + if isinstance(names, str): + names = [names] + result = [] + for name in names: + idx = self.__find__(name) + if (idx < 0) and ignoreInvalid: + continue + if (idx < 0) and not ignoreInvalid: + raise KeyError(f"Rules manager: invalid rule name {name}") + self.__rules__[idx].enabled = True + result.append(name) + self.__cache__ = None + return result + + def enableOnly(self, names: str | Iterable[str], ignoreInvalid: bool = False): + """Enable rules with given names, and disable everything else. + + :param names: name or list of rule names to enable. + :param ignoreInvalid: ignore errors when rule not found + :raises: KeyError if name not found and not ignoreInvalid + :return: list of found rule names + """ + if isinstance(names, str): + names = [names] + for rule in self.__rules__: + rule.enabled = False + self.enable(names, ignoreInvalid) + + def disable(self, names: str | Iterable[str], ignoreInvalid: bool = False): + """Disable rules with given names. + + :param names: name or list of rule names to enable. + :param ignoreInvalid: ignore errors when rule not found + :raises: KeyError if name not found and not ignoreInvalid + :return: list of found rule names + """ + if isinstance(names, str): + names = [names] + result = [] + for name in names: + idx = self.__find__(name) + if (idx < 0) and ignoreInvalid: + continue + if (idx < 0) and not ignoreInvalid: + raise KeyError(f"Rules manager: invalid rule name {name}") + self.__rules__[idx].enabled = False + result.append(name) + self.__cache__ = None + return result + + def getRules(self, chainName: str) -> list[RuleFunc]: + """Return array of active functions (rules) for given chain name. + It analyzes rules configuration, compiles caches if not exists and returns result. + + Default chain name is `''` (empty string). It can't be skipped. + That's done intentionally, to keep signature monomorphic for high speed. + + """ + if self.__cache__ is None: + self.__compile__() + assert self.__cache__ is not None + # Chain can be empty, if rules disabled. But we still have to return Array. + return self.__cache__.get(chainName, []) or [] + + def get_all_rules(self) -> list[str]: + """Return all available rule names.""" + return [r.name for r in self.__rules__] + + def get_active_rules(self) -> list[str]: + """Return the active rule names.""" + return [r.name for r in self.__rules__ if r.enabled] diff --git a/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/__init__.py b/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f27907ce5133c345f686143c155f3e8523ab46d5 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/__init__.py @@ -0,0 +1,29 @@ +__all__ = ( + "StateInline", + "text", + "text_collapse", + "link_pairs", + "escape", + "newline", + "backtick", + "emphasis", + "image", + "link", + "autolink", + "entity", + "html_inline", + "strikethrough", +) +from . import emphasis, strikethrough +from .autolink import autolink +from .backticks import backtick +from .balance_pairs import link_pairs +from .entity import entity +from .escape import escape +from .html_inline import html_inline +from .image import image +from .link import link +from .newline import newline +from .state_inline import StateInline +from .text import text +from .text_collapse import text_collapse diff --git a/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/__pycache__/__init__.cpython-310.pyc b/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..878dd56db6c72da85d95e7fa1257122fcbf5ebeb Binary files /dev/null and b/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/__pycache__/__init__.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/__pycache__/autolink.cpython-310.pyc b/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/__pycache__/autolink.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ac806aa6a1e44377327f495717a177827deeba3 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/__pycache__/autolink.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/__pycache__/backticks.cpython-310.pyc b/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/__pycache__/backticks.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f74bee457e15cfda1a200067c1a9569fb9708db8 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/__pycache__/backticks.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/__pycache__/balance_pairs.cpython-310.pyc b/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/__pycache__/balance_pairs.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b2effa71c8f37dd3c5823948669c9fc9308f193c Binary files /dev/null and b/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/__pycache__/balance_pairs.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/__pycache__/emphasis.cpython-310.pyc b/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/__pycache__/emphasis.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cf446df7cfe4b2b6aa50498b22e1d89004ebd5e0 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/__pycache__/emphasis.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/__pycache__/entity.cpython-310.pyc b/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/__pycache__/entity.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..724c68cef76e1987bac332df603ff2b3919a0f4d Binary files /dev/null and b/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/__pycache__/entity.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/__pycache__/escape.cpython-310.pyc b/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/__pycache__/escape.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..46407b2aa3cb784b58ec93053569c244f6b41f9e Binary files /dev/null and b/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/__pycache__/escape.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/__pycache__/image.cpython-310.pyc b/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/__pycache__/image.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..17477574edefe939956c26ad5f14d795f204f9bb Binary files /dev/null and b/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/__pycache__/image.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/__pycache__/link.cpython-310.pyc b/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/__pycache__/link.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e37142373f660e1e4fa9dc7269c83080e7c6de5 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/__pycache__/link.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/__pycache__/newline.cpython-310.pyc b/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/__pycache__/newline.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad552d92bfa456bdb63ef040ec106fb9dac57da9 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/__pycache__/newline.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/__pycache__/strikethrough.cpython-310.pyc b/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/__pycache__/strikethrough.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..606cb8f9ab3784828fa8dba97367ded2662212eb Binary files /dev/null and b/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/__pycache__/strikethrough.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/__pycache__/text.cpython-310.pyc b/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/__pycache__/text.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..96011ae7e2beebaad4d578f6d66392b4e8bbcbcb Binary files /dev/null and b/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/__pycache__/text.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/autolink.py b/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/autolink.py new file mode 100644 index 0000000000000000000000000000000000000000..11ac5905acae2a87f5ec9e890cac80096aa67d4f --- /dev/null +++ b/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/autolink.py @@ -0,0 +1,77 @@ +# Process autolinks '' +import re + +from .state_inline import StateInline + +EMAIL_RE = re.compile( + r"^([a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)$" # noqa: E501 +) +AUTOLINK_RE = re.compile(r"^([a-zA-Z][a-zA-Z0-9+.\-]{1,31}):([^<>\x00-\x20]*)$") + + +def autolink(state: StateInline, silent: bool) -> bool: + pos = state.pos + + if state.srcCharCode[pos] != 0x3C: # /* < */ + return False + + start = state.pos + maximum = state.posMax + + while True: + pos += 1 + if pos >= maximum: + return False + + ch = state.srcCharCode[pos] + + if ch == 0x3C: # /* < */ + return False + if ch == 0x3E: # /* > */ + break + + url = state.src[start + 1 : pos] + + if AUTOLINK_RE.search(url) is not None: + fullUrl = state.md.normalizeLink(url) + if not state.md.validateLink(fullUrl): + return False + + if not silent: + token = state.push("link_open", "a", 1) + token.attrs = {"href": fullUrl} + token.markup = "autolink" + token.info = "auto" + + token = state.push("text", "", 0) + token.content = state.md.normalizeLinkText(url) + + token = state.push("link_close", "a", -1) + token.markup = "autolink" + token.info = "auto" + + state.pos += len(url) + 2 + return True + + if EMAIL_RE.search(url) is not None: + fullUrl = state.md.normalizeLink("mailto:" + url) + if not state.md.validateLink(fullUrl): + return False + + if not silent: + token = state.push("link_open", "a", 1) + token.attrs = {"href": fullUrl} + token.markup = "autolink" + token.info = "auto" + + token = state.push("text", "", 0) + token.content = state.md.normalizeLinkText(url) + + token = state.push("link_close", "a", -1) + token.markup = "autolink" + token.info = "auto" + + state.pos += len(url) + 2 + return True + + return False diff --git a/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/backticks.py b/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/backticks.py new file mode 100644 index 0000000000000000000000000000000000000000..5f1e05526541f419f1f66917caf1e8a47764b825 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/backticks.py @@ -0,0 +1,74 @@ +# Parse backticks +import re + +from .state_inline import StateInline + +regex = re.compile("^ (.+) $") + + +def backtick(state: StateInline, silent: bool) -> bool: + pos = state.pos + ch = state.srcCharCode[pos] + + # /* ` */ + if ch != 0x60: + return False + + start = pos + pos += 1 + maximum = state.posMax + + # scan marker length + while pos < maximum and (state.srcCharCode[pos] == 0x60): # /* ` */ + pos += 1 + + marker = state.src[start:pos] + openerLength = len(marker) + + if state.backticksScanned and state.backticks.get(openerLength, 0) <= start: + if not silent: + state.pending += marker + state.pos += openerLength + return True + + matchStart = matchEnd = pos + + # Nothing found in the cache, scan until the end of the line (or until marker is found) + while True: + try: + matchStart = state.src.index("`", matchEnd) + except ValueError: + break + matchEnd = matchStart + 1 + + # scan marker length + while matchEnd < maximum and (state.srcCharCode[matchEnd] == 0x60): # /* ` */ + matchEnd += 1 + + closerLength = matchEnd - matchStart + + if closerLength == openerLength: + # Found matching closer length. + if not silent: + token = state.push("code_inline", "code", 0) + token.markup = marker + token.content = state.src[pos:matchStart].replace("\n", " ") + if ( + token.content.startswith(" ") + and token.content.endswith(" ") + and len(token.content.strip()) > 0 + ): + token.content = token.content[1:-1] + state.pos = matchEnd + return True + + # Some different length found, put it in cache as upper limit of where closer can be found + state.backticks[closerLength] = matchStart + + # Scanned through the end, didn't find anything + state.backticksScanned = True + + if not silent: + state.pending += marker + state.pos += openerLength + return True diff --git a/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/balance_pairs.py b/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/balance_pairs.py new file mode 100644 index 0000000000000000000000000000000000000000..5423b5d6cf1f26b17c28162083329926adeb3400 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/balance_pairs.py @@ -0,0 +1,112 @@ +# For each opening emphasis-like marker find a matching closing one +# +from .state_inline import StateInline + + +def processDelimiters(state: StateInline, delimiters, *args): + openersBottom = {} + maximum = len(delimiters) + + closerIdx = 0 + while closerIdx < maximum: + closer = delimiters[closerIdx] + + # Length is only used for emphasis-specific "rule of 3", + # if it's not defined (in strikethrough or 3rd party plugins), + # we can default it to 0 to disable those checks. + # + closer.length = closer.length or 0 + + if not closer.close: + closerIdx += 1 + continue + + # Previously calculated lower bounds (previous fails) + # for each marker, each delimiter length modulo 3, + # and for whether this closer can be an opener; + # https://github.com/commonmark/cmark/commit/34250e12ccebdc6372b8b49c44fab57c72443460 + if closer.marker not in openersBottom: + openersBottom[closer.marker] = [-1, -1, -1, -1, -1, -1] + + minOpenerIdx = openersBottom[closer.marker][ + (3 if closer.open else 0) + (closer.length % 3) + ] + + openerIdx = closerIdx - closer.jump - 1 + + # avoid crash if `closer.jump` is pointing outside of the array, + # e.g. for strikethrough + if openerIdx < -1: + openerIdx = -1 + + newMinOpenerIdx = openerIdx + + while openerIdx > minOpenerIdx: + opener = delimiters[openerIdx] + + if opener.marker != closer.marker: + openerIdx -= opener.jump + 1 + continue + + if opener.open and opener.end < 0: + isOddMatch = False + + # from spec: + # + # If one of the delimiters can both open and close emphasis, then the + # sum of the lengths of the delimiter runs containing the opening and + # closing delimiters must not be a multiple of 3 unless both lengths + # are multiples of 3. + # + if opener.close or closer.open: + if (opener.length + closer.length) % 3 == 0: + if opener.length % 3 != 0 or closer.length % 3 != 0: + isOddMatch = True + + if not isOddMatch: + # If previous delimiter cannot be an opener, we can safely skip + # the entire sequence in future checks. This is required to make + # sure algorithm has linear complexity (see *_*_*_*_*_... case). + # + if openerIdx > 0 and not delimiters[openerIdx - 1].open: + lastJump = delimiters[openerIdx - 1].jump + 1 + else: + lastJump = 0 + + closer.jump = closerIdx - openerIdx + lastJump + closer.open = False + opener.end = closerIdx + opener.jump = lastJump + opener.close = False + newMinOpenerIdx = -1 + break + + openerIdx -= opener.jump + 1 + + if newMinOpenerIdx != -1: + # If match for this delimiter run failed, we want to set lower bound for + # future lookups. This is required to make sure algorithm has linear + # complexity. + # + # See details here: + # https:#github.com/commonmark/cmark/issues/178#issuecomment-270417442 + # + openersBottom[closer.marker][ + (3 if closer.open else 0) + ((closer.length or 0) % 3) + ] = newMinOpenerIdx + + closerIdx += 1 + + +def link_pairs(state: StateInline) -> None: + tokens_meta = state.tokens_meta + maximum = len(state.tokens_meta) + + processDelimiters(state, state.delimiters) + + curr = 0 + while curr < maximum: + curr_meta = tokens_meta[curr] + if curr_meta and "delimiters" in curr_meta: + processDelimiters(state, curr_meta["delimiters"]) + curr += 1 diff --git a/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/emphasis.py b/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/emphasis.py new file mode 100644 index 0000000000000000000000000000000000000000..5262430b64bfe416a43a99670dd1595a0236f7ab --- /dev/null +++ b/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/emphasis.py @@ -0,0 +1,101 @@ +# Process *this* and _that_ +# + +from .state_inline import Delimiter, StateInline + + +def tokenize(state: StateInline, silent: bool): + """Insert each marker as a separate text token, and add it to delimiter list""" + start = state.pos + marker = state.srcCharCode[start] + + if silent: + return False + + # /* _ */ /* * */ + if marker != 0x5F and marker != 0x2A: + return False + + scanned = state.scanDelims(state.pos, marker == 0x2A) + + for i in range(scanned.length): + token = state.push("text", "", 0) + token.content = chr(marker) + state.delimiters.append( + Delimiter( + marker=marker, + length=scanned.length, + jump=i, + token=len(state.tokens) - 1, + end=-1, + open=scanned.can_open, + close=scanned.can_close, + ) + ) + + state.pos += scanned.length + + return True + + +def _postProcess(state, delimiters): + i = len(delimiters) - 1 + while i >= 0: + startDelim = delimiters[i] + + # /* _ */ /* * */ + if startDelim.marker != 0x5F and startDelim.marker != 0x2A: + i -= 1 + continue + + # Process only opening markers + if startDelim.end == -1: + i -= 1 + continue + + endDelim = delimiters[startDelim.end] + + # If the previous delimiter has the same marker and is adjacent to this one, + # merge those into one strong delimiter. + # + # `whatever` -> `whatever` + # + isStrong = ( + i > 0 + and delimiters[i - 1].end == startDelim.end + 1 + and delimiters[i - 1].token == startDelim.token - 1 + and delimiters[startDelim.end + 1].token == endDelim.token + 1 + and delimiters[i - 1].marker == startDelim.marker + ) + + ch = chr(startDelim.marker) + + token = state.tokens[startDelim.token] + token.type = "strong_open" if isStrong else "em_open" + token.tag = "strong" if isStrong else "em" + token.nesting = 1 + token.markup = ch + ch if isStrong else ch + token.content = "" + + token = state.tokens[endDelim.token] + token.type = "strong_close" if isStrong else "em_close" + token.tag = "strong" if isStrong else "em" + token.nesting = -1 + token.markup = ch + ch if isStrong else ch + token.content = "" + + if isStrong: + state.tokens[delimiters[i - 1].token].content = "" + state.tokens[delimiters[startDelim.end + 1].token].content = "" + i -= 1 + + i -= 1 + + +def postProcess(state: StateInline): + """Walk through delimiter list and replace text tokens with tags.""" + _postProcess(state, state.delimiters) + + for token in state.tokens_meta: + if token and "delimiters" in token: + _postProcess(state, token["delimiters"]) diff --git a/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/escape.py b/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/escape.py new file mode 100644 index 0000000000000000000000000000000000000000..36bd04022d41556c75ee83a3f741474a88388553 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/escape.py @@ -0,0 +1,49 @@ +""" +Process escaped chars and hardbreaks +""" +from ..common.utils import isSpace +from .state_inline import StateInline + +ESCAPED = [0 for _ in range(256)] +for ch in "\\!\"#$%&'()*+,./:;<=>?@[]^_`{|}~-": + ESCAPED[ord(ch)] = 1 + + +def escape(state: StateInline, silent: bool): + pos = state.pos + maximum = state.posMax + + # /* \ */ + if state.srcCharCode[pos] != 0x5C: + return False + + pos += 1 + + if pos < maximum: + ch = state.srcCharCode[pos] + + if ch < 256 and ESCAPED[ch] != 0: + if not silent: + state.pending += state.src[pos] + state.pos += 2 + return True + + if ch == 0x0A: + if not silent: + state.push("hardbreak", "br", 0) + + pos += 1 + # skip leading whitespaces from next line + while pos < maximum: + ch = state.srcCharCode[pos] + if not isSpace(ch): + break + pos += 1 + + state.pos = pos + return True + + if not silent: + state.pending += "\\" + state.pos += 1 + return True diff --git a/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/html_inline.py b/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/html_inline.py new file mode 100644 index 0000000000000000000000000000000000000000..b875e884846832933181fbfdc18fef6e80bb5c54 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/html_inline.py @@ -0,0 +1,42 @@ +# Process html tags +from ..common.html_re import HTML_TAG_RE +from .state_inline import StateInline + + +def isLetter(ch: int): + lc = ch | 0x20 # to lower case + # /* a */ and /* z */ + return (lc >= 0x61) and (lc <= 0x7A) + + +def html_inline(state: StateInline, silent: bool): + pos = state.pos + + if not state.md.options.get("html", None): + return False + + # Check start + maximum = state.posMax + if state.srcCharCode[pos] != 0x3C or pos + 2 >= maximum: # /* < */ + return False + + # Quick fail on second char + ch = state.srcCharCode[pos + 1] + if ( + ch != 0x21 + and ch != 0x3F # /* ! */ + and ch != 0x2F # /* ? */ + and not isLetter(ch) # /* / */ + ): + return False + + match = HTML_TAG_RE.search(state.src[pos:]) + if not match: + return False + + if not silent: + token = state.push("html_inline", "", 0) + token.content = state.src[pos : pos + len(match.group(0))] + + state.pos += len(match.group(0)) + return True diff --git a/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/image.py b/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/image.py new file mode 100644 index 0000000000000000000000000000000000000000..d7215bdfabb99a00268c6e2a838b01323a7b5ed0 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/image.py @@ -0,0 +1,150 @@ +# Process ![image]( "title") +from __future__ import annotations + +from ..common.utils import isSpace, normalizeReference +from ..token import Token +from .state_inline import StateInline + + +def image(state: StateInline, silent: bool): + label = None + href = "" + oldPos = state.pos + max = state.posMax + + # /* ! */ + if state.srcCharCode[state.pos] != 0x21: + return False + # /* [ */ + if state.pos + 1 < state.posMax and state.srcCharCode[state.pos + 1] != 0x5B: + return False + + labelStart = state.pos + 2 + labelEnd = state.md.helpers.parseLinkLabel(state, state.pos + 1, False) + + # parser failed to find ']', so it's not a valid link + if labelEnd < 0: + return False + + pos = labelEnd + 1 + # /* ( */ + if pos < max and state.srcCharCode[pos] == 0x28: + # + # Inline link + # + + # [link]( "title" ) + # ^^ skipping these spaces + pos += 1 + while pos < max: + code = state.srcCharCode[pos] + if not isSpace(code) and code != 0x0A: + break + pos += 1 + + if pos >= max: + return False + + # [link]( "title" ) + # ^^^^^^ parsing link destination + start = pos + res = state.md.helpers.parseLinkDestination(state.src, pos, state.posMax) + if res.ok: + href = state.md.normalizeLink(res.str) + if state.md.validateLink(href): + pos = res.pos + else: + href = "" + + # [link]( "title" ) + # ^^ skipping these spaces + start = pos + while pos < max: + code = state.srcCharCode[pos] + if not isSpace(code) and code != 0x0A: + break + pos += 1 + + # [link]( "title" ) + # ^^^^^^^ parsing link title + res = state.md.helpers.parseLinkTitle(state.src, pos, state.posMax) + if pos < max and start != pos and res.ok: + title = res.str + pos = res.pos + + # [link]( "title" ) + # ^^ skipping these spaces + while pos < max: + code = state.srcCharCode[pos] + if not isSpace(code) and code != 0x0A: + break + pos += 1 + else: + title = "" + + # /* ) */ + if pos >= max or state.srcCharCode[pos] != 0x29: + state.pos = oldPos + return False + + pos += 1 + + else: + # + # Link reference + # + if "references" not in state.env: + return False + + # /* [ */ + if pos < max and state.srcCharCode[pos] == 0x5B: + start = pos + 1 + pos = state.md.helpers.parseLinkLabel(state, pos) + if pos >= 0: + label = state.src[start:pos] + pos += 1 + else: + pos = labelEnd + 1 + else: + pos = labelEnd + 1 + + # covers label == '' and label == undefined + # (collapsed reference link and shortcut reference link respectively) + if not label: + label = state.src[labelStart:labelEnd] + + label = normalizeReference(label) + + ref = state.env["references"].get(label, None) + if not ref: + state.pos = oldPos + return False + + href = ref["href"] + title = ref["title"] + + # + # We found the end of the link, and know for a fact it's a valid link + # so all that's left to do is to call tokenizer. + # + if not silent: + content = state.src[labelStart:labelEnd] + + tokens: list[Token] = [] + state.md.inline.parse(content, state.md, state.env, tokens) + + token = state.push("image", "img", 0) + token.attrs = {"src": href, "alt": ""} + token.children = tokens or None + token.content = content + + if title: + token.attrSet("title", title) + + # note, this is not part of markdown-it JS, but is useful for renderers + if label and state.md.options.get("store_labels", False): + token.meta["label"] = label + + state.pos = pos + state.posMax = max + return True diff --git a/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/link.py b/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/link.py new file mode 100644 index 0000000000000000000000000000000000000000..a6345152f4c34ac16a84c901e8052cd4d23ed433 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/link.py @@ -0,0 +1,149 @@ +# Process [link]( "stuff") + +from ..common.utils import isSpace, normalizeReference +from .state_inline import StateInline + + +def link(state: StateInline, silent: bool): + href = "" + title = "" + label = None + oldPos = state.pos + maximum = state.posMax + start = state.pos + parseReference = True + + if state.srcCharCode[state.pos] != 0x5B: # /* [ */ + return False + + labelStart = state.pos + 1 + labelEnd = state.md.helpers.parseLinkLabel(state, state.pos, True) + + # parser failed to find ']', so it's not a valid link + if labelEnd < 0: + return False + + pos = labelEnd + 1 + + if pos < maximum and state.srcCharCode[pos] == 0x28: # /* ( */ + # + # Inline link + # + + # might have found a valid shortcut link, disable reference parsing + parseReference = False + + # [link]( "title" ) + # ^^ skipping these spaces + pos += 1 + while pos < maximum: + code = state.srcCharCode[pos] + if not isSpace(code) and code != 0x0A: + break + pos += 1 + + if pos >= maximum: + return False + + # [link]( "title" ) + # ^^^^^^ parsing link destination + start = pos + res = state.md.helpers.parseLinkDestination(state.src, pos, state.posMax) + if res.ok: + href = state.md.normalizeLink(res.str) + if state.md.validateLink(href): + pos = res.pos + else: + href = "" + + # [link]( "title" ) + # ^^ skipping these spaces + start = pos + while pos < maximum: + code = state.srcCharCode[pos] + if not isSpace(code) and code != 0x0A: + break + pos += 1 + + # [link]( "title" ) + # ^^^^^^^ parsing link title + res = state.md.helpers.parseLinkTitle(state.src, pos, state.posMax) + if pos < maximum and start != pos and res.ok: + title = res.str + pos = res.pos + + # [link]( "title" ) + # ^^ skipping these spaces + while pos < maximum: + code = state.srcCharCode[pos] + if not isSpace(code) and code != 0x0A: + break + pos += 1 + + if pos >= maximum or state.srcCharCode[pos] != 0x29: # /* ) */ + # parsing a valid shortcut link failed, fallback to reference + parseReference = True + + pos += 1 + + if parseReference: + # + # Link reference + # + if "references" not in state.env: + return False + + if pos < maximum and state.srcCharCode[pos] == 0x5B: # /* [ */ + start = pos + 1 + pos = state.md.helpers.parseLinkLabel(state, pos) + if pos >= 0: + label = state.src[start:pos] + pos += 1 + else: + pos = labelEnd + 1 + + else: + pos = labelEnd + 1 + + # covers label == '' and label == undefined + # (collapsed reference link and shortcut reference link respectively) + if not label: + label = state.src[labelStart:labelEnd] + + label = normalizeReference(label) + + ref = ( + state.env["references"][label] if label in state.env["references"] else None + ) + if not ref: + state.pos = oldPos + return False + + href = ref["href"] + title = ref["title"] + + # + # We found the end of the link, and know for a fact it's a valid link + # so all that's left to do is to call tokenizer. + # + if not silent: + state.pos = labelStart + state.posMax = labelEnd + + token = state.push("link_open", "a", 1) + token.attrs = {"href": href} + + if title: + token.attrSet("title", title) + + # note, this is not part of markdown-it JS, but is useful for renderers + if label and state.md.options.get("store_labels", False): + token.meta["label"] = label + + state.md.inline.tokenize(state) + + token = state.push("link_close", "a", -1) + + state.pos = pos + state.posMax = maximum + return True diff --git a/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/newline.py b/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/newline.py new file mode 100644 index 0000000000000000000000000000000000000000..3034e408ef9622053f698aaef506f3897d6b6466 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/newline.py @@ -0,0 +1,43 @@ +# Proceess '\n' +import re + +from ..common.utils import charCodeAt, isSpace +from .state_inline import StateInline + +endSpace = re.compile(r" +$") + + +def newline(state: StateInline, silent: bool): + pos = state.pos + + # /* \n */ + if state.srcCharCode[pos] != 0x0A: + return False + + pmax = len(state.pending) - 1 + maximum = state.posMax + + # ' \n' -> hardbreak + # Lookup in pending chars is bad practice! Don't copy to other rules! + # Pending string is stored in concat mode, indexed lookups will cause + # conversion to flat mode. + if not silent: + if pmax >= 0 and charCodeAt(state.pending, pmax) == 0x20: + if pmax >= 1 and charCodeAt(state.pending, pmax - 1) == 0x20: + state.pending = endSpace.sub("", state.pending) + state.push("hardbreak", "br", 0) + else: + state.pending = state.pending[:-1] + state.push("softbreak", "br", 0) + + else: + state.push("softbreak", "br", 0) + + pos += 1 + + # skip heading spaces for next line + while pos < maximum and isSpace(state.srcCharCode[pos]): + pos += 1 + + state.pos = pos + return True diff --git a/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/state_inline.py b/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/state_inline.py new file mode 100644 index 0000000000000000000000000000000000000000..283532ccf3bd1ada585b8677130bc7297e795186 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/state_inline.py @@ -0,0 +1,175 @@ +from __future__ import annotations + +from collections import namedtuple +from collections.abc import MutableMapping +from dataclasses import dataclass +from typing import TYPE_CHECKING + +from .._compat import DATACLASS_KWARGS +from ..common.utils import isMdAsciiPunct, isPunctChar, isWhiteSpace +from ..ruler import StateBase +from ..token import Token + +if TYPE_CHECKING: + from markdown_it import MarkdownIt + + +@dataclass(**DATACLASS_KWARGS) +class Delimiter: + # Char code of the starting marker (number). + marker: int + + # Total length of these series of delimiters. + length: int + + # An amount of characters before this one that's equivalent to + # current one. In plain English: if this delimiter does not open + # an emphasis, neither do previous `jump` characters. + # + # Used to skip sequences like "*****" in one step, for 1st asterisk + # value will be 0, for 2nd it's 1 and so on. + jump: int + + # A position of the token this delimiter corresponds to. + token: int + + # If this delimiter is matched as a valid opener, `end` will be + # equal to its position, otherwise it's `-1`. + end: int + + # Boolean flags that determine if this delimiter could open or close + # an emphasis. + open: bool + close: bool + + level: bool | None = None + + +Scanned = namedtuple("Scanned", ["can_open", "can_close", "length"]) + + +class StateInline(StateBase): + def __init__( + self, src: str, md: MarkdownIt, env: MutableMapping, outTokens: list[Token] + ): + self.src = src + self.env = env + self.md = md + self.tokens = outTokens + self.tokens_meta: list[dict | None] = [None] * len(outTokens) + + self.pos = 0 + self.posMax = len(self.src) + self.level = 0 + self.pending = "" + self.pendingLevel = 0 + + # Stores { start: end } pairs. Useful for backtrack + # optimization of pairs parse (emphasis, strikes). + self.cache: dict[int, int] = {} + + # List of emphasis-like delimiters for current tag + self.delimiters: list[Delimiter] = [] + + # Stack of delimiter lists for upper level tags + self._prev_delimiters: list[list[Delimiter]] = [] + + # backticklength => last seen position + self.backticks: dict[int, int] = {} + self.backticksScanned = False + + def __repr__(self): + return ( + f"{self.__class__.__name__}" + f"(pos=[{self.pos} of {self.posMax}], token={len(self.tokens)})" + ) + + def pushPending(self): + token = Token("text", "", 0) + token.content = self.pending + token.level = self.pendingLevel + self.tokens.append(token) + self.pending = "" + return token + + def push(self, ttype, tag, nesting): + """Push new token to "stream". + If pending text exists - flush it as text token + """ + if self.pending: + self.pushPending() + + token = Token(ttype, tag, nesting) + token_meta = None + + if nesting < 0: + # closing tag + self.level -= 1 + self.delimiters = self._prev_delimiters.pop() + + token.level = self.level + + if nesting > 0: + # opening tag + self.level += 1 + self._prev_delimiters.append(self.delimiters) + self.delimiters = [] + token_meta = {"delimiters": self.delimiters} + + self.pendingLevel = self.level + self.tokens.append(token) + self.tokens_meta.append(token_meta) + return token + + def scanDelims(self, start, canSplitWord): + """ + Scan a sequence of emphasis-like markers, and determine whether + it can start an emphasis sequence or end an emphasis sequence. + + - start - position to scan from (it should point at a valid marker); + - canSplitWord - determine if these markers can be found inside a word + + """ + pos = start + left_flanking = True + right_flanking = True + maximum = self.posMax + marker = self.srcCharCode[start] + + # treat beginning of the line as a whitespace + lastChar = self.srcCharCode[start - 1] if start > 0 else 0x20 + + while pos < maximum and self.srcCharCode[pos] == marker: + pos += 1 + + count = pos - start + + # treat end of the line as a whitespace + nextChar = self.srcCharCode[pos] if pos < maximum else 0x20 + + isLastPunctChar = isMdAsciiPunct(lastChar) or isPunctChar(chr(lastChar)) + isNextPunctChar = isMdAsciiPunct(nextChar) or isPunctChar(chr(nextChar)) + + isLastWhiteSpace = isWhiteSpace(lastChar) + isNextWhiteSpace = isWhiteSpace(nextChar) + + if isNextWhiteSpace: + left_flanking = False + elif isNextPunctChar: + if not (isLastWhiteSpace or isLastPunctChar): + left_flanking = False + + if isLastWhiteSpace: + right_flanking = False + elif isLastPunctChar: + if not (isNextWhiteSpace or isNextPunctChar): + right_flanking = False + + if not canSplitWord: + can_open = left_flanking and ((not right_flanking) or isLastPunctChar) + can_close = right_flanking and ((not left_flanking) or isNextPunctChar) + else: + can_open = left_flanking + can_close = right_flanking + + return Scanned(can_open, can_close, count) diff --git a/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/strikethrough.py b/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/strikethrough.py new file mode 100644 index 0000000000000000000000000000000000000000..9b062a661102ec221062af4d32b447d733deea22 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/strikethrough.py @@ -0,0 +1,131 @@ +# ~~strike through~~ +from __future__ import annotations + +from .state_inline import Delimiter, StateInline + + +def tokenize(state: StateInline, silent: bool): + """Insert each marker as a separate text token, and add it to delimiter list""" + start = state.pos + marker = state.srcCharCode[start] + + if silent: + return False + + if marker != 0x7E: # /* ~ */ + return False + + scanned = state.scanDelims(state.pos, True) + length = scanned.length + ch = chr(marker) + + if length < 2: + return False + + if length % 2: + token = state.push("text", "", 0) + token.content = ch + length -= 1 + + i = 0 + while i < length: + token = state.push("text", "", 0) + token.content = ch + ch + state.delimiters.append( + Delimiter( + **{ + "marker": marker, + "length": 0, # disable "rule of 3" length checks meant for emphasis + "jump": i // 2, # for `~~` 1 marker = 2 characters + "token": len(state.tokens) - 1, + "end": -1, + "open": scanned.can_open, + "close": scanned.can_close, + } + ) + ) + + i += 2 + + state.pos += scanned.length + + return True + + +def _postProcess(state: StateInline, delimiters: list[Delimiter]): + loneMarkers = [] + maximum = len(delimiters) + + i = 0 + while i < maximum: + startDelim = delimiters[i] + + if startDelim.marker != 0x7E: # /* ~ */ + i += 1 + continue + + if startDelim.end == -1: + i += 1 + continue + + endDelim = delimiters[startDelim.end] + + token = state.tokens[startDelim.token] + token.type = "s_open" + token.tag = "s" + token.nesting = 1 + token.markup = "~~" + token.content = "" + + token = state.tokens[endDelim.token] + token.type = "s_close" + token.tag = "s" + token.nesting = -1 + token.markup = "~~" + token.content = "" + + if ( + state.tokens[endDelim.token - 1].type == "text" + and state.tokens[endDelim.token - 1].content == "~" + ): + loneMarkers.append(endDelim.token - 1) + + i += 1 + + # If a marker sequence has an odd number of characters, it's split + # like this: `~~~~~` -> `~` + `~~` + `~~`, leaving one marker at the + # start of the sequence. + # + # So, we have to move all those markers after subsequent s_close tags. + # + while loneMarkers: + i = loneMarkers.pop() + j = i + 1 + + while (j < len(state.tokens)) and (state.tokens[j].type == "s_close"): + j += 1 + + j -= 1 + + if i != j: + token = state.tokens[j] + state.tokens[j] = state.tokens[i] + state.tokens[i] = token + + +def postProcess(state: StateInline): + """Walk through delimiter list and replace text tokens with tags.""" + tokens_meta = state.tokens_meta + maximum = len(state.tokens_meta) + _postProcess(state, state.delimiters) + + curr = 0 + while curr < maximum: + try: + curr_meta = tokens_meta[curr] + except IndexError: + pass + else: + if curr_meta and "delimiters" in curr_meta: + _postProcess(state, curr_meta["delimiters"]) + curr += 1 diff --git a/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/text.py b/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/text.py new file mode 100644 index 0000000000000000000000000000000000000000..ec6ee0faa0cb23133841548048cca9c60210bb7b --- /dev/null +++ b/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/text.py @@ -0,0 +1,57 @@ +# Skip text characters for text token, place those to pending buffer +# and increment current pos + +from .state_inline import StateInline + +# Rule to skip pure text +# '{}$%@~+=:' reserved for extensions + +# !, ", #, $, %, &, ', (, ), *, +, ,, -, ., /, :, ;, <, =, >, ?, @, [, \, ], ^, _, `, {, |, }, or ~ + +# !!!! Don't confuse with "Markdown ASCII Punctuation" chars +# http://spec.commonmark.org/0.15/#ascii-punctuation-character + + +def isTerminatorChar(ch): + return ch in { + 0x0A, # /* \n */: + 0x21, # /* ! */: + 0x23, # /* # */: + 0x24, # /* $ */: + 0x25, # /* % */: + 0x26, # /* & */: + 0x2A, # /* * */: + 0x2B, # /* + */: + 0x2D, # /* - */: + 0x3A, # /* : */: + 0x3C, # /* < */: + 0x3D, # /* = */: + 0x3E, # /* > */: + 0x40, # /* @ */: + 0x5B, # /* [ */: + 0x5C, # /* \ */: + 0x5D, # /* ] */: + 0x5E, # /* ^ */: + 0x5F, # /* _ */: + 0x60, # /* ` */: + 0x7B, # /* { */: + 0x7D, # /* } */: + 0x7E, # /* ~ */: + } + + +def text(state: StateInline, silent: bool, **args): + pos = state.pos + posMax = state.posMax + while (pos < posMax) and not isTerminatorChar(state.srcCharCode[pos]): + pos += 1 + + if pos == state.pos: + return False + + if not silent: + state.pending += state.src[state.pos : pos] + + state.pos = pos + + return True diff --git a/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/text_collapse.py b/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/text_collapse.py new file mode 100644 index 0000000000000000000000000000000000000000..6d0c0ab603e98fa0acf844f66d6fc50541856f3d --- /dev/null +++ b/parrot/lib/python3.10/site-packages/markdown_it/rules_inline/text_collapse.py @@ -0,0 +1,43 @@ +from .state_inline import StateInline + + +def text_collapse(state: StateInline, *args): + """ + Clean up tokens after emphasis and strikethrough postprocessing: + merge adjacent text nodes into one and re-calculate all token levels + + This is necessary because initially emphasis delimiter markers (``*, _, ~``) + are treated as their own separate text tokens. Then emphasis rule either + leaves them as text (needed to merge with adjacent text) or turns them + into opening/closing tags (which messes up levels inside). + """ + level = 0 + maximum = len(state.tokens) + + curr = last = 0 + while curr < maximum: + # re-calculate levels after emphasis/strikethrough turns some text nodes + # into opening/closing tags + if state.tokens[curr].nesting < 0: + level -= 1 # closing tag + state.tokens[curr].level = level + if state.tokens[curr].nesting > 0: + level += 1 # opening tag + + if ( + state.tokens[curr].type == "text" + and curr + 1 < maximum + and state.tokens[curr + 1].type == "text" + ): + # collapse two adjacent text nodes + state.tokens[curr + 1].content = ( + state.tokens[curr].content + state.tokens[curr + 1].content + ) + else: + if curr != last: + state.tokens[last] = state.tokens[curr] + last += 1 + curr += 1 + + if curr != last: + del state.tokens[last:] diff --git a/parrot/lib/python3.10/site-packages/markdown_it/token.py b/parrot/lib/python3.10/site-packages/markdown_it/token.py new file mode 100644 index 0000000000000000000000000000000000000000..7a41a7843ab6c3019d1385bdc245064d202a70e5 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/markdown_it/token.py @@ -0,0 +1,180 @@ +from __future__ import annotations + +from collections.abc import Callable, MutableMapping +import dataclasses as dc +from typing import Any +import warnings + +from markdown_it._compat import DATACLASS_KWARGS + + +def convert_attrs(value: Any) -> Any: + """Convert Token.attrs set as ``None`` or ``[[key, value], ...]`` to a dict. + + This improves compatibility with upstream markdown-it. + """ + if not value: + return {} + if isinstance(value, list): + return dict(value) + return value + + +@dc.dataclass(**DATACLASS_KWARGS) +class Token: + type: str + """Type of the token (string, e.g. "paragraph_open")""" + + tag: str + """HTML tag name, e.g. 'p'""" + + nesting: int + """Level change (number in {-1, 0, 1} set), where: + - `1` means the tag is opening + - `0` means the tag is self-closing + - `-1` means the tag is closing + """ + + attrs: dict[str, str | int | float] = dc.field(default_factory=dict) + """HTML attributes. + Note this differs from the upstream "list of lists" format, + although than an instance can still be initialised with this format. + """ + + map: list[int] | None = None + """Source map info. Format: `[ line_begin, line_end ]`""" + + level: int = 0 + """Nesting level, the same as `state.level`""" + + children: list[Token] | None = None + """Array of child nodes (inline and img tokens).""" + + content: str = "" + """Inner content, in the case of a self-closing tag (code, html, fence, etc.),""" + + markup: str = "" + """'*' or '_' for emphasis, fence string for fence, etc.""" + + info: str = "" + """Additional information: + - Info string for "fence" tokens + - The value "auto" for autolink "link_open" and "link_close" tokens + - The string value of the item marker for ordered-list "list_item_open" tokens + """ + + meta: dict = dc.field(default_factory=dict) + """A place for plugins to store any arbitrary data""" + + block: bool = False + """True for block-level tokens, false for inline tokens. + Used in renderer to calculate line breaks + """ + + hidden: bool = False + """If true, ignore this element when rendering. + Used for tight lists to hide paragraphs. + """ + + def __post_init__(self): + self.attrs = convert_attrs(self.attrs) + + def attrIndex(self, name: str) -> int: + warnings.warn( + "Token.attrIndex should not be used, since Token.attrs is a dictionary", + UserWarning, + ) + if name not in self.attrs: + return -1 + return list(self.attrs.keys()).index(name) + + def attrItems(self) -> list[tuple[str, str | int | float]]: + """Get (key, value) list of attrs.""" + return list(self.attrs.items()) + + def attrPush(self, attrData: tuple[str, str | int | float]) -> None: + """Add `[ name, value ]` attribute to list. Init attrs if necessary.""" + name, value = attrData + self.attrSet(name, value) + + def attrSet(self, name: str, value: str | int | float) -> None: + """Set `name` attribute to `value`. Override old value if exists.""" + self.attrs[name] = value + + def attrGet(self, name: str) -> None | str | int | float: + """Get the value of attribute `name`, or null if it does not exist.""" + return self.attrs.get(name, None) + + def attrJoin(self, name: str, value: str) -> None: + """Join value to existing attribute via space. + Or create new attribute if not exists. + Useful to operate with token classes. + """ + if name in self.attrs: + current = self.attrs[name] + if not isinstance(current, str): + raise TypeError( + f"existing attr 'name' is not a str: {self.attrs[name]}" + ) + self.attrs[name] = f"{current} {value}" + else: + self.attrs[name] = value + + def copy(self, **changes: Any) -> Token: + """Return a shallow copy of the instance.""" + return dc.replace(self, **changes) + + def as_dict( + self, + *, + children: bool = True, + as_upstream: bool = True, + meta_serializer: Callable[[dict], Any] | None = None, + filter: Callable[[str, Any], bool] | None = None, + dict_factory: Callable[..., MutableMapping[str, Any]] = dict, + ) -> MutableMapping[str, Any]: + """Return the token as a dictionary. + + :param children: Also convert children to dicts + :param as_upstream: Ensure the output dictionary is equal to that created by markdown-it + For example, attrs are converted to null or lists + :param meta_serializer: hook for serializing ``Token.meta`` + :param filter: A callable whose return code determines whether an + attribute or element is included (``True``) or dropped (``False``). + Is called with the (key, value) pair. + :param dict_factory: A callable to produce dictionaries from. + For example, to produce ordered dictionaries instead of normal Python + dictionaries, pass in ``collections.OrderedDict``. + + """ + mapping = dict_factory((f.name, getattr(self, f.name)) for f in dc.fields(self)) + if filter: + mapping = dict_factory((k, v) for k, v in mapping.items() if filter(k, v)) + if as_upstream and "attrs" in mapping: + mapping["attrs"] = ( + None + if not mapping["attrs"] + else [[k, v] for k, v in mapping["attrs"].items()] + ) + if meta_serializer and "meta" in mapping: + mapping["meta"] = meta_serializer(mapping["meta"]) + if children and mapping.get("children", None): + mapping["children"] = [ + child.as_dict( + children=children, + filter=filter, + dict_factory=dict_factory, + as_upstream=as_upstream, + meta_serializer=meta_serializer, + ) + for child in mapping["children"] + ] + return mapping + + @classmethod + def from_dict(cls, dct: MutableMapping[str, Any]) -> Token: + """Convert a dict to a Token.""" + token = cls(**dct) + if token.children: + token.children = [cls.from_dict(c) for c in token.children] # type: ignore[arg-type] + return token diff --git a/parrot/lib/python3.10/site-packages/markdown_it/tree.py b/parrot/lib/python3.10/site-packages/markdown_it/tree.py new file mode 100644 index 0000000000000000000000000000000000000000..09476b226c671e8644fb40923a2c6f40a1009124 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/markdown_it/tree.py @@ -0,0 +1,330 @@ +"""A tree representation of a linear markdown-it token stream. + +This module is not part of upstream JavaScript markdown-it. +""" +from __future__ import annotations + +from collections.abc import Generator, Sequence +import textwrap +from typing import Any, NamedTuple, TypeVar, overload + +from .token import Token +from .utils import _removesuffix + + +class _NesterTokens(NamedTuple): + opening: Token + closing: Token + + +_NodeType = TypeVar("_NodeType", bound="SyntaxTreeNode") + + +class SyntaxTreeNode: + """A Markdown syntax tree node. + + A class that can be used to construct a tree representation of a linear + `markdown-it-py` token stream. + + Each node in the tree represents either: + - root of the Markdown document + - a single unnested `Token` + - a `Token` "_open" and "_close" token pair, and the tokens nested in + between + """ + + def __init__( + self, tokens: Sequence[Token] = (), *, create_root: bool = True + ) -> None: + """Initialize a `SyntaxTreeNode` from a token stream. + + If `create_root` is True, create a root node for the document. + """ + # Only nodes representing an unnested token have self.token + self.token: Token | None = None + + # Only containers have nester tokens + self.nester_tokens: _NesterTokens | None = None + + # Root node does not have self.parent + self._parent: Any = None + + # Empty list unless a non-empty container, or unnested token that has + # children (i.e. inline or img) + self._children: list = [] + + if create_root: + self._set_children_from_tokens(tokens) + return + + if not tokens: + raise ValueError( + "Can only create root from empty token sequence." + " Set `create_root=True`." + ) + elif len(tokens) == 1: + inline_token = tokens[0] + if inline_token.nesting: + raise ValueError( + "Unequal nesting level at the start and end of token stream." + ) + self.token = inline_token + if inline_token.children: + self._set_children_from_tokens(inline_token.children) + else: + self.nester_tokens = _NesterTokens(tokens[0], tokens[-1]) + self._set_children_from_tokens(tokens[1:-1]) + + def __repr__(self) -> str: + return f"{type(self).__name__}({self.type})" + + @overload + def __getitem__(self: _NodeType, item: int) -> _NodeType: + ... + + @overload + def __getitem__(self: _NodeType, item: slice) -> list[_NodeType]: + ... + + def __getitem__(self: _NodeType, item: int | slice) -> _NodeType | list[_NodeType]: + return self.children[item] + + def to_tokens(self: _NodeType) -> list[Token]: + """Recover the linear token stream.""" + + def recursive_collect_tokens(node: _NodeType, token_list: list[Token]) -> None: + if node.type == "root": + for child in node.children: + recursive_collect_tokens(child, token_list) + elif node.token: + token_list.append(node.token) + else: + assert node.nester_tokens + token_list.append(node.nester_tokens.opening) + for child in node.children: + recursive_collect_tokens(child, token_list) + token_list.append(node.nester_tokens.closing) + + tokens: list[Token] = [] + recursive_collect_tokens(self, tokens) + return tokens + + @property + def children(self: _NodeType) -> list[_NodeType]: + return self._children + + @children.setter + def children(self: _NodeType, value: list[_NodeType]) -> None: + self._children = value + + @property + def parent(self: _NodeType) -> _NodeType | None: + return self._parent + + @parent.setter + def parent(self: _NodeType, value: _NodeType | None) -> None: + self._parent = value + + @property + def is_root(self) -> bool: + """Is the node a special root node?""" + return not (self.token or self.nester_tokens) + + @property + def is_nested(self) -> bool: + """Is this node nested?. + + Returns `True` if the node represents a `Token` pair and tokens in the + sequence between them, where `Token.nesting` of the first `Token` in + the pair is 1 and nesting of the other `Token` is -1. + """ + return bool(self.nester_tokens) + + @property + def siblings(self: _NodeType) -> Sequence[_NodeType]: + """Get siblings of the node. + + Gets the whole group of siblings, including self. + """ + if not self.parent: + return [self] + return self.parent.children + + @property + def type(self) -> str: + """Get a string type of the represented syntax. + + - "root" for root nodes + - `Token.type` if the node represents an unnested token + - `Token.type` of the opening token, with "_open" suffix stripped, if + the node represents a nester token pair + """ + if self.is_root: + return "root" + if self.token: + return self.token.type + assert self.nester_tokens + return _removesuffix(self.nester_tokens.opening.type, "_open") + + @property + def next_sibling(self: _NodeType) -> _NodeType | None: + """Get the next node in the sequence of siblings. + + Returns `None` if this is the last sibling. + """ + self_index = self.siblings.index(self) + if self_index + 1 < len(self.siblings): + return self.siblings[self_index + 1] + return None + + @property + def previous_sibling(self: _NodeType) -> _NodeType | None: + """Get the previous node in the sequence of siblings. + + Returns `None` if this is the first sibling. + """ + self_index = self.siblings.index(self) + if self_index - 1 >= 0: + return self.siblings[self_index - 1] + return None + + def _add_child( + self, + tokens: Sequence[Token], + ) -> None: + """Make a child node for `self`.""" + child = type(self)(tokens, create_root=False) + child.parent = self + self.children.append(child) + + def _set_children_from_tokens(self, tokens: Sequence[Token]) -> None: + """Convert the token stream to a tree structure and set the resulting + nodes as children of `self`.""" + reversed_tokens = list(reversed(tokens)) + while reversed_tokens: + token = reversed_tokens.pop() + + if not token.nesting: + self._add_child([token]) + continue + if token.nesting != 1: + raise ValueError("Invalid token nesting") + + nested_tokens = [token] + nesting = 1 + while reversed_tokens and nesting: + token = reversed_tokens.pop() + nested_tokens.append(token) + nesting += token.nesting + if nesting: + raise ValueError(f"unclosed tokens starting {nested_tokens[0]}") + + self._add_child(nested_tokens) + + def pretty( + self, *, indent: int = 2, show_text: bool = False, _current: int = 0 + ) -> str: + """Create an XML style string of the tree.""" + prefix = " " * _current + text = prefix + f"<{self.type}" + if not self.is_root and self.attrs: + text += " " + " ".join(f"{k}={v!r}" for k, v in self.attrs.items()) + text += ">" + if show_text and not self.is_root and self.type == "text" and self.content: + text += "\n" + textwrap.indent(self.content, prefix + " " * indent) + for child in self.children: + text += "\n" + child.pretty( + indent=indent, show_text=show_text, _current=_current + indent + ) + return text + + def walk( + self: _NodeType, *, include_self: bool = True + ) -> Generator[_NodeType, None, None]: + """Recursively yield all descendant nodes in the tree starting at self. + + The order mimics the order of the underlying linear token + stream (i.e. depth first). + """ + if include_self: + yield self + for child in self.children: + yield from child.walk(include_self=True) + + # NOTE: + # The values of the properties defined below directly map to properties + # of the underlying `Token`s. A root node does not translate to a `Token` + # object, so calling these property getters on a root node will raise an + # `AttributeError`. + # + # There is no mapping for `Token.nesting` because the `is_nested` property + # provides that data, and can be called on any node type, including root. + + def _attribute_token(self) -> Token: + """Return the `Token` that is used as the data source for the + properties defined below.""" + if self.token: + return self.token + if self.nester_tokens: + return self.nester_tokens.opening + raise AttributeError("Root node does not have the accessed attribute") + + @property + def tag(self) -> str: + """html tag name, e.g. \"p\" """ + return self._attribute_token().tag + + @property + def attrs(self) -> dict[str, str | int | float]: + """Html attributes.""" + return self._attribute_token().attrs + + def attrGet(self, name: str) -> None | str | int | float: + """Get the value of attribute `name`, or null if it does not exist.""" + return self._attribute_token().attrGet(name) + + @property + def map(self) -> tuple[int, int] | None: + """Source map info. Format: `tuple[ line_begin, line_end ]`""" + map_ = self._attribute_token().map + if map_: + # Type ignore because `Token`s attribute types are not perfect + return tuple(map_) # type: ignore + return None + + @property + def level(self) -> int: + """nesting level, the same as `state.level`""" + return self._attribute_token().level + + @property + def content(self) -> str: + """In a case of self-closing tag (code, html, fence, etc.), it + has contents of this tag.""" + return self._attribute_token().content + + @property + def markup(self) -> str: + """'*' or '_' for emphasis, fence string for fence, etc.""" + return self._attribute_token().markup + + @property + def info(self) -> str: + """fence infostring""" + return self._attribute_token().info + + @property + def meta(self) -> dict: + """A place for plugins to store an arbitrary data.""" + return self._attribute_token().meta + + @property + def block(self) -> bool: + """True for block-level tokens, false for inline tokens.""" + return self._attribute_token().block + + @property + def hidden(self) -> bool: + """If it's true, ignore this element when rendering. + Used for tight lists to hide paragraphs.""" + return self._attribute_token().hidden diff --git a/parrot/lib/python3.10/site-packages/markdown_it/utils.py b/parrot/lib/python3.10/site-packages/markdown_it/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..2ba2995a4b882e9df38616b26718fafcedc8d1f5 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/markdown_it/utils.py @@ -0,0 +1,122 @@ +from __future__ import annotations + +from collections.abc import Callable +from pathlib import Path + + +class OptionsDict(dict): + """A dictionary, with attribute access to core markdownit configuration options.""" + + @property + def maxNesting(self) -> int: + """Internal protection, recursion limit.""" + return self["maxNesting"] + + @maxNesting.setter + def maxNesting(self, value: int): + self["maxNesting"] = value + + @property + def html(self) -> bool: + """Enable HTML tags in source.""" + return self["html"] + + @html.setter + def html(self, value: bool): + self["html"] = value + + @property + def linkify(self) -> bool: + """Enable autoconversion of URL-like texts to links.""" + return self["linkify"] + + @linkify.setter + def linkify(self, value: bool): + self["linkify"] = value + + @property + def typographer(self) -> bool: + """Enable smartquotes and replacements.""" + return self["typographer"] + + @typographer.setter + def typographer(self, value: bool): + self["typographer"] = value + + @property + def quotes(self) -> str: + """Quote characters.""" + return self["quotes"] + + @quotes.setter + def quotes(self, value: str): + self["quotes"] = value + + @property + def xhtmlOut(self) -> bool: + """Use '/' to close single tags (
).""" + return self["xhtmlOut"] + + @xhtmlOut.setter + def xhtmlOut(self, value: bool): + self["xhtmlOut"] = value + + @property + def breaks(self) -> bool: + """Convert newlines in paragraphs into
.""" + return self["breaks"] + + @breaks.setter + def breaks(self, value: bool): + self["breaks"] = value + + @property + def langPrefix(self) -> str: + """CSS language prefix for fenced blocks.""" + return self["langPrefix"] + + @langPrefix.setter + def langPrefix(self, value: str): + self["langPrefix"] = value + + @property + def highlight(self) -> Callable[[str, str, str], str] | None: + """Highlighter function: (content, langName, langAttrs) -> escaped HTML.""" + return self["highlight"] + + @highlight.setter + def highlight(self, value: Callable[[str, str, str], str] | None): + self["highlight"] = value + + +def read_fixture_file(path: str | Path) -> list[list]: + text = Path(path).read_text(encoding="utf-8") + tests = [] + section = 0 + last_pos = 0 + lines = text.splitlines(keepends=True) + for i in range(len(lines)): + if lines[i].rstrip() == ".": + if section == 0: + tests.append([i, lines[i - 1].strip()]) + section = 1 + elif section == 1: + tests[-1].append("".join(lines[last_pos + 1 : i])) + section = 2 + elif section == 2: + tests[-1].append("".join(lines[last_pos + 1 : i])) + section = 0 + + last_pos = i + return tests + + +def _removesuffix(string: str, suffix: str) -> str: + """Remove a suffix from a string. + + Replace this with str.removesuffix() from stdlib when minimum Python + version is 3.9. + """ + if suffix and string.endswith(suffix): + return string[: -len(suffix)] + return string