diff --git a/evalkit_tf446/lib/python3.10/site-packages/google_resumable_media-2.7.2.dist-info/INSTALLER b/evalkit_tf446/lib/python3.10/site-packages/google_resumable_media-2.7.2.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/evalkit_tf446/lib/python3.10/site-packages/google_resumable_media-2.7.2.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/evalkit_tf446/lib/python3.10/site-packages/google_resumable_media-2.7.2.dist-info/METADATA b/evalkit_tf446/lib/python3.10/site-packages/google_resumable_media-2.7.2.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..93ca79e6c423cbc115fc594cc896ac9e4cae46f4 --- /dev/null +++ b/evalkit_tf446/lib/python3.10/site-packages/google_resumable_media-2.7.2.dist-info/METADATA @@ -0,0 +1,67 @@ +Metadata-Version: 2.1 +Name: google-resumable-media +Version: 2.7.2 +Summary: Utilities for Google Media Downloads and Resumable Uploads +Home-page: https://github.com/googleapis/google-resumable-media-python +Author: Google Cloud Platform +Author-email: googleapis-publisher@google.com +License: Apache 2.0 +Platform: Posix; MacOS X; Windows +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Topic :: Internet +Requires-Python: >= 3.7 +License-File: LICENSE +Requires-Dist: google-crc32c <2.0dev,>=1.0 +Provides-Extra: aiohttp +Requires-Dist: aiohttp <4.0.0dev,>=3.6.2 ; extra == 'aiohttp' +Requires-Dist: google-auth <2.0dev,>=1.22.0 ; extra == 'aiohttp' +Provides-Extra: requests +Requires-Dist: requests <3.0.0dev,>=2.18.0 ; extra == 'requests' + +``google-resumable-media`` +========================== + + +Utilities for Google Media Downloads and Resumable Uploads + + +See the `docs`_ for examples and usage. + +.. _docs: https://googleapis.dev/python/google-resumable-media/latest/index.html + +Experimental `asyncio` Support +------------------------------ +While still in development and subject to change, this library has `asyncio` +support at `google._async_resumable_media`. + +Supported Python Versions +------------------------- +Python >= 3.7 + +Unsupported Python Versions +--------------------------- + +Python == 2.7, Python == 3.5, Python == 3.6. + +The last version of this library compatible with Python 2.7 and 3.5 is +`google-resumable-media==1.3.3`. + +The last version of this library compatible with Python 3.6 is +`google-resumable-media==2.3.3`. + +License +------- + +Apache 2.0 - See `the LICENSE`_ for more information. + +.. _the LICENSE: https://github.com/googleapis/google-resumable-media-python/blob/main/LICENSE diff --git a/evalkit_tf446/lib/python3.10/site-packages/google_resumable_media-2.7.2.dist-info/WHEEL b/evalkit_tf446/lib/python3.10/site-packages/google_resumable_media-2.7.2.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..7601b88b4a3b444bfddeee3ddf1172c2629f4991 --- /dev/null +++ b/evalkit_tf446/lib/python3.10/site-packages/google_resumable_media-2.7.2.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: setuptools (70.2.0) +Root-Is-Purelib: true +Tag: py2-none-any +Tag: py3-none-any + diff --git a/evalkit_tf446/lib/python3.10/site-packages/google_resumable_media-2.7.2.dist-info/top_level.txt b/evalkit_tf446/lib/python3.10/site-packages/google_resumable_media-2.7.2.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..22d04af7e76cc49b351ca4c9335972850f7a8d7d --- /dev/null +++ b/evalkit_tf446/lib/python3.10/site-packages/google_resumable_media-2.7.2.dist-info/top_level.txt @@ -0,0 +1,2 @@ +google +testing diff --git a/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/__pycache__/__init__.cpython-310.pyc b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fbdfb661f3652c36eb10e009fb82bfd438330010 Binary files /dev/null and b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/__pycache__/__init__.cpython-310.pyc differ diff --git a/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/__pycache__/case.cpython-310.pyc b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/__pycache__/case.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0c59c071a8090b7c3553c472edc23ff84f08d604 Binary files /dev/null and b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/__pycache__/case.cpython-310.pyc differ diff --git a/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/__pycache__/cli.cpython-310.pyc b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/__pycache__/cli.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..af1e78b3d5f7446b34a00540458fab810b24ca7d Binary files /dev/null and b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/__pycache__/cli.cpython-310.pyc differ diff --git a/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/__pycache__/compat.cpython-310.pyc b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/__pycache__/compat.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9f849ec449fc5a556bfbe2dbe870ea2fddbea089 Binary files /dev/null and b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/__pycache__/compat.cpython-310.pyc differ diff --git a/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/__pycache__/decorators.cpython-310.pyc b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/__pycache__/decorators.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e115684f6b3d7aa94dc52d4160d8a6df4dd8c3b Binary files /dev/null and b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/__pycache__/decorators.cpython-310.pyc differ diff --git a/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/__pycache__/deprecation.cpython-310.pyc b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/__pycache__/deprecation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9aa87bab19cff97eb5f519cb987019f5f5462f6e Binary files /dev/null and b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/__pycache__/deprecation.cpython-310.pyc differ diff --git a/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/__pycache__/prompts.cpython-310.pyc b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/__pycache__/prompts.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..32f87eb2141016b50564bd9174c7ca5a0f4bcece Binary files /dev/null and b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/__pycache__/prompts.cpython-310.pyc differ diff --git a/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/__pycache__/sphinx.cpython-310.pyc b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/__pycache__/sphinx.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a89270e18b604547390fadbe45d0e6222da207cd Binary files /dev/null and b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/__pycache__/sphinx.cpython-310.pyc differ diff --git a/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/__pycache__/tables.cpython-310.pyc b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/__pycache__/tables.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fa57032ad537f31a0f1d6e73f1dab31a16aae667 Binary files /dev/null and b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/__pycache__/tables.cpython-310.pyc differ diff --git a/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/__pycache__/testing.cpython-310.pyc b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/__pycache__/testing.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..30c84d7a97d1605e396100467212b5ce85be4180 Binary files /dev/null and b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/__pycache__/testing.cpython-310.pyc differ diff --git a/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/__pycache__/tests.cpython-310.pyc b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/__pycache__/tests.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..391b55966a4cabe16cb9190ba089611f79dd7abe Binary files /dev/null and b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/__pycache__/tests.cpython-310.pyc differ diff --git a/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/__pycache__/text.cpython-310.pyc b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/__pycache__/text.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b03fe31b085d5507438676ae3ea886a6af0c769c Binary files /dev/null and b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/__pycache__/text.cpython-310.pyc differ diff --git a/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/__pycache__/usage.cpython-310.pyc b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/__pycache__/usage.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..866bb200ef381ec9a9d69711e676ddeb88d64881 Binary files /dev/null and b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/__pycache__/usage.cpython-310.pyc differ diff --git a/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/case.py b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/case.py new file mode 100644 index 0000000000000000000000000000000000000000..4c71857e40c4d1f517c0069b0b83ababcdfc0ae8 --- /dev/null +++ b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/case.py @@ -0,0 +1,157 @@ +# Human friendly input/output in Python. +# +# Author: Peter Odding +# Last Change: April 19, 2020 +# URL: https://humanfriendly.readthedocs.io + +""" +Simple case insensitive dictionaries. + +The :class:`CaseInsensitiveDict` class is a dictionary whose string keys +are case insensitive. It works by automatically coercing string keys to +:class:`CaseInsensitiveKey` objects. Keys that are not strings are +supported as well, just without case insensitivity. + +At its core this module works by normalizing strings to lowercase before +comparing or hashing them. It doesn't support proper case folding nor +does it support Unicode normalization, hence the word "simple". +""" + +# Standard library modules. +import collections + +try: + # Python >= 3.3. + from collections.abc import Iterable, Mapping +except ImportError: + # Python 2.7. + from collections import Iterable, Mapping + +# Modules included in our package. +from humanfriendly.compat import basestring, unicode + +# Public identifiers that require documentation. +__all__ = ("CaseInsensitiveDict", "CaseInsensitiveKey") + + +class CaseInsensitiveDict(collections.OrderedDict): + + """ + Simple case insensitive dictionary implementation (that remembers insertion order). + + This class works by overriding methods that deal with dictionary keys to + coerce string keys to :class:`CaseInsensitiveKey` objects before calling + down to the regular dictionary handling methods. While intended to be + complete this class has not been extensively tested yet. + """ + + def __init__(self, other=None, **kw): + """Initialize a :class:`CaseInsensitiveDict` object.""" + # Initialize our superclass. + super(CaseInsensitiveDict, self).__init__() + # Handle the initializer arguments. + self.update(other, **kw) + + def coerce_key(self, key): + """ + Coerce string keys to :class:`CaseInsensitiveKey` objects. + + :param key: The value to coerce (any type). + :returns: If `key` is a string then a :class:`CaseInsensitiveKey` + object is returned, otherwise the value of `key` is + returned unmodified. + """ + if isinstance(key, basestring): + key = CaseInsensitiveKey(key) + return key + + @classmethod + def fromkeys(cls, iterable, value=None): + """Create a case insensitive dictionary with keys from `iterable` and values set to `value`.""" + return cls((k, value) for k in iterable) + + def get(self, key, default=None): + """Get the value of an existing item.""" + return super(CaseInsensitiveDict, self).get(self.coerce_key(key), default) + + def pop(self, key, default=None): + """Remove an item from a case insensitive dictionary.""" + return super(CaseInsensitiveDict, self).pop(self.coerce_key(key), default) + + def setdefault(self, key, default=None): + """Get the value of an existing item or add a new item.""" + return super(CaseInsensitiveDict, self).setdefault(self.coerce_key(key), default) + + def update(self, other=None, **kw): + """Update a case insensitive dictionary with new items.""" + if isinstance(other, Mapping): + # Copy the items from the given mapping. + for key, value in other.items(): + self[key] = value + elif isinstance(other, Iterable): + # Copy the items from the given iterable. + for key, value in other: + self[key] = value + elif other is not None: + # Complain about unsupported values. + msg = "'%s' object is not iterable" + type_name = type(value).__name__ + raise TypeError(msg % type_name) + # Copy the keyword arguments (if any). + for key, value in kw.items(): + self[key] = value + + def __contains__(self, key): + """Check if a case insensitive dictionary contains the given key.""" + return super(CaseInsensitiveDict, self).__contains__(self.coerce_key(key)) + + def __delitem__(self, key): + """Delete an item in a case insensitive dictionary.""" + return super(CaseInsensitiveDict, self).__delitem__(self.coerce_key(key)) + + def __getitem__(self, key): + """Get the value of an item in a case insensitive dictionary.""" + return super(CaseInsensitiveDict, self).__getitem__(self.coerce_key(key)) + + def __setitem__(self, key, value): + """Set the value of an item in a case insensitive dictionary.""" + return super(CaseInsensitiveDict, self).__setitem__(self.coerce_key(key), value) + + +class CaseInsensitiveKey(unicode): + + """ + Simple case insensitive dictionary key implementation. + + The :class:`CaseInsensitiveKey` class provides an intentionally simple + implementation of case insensitive strings to be used as dictionary keys. + + If you need features like Unicode normalization or proper case folding + please consider using a more advanced implementation like the :pypi:`istr` + package instead. + """ + + def __new__(cls, value): + """Create a :class:`CaseInsensitiveKey` object.""" + # Delegate string object creation to our superclass. + obj = unicode.__new__(cls, value) + # Store the lowercased string and its hash value. + normalized = obj.lower() + obj._normalized = normalized + obj._hash_value = hash(normalized) + return obj + + def __hash__(self): + """Get the hash value of the lowercased string.""" + return self._hash_value + + def __eq__(self, other): + """Compare two strings as lowercase.""" + if isinstance(other, CaseInsensitiveKey): + # Fast path (and the most common case): Comparison with same type. + return self._normalized == other._normalized + elif isinstance(other, unicode): + # Slow path: Comparison with strings that need lowercasing. + return self._normalized == other.lower() + else: + return NotImplemented diff --git a/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/cli.py b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..eb81db172bcdc45fb0d0cea32a63df07a3abde4a --- /dev/null +++ b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/cli.py @@ -0,0 +1,291 @@ +# Human friendly input/output in Python. +# +# Author: Peter Odding +# Last Change: March 1, 2020 +# URL: https://humanfriendly.readthedocs.io + +""" +Usage: humanfriendly [OPTIONS] + +Human friendly input/output (text formatting) on the command +line based on the Python package with the same name. + +Supported options: + + -c, --run-command + + Execute an external command (given as the positional arguments) and render + a spinner and timer while the command is running. The exit status of the + command is propagated. + + --format-table + + Read tabular data from standard input (each line is a row and each + whitespace separated field is a column), format the data as a table and + print the resulting table to standard output. See also the --delimiter + option. + + -d, --delimiter=VALUE + + Change the delimiter used by --format-table to VALUE (a string). By default + all whitespace is treated as a delimiter. + + -l, --format-length=LENGTH + + Convert a length count (given as the integer or float LENGTH) into a human + readable string and print that string to standard output. + + -n, --format-number=VALUE + + Format a number (given as the integer or floating point number VALUE) with + thousands separators and two decimal places (if needed) and print the + formatted number to standard output. + + -s, --format-size=BYTES + + Convert a byte count (given as the integer BYTES) into a human readable + string and print that string to standard output. + + -b, --binary + + Change the output of -s, --format-size to use binary multiples of bytes + (base-2) instead of the default decimal multiples of bytes (base-10). + + -t, --format-timespan=SECONDS + + Convert a number of seconds (given as the floating point number SECONDS) + into a human readable timespan and print that string to standard output. + + --parse-length=VALUE + + Parse a human readable length (given as the string VALUE) and print the + number of metres to standard output. + + --parse-size=VALUE + + Parse a human readable data size (given as the string VALUE) and print the + number of bytes to standard output. + + --demo + + Demonstrate changing the style and color of the terminal font using ANSI + escape sequences. + + -h, --help + + Show this message and exit. +""" + +# Standard library modules. +import functools +import getopt +import pipes +import subprocess +import sys + +# Modules included in our package. +from humanfriendly import ( + Timer, + format_length, + format_number, + format_size, + format_timespan, + parse_length, + parse_size, +) +from humanfriendly.tables import format_pretty_table, format_smart_table +from humanfriendly.terminal import ( + ANSI_COLOR_CODES, + ANSI_TEXT_STYLES, + HIGHLIGHT_COLOR, + ansi_strip, + ansi_wrap, + enable_ansi_support, + find_terminal_size, + output, + usage, + warning, +) +from humanfriendly.terminal.spinners import Spinner + +# Public identifiers that require documentation. +__all__ = ( + 'demonstrate_256_colors', + 'demonstrate_ansi_formatting', + 'main', + 'print_formatted_length', + 'print_formatted_number', + 'print_formatted_size', + 'print_formatted_table', + 'print_formatted_timespan', + 'print_parsed_length', + 'print_parsed_size', + 'run_command', +) + + +def main(): + """Command line interface for the ``humanfriendly`` program.""" + enable_ansi_support() + try: + options, arguments = getopt.getopt(sys.argv[1:], 'cd:l:n:s:bt:h', [ + 'run-command', 'format-table', 'delimiter=', 'format-length=', + 'format-number=', 'format-size=', 'binary', 'format-timespan=', + 'parse-length=', 'parse-size=', 'demo', 'help', + ]) + except Exception as e: + warning("Error: %s", e) + sys.exit(1) + actions = [] + delimiter = None + should_format_table = False + binary = any(o in ('-b', '--binary') for o, v in options) + for option, value in options: + if option in ('-d', '--delimiter'): + delimiter = value + elif option == '--parse-size': + actions.append(functools.partial(print_parsed_size, value)) + elif option == '--parse-length': + actions.append(functools.partial(print_parsed_length, value)) + elif option in ('-c', '--run-command'): + actions.append(functools.partial(run_command, arguments)) + elif option in ('-l', '--format-length'): + actions.append(functools.partial(print_formatted_length, value)) + elif option in ('-n', '--format-number'): + actions.append(functools.partial(print_formatted_number, value)) + elif option in ('-s', '--format-size'): + actions.append(functools.partial(print_formatted_size, value, binary)) + elif option == '--format-table': + should_format_table = True + elif option in ('-t', '--format-timespan'): + actions.append(functools.partial(print_formatted_timespan, value)) + elif option == '--demo': + actions.append(demonstrate_ansi_formatting) + elif option in ('-h', '--help'): + usage(__doc__) + return + if should_format_table: + actions.append(functools.partial(print_formatted_table, delimiter)) + if not actions: + usage(__doc__) + return + for partial in actions: + partial() + + +def run_command(command_line): + """Run an external command and show a spinner while the command is running.""" + timer = Timer() + spinner_label = "Waiting for command: %s" % " ".join(map(pipes.quote, command_line)) + with Spinner(label=spinner_label, timer=timer) as spinner: + process = subprocess.Popen(command_line) + while True: + spinner.step() + spinner.sleep() + if process.poll() is not None: + break + sys.exit(process.returncode) + + +def print_formatted_length(value): + """Print a human readable length.""" + if '.' in value: + output(format_length(float(value))) + else: + output(format_length(int(value))) + + +def print_formatted_number(value): + """Print large numbers in a human readable format.""" + output(format_number(float(value))) + + +def print_formatted_size(value, binary): + """Print a human readable size.""" + output(format_size(int(value), binary=binary)) + + +def print_formatted_table(delimiter): + """Read tabular data from standard input and print a table.""" + data = [] + for line in sys.stdin: + line = line.rstrip() + data.append(line.split(delimiter)) + output(format_pretty_table(data)) + + +def print_formatted_timespan(value): + """Print a human readable timespan.""" + output(format_timespan(float(value))) + + +def print_parsed_length(value): + """Parse a human readable length and print the number of metres.""" + output(parse_length(value)) + + +def print_parsed_size(value): + """Parse a human readable data size and print the number of bytes.""" + output(parse_size(value)) + + +def demonstrate_ansi_formatting(): + """Demonstrate the use of ANSI escape sequences.""" + # First we demonstrate the supported text styles. + output('%s', ansi_wrap('Text styles:', bold=True)) + styles = ['normal', 'bright'] + styles.extend(ANSI_TEXT_STYLES.keys()) + for style_name in sorted(styles): + options = dict(color=HIGHLIGHT_COLOR) + if style_name != 'normal': + options[style_name] = True + style_label = style_name.replace('_', ' ').capitalize() + output(' - %s', ansi_wrap(style_label, **options)) + # Now we demonstrate named foreground and background colors. + for color_type, color_label in (('color', 'Foreground colors'), + ('background', 'Background colors')): + intensities = [ + ('normal', dict()), + ('bright', dict(bright=True)), + ] + if color_type != 'background': + intensities.insert(0, ('faint', dict(faint=True))) + output('\n%s' % ansi_wrap('%s:' % color_label, bold=True)) + output(format_smart_table([ + [color_name] + [ + ansi_wrap( + 'XXXXXX' if color_type != 'background' else (' ' * 6), + **dict(list(kw.items()) + [(color_type, color_name)]) + ) for label, kw in intensities + ] for color_name in sorted(ANSI_COLOR_CODES.keys()) + ], column_names=['Color'] + [ + label.capitalize() for label, kw in intensities + ])) + # Demonstrate support for 256 colors as well. + demonstrate_256_colors(0, 7, 'standard colors') + demonstrate_256_colors(8, 15, 'high-intensity colors') + demonstrate_256_colors(16, 231, '216 colors') + demonstrate_256_colors(232, 255, 'gray scale colors') + + +def demonstrate_256_colors(i, j, group=None): + """Demonstrate 256 color mode support.""" + # Generate the label. + label = '256 color mode' + if group: + label += ' (%s)' % group + output('\n' + ansi_wrap('%s:' % label, bold=True)) + # Generate a simple rendering of the colors in the requested range and + # check if it will fit on a single line (given the terminal's width). + single_line = ''.join(' ' + ansi_wrap(str(n), color=n) for n in range(i, j + 1)) + lines, columns = find_terminal_size() + if columns >= len(ansi_strip(single_line)): + output(single_line) + else: + # Generate a more complex rendering of the colors that will nicely wrap + # over multiple lines without using too many lines. + width = len(str(j)) + 1 + colors_per_line = int(columns / width) + colors = [ansi_wrap(str(n).rjust(width), color=n) for n in range(i, j + 1)] + blocks = [colors[n:n + colors_per_line] for n in range(0, len(colors), colors_per_line)] + output('\n'.join(''.join(b) for b in blocks)) diff --git a/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/compat.py b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/compat.py new file mode 100644 index 0000000000000000000000000000000000000000..24c9d1833adbcc8a0f7ad736b63e37e8e88ec9d4 --- /dev/null +++ b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/compat.py @@ -0,0 +1,146 @@ +# Human friendly input/output in Python. +# +# Author: Peter Odding +# Last Change: September 17, 2021 +# URL: https://humanfriendly.readthedocs.io + +""" +Compatibility with Python 2 and 3. + +This module exposes aliases and functions that make it easier to write Python +code that is compatible with Python 2 and Python 3. + +.. data:: basestring + + Alias for :func:`python2:basestring` (in Python 2) or :class:`python3:str` + (in Python 3). See also :func:`is_string()`. + +.. data:: HTMLParser + + Alias for :class:`python2:HTMLParser.HTMLParser` (in Python 2) or + :class:`python3:html.parser.HTMLParser` (in Python 3). + +.. data:: interactive_prompt + + Alias for :func:`python2:raw_input()` (in Python 2) or + :func:`python3:input()` (in Python 3). + +.. data:: StringIO + + Alias for :class:`python2:StringIO.StringIO` (in Python 2) or + :class:`python3:io.StringIO` (in Python 3). + +.. data:: unicode + + Alias for :func:`python2:unicode` (in Python 2) or :class:`python3:str` (in + Python 3). See also :func:`coerce_string()`. + +.. data:: monotonic + + Alias for :func:`python3:time.monotonic()` (in Python 3.3 and higher) or + `monotonic.monotonic()` (a `conditional dependency + `_ on older Python versions). +""" + +__all__ = ( + 'HTMLParser', + 'StringIO', + 'basestring', + 'coerce_string', + 'interactive_prompt', + 'is_string', + 'is_unicode', + 'monotonic', + 'name2codepoint', + 'on_macos', + 'on_windows', + 'unichr', + 'unicode', + 'which', +) + +# Standard library modules. +import sys + +# Differences between Python 2 and 3. +try: + # Python 2. + unicode = unicode + unichr = unichr + basestring = basestring + interactive_prompt = raw_input + from distutils.spawn import find_executable as which + from HTMLParser import HTMLParser + from StringIO import StringIO + from htmlentitydefs import name2codepoint +except (ImportError, NameError): + # Python 3. + unicode = str + unichr = chr + basestring = str + interactive_prompt = input + from shutil import which + from html.parser import HTMLParser + from io import StringIO + from html.entities import name2codepoint + +try: + # Python 3.3 and higher. + from time import monotonic +except ImportError: + # A replacement for older Python versions: + # https://pypi.org/project/monotonic/ + try: + from monotonic import monotonic + except (ImportError, RuntimeError): + # We fall back to the old behavior of using time.time() instead of + # failing when {time,monotonic}.monotonic() are both missing. + from time import time as monotonic + + +def coerce_string(value): + """ + Coerce any value to a Unicode string (:func:`python2:unicode` in Python 2 and :class:`python3:str` in Python 3). + + :param value: The value to coerce. + :returns: The value coerced to a Unicode string. + """ + return value if is_string(value) else unicode(value) + + +def is_string(value): + """ + Check if a value is a :func:`python2:basestring` (in Python 2) or :class:`python3:str` (in Python 3) object. + + :param value: The value to check. + :returns: :data:`True` if the value is a string, :data:`False` otherwise. + """ + return isinstance(value, basestring) + + +def is_unicode(value): + """ + Check if a value is a :func:`python2:unicode` (in Python 2) or :class:`python2:str` (in Python 3) object. + + :param value: The value to check. + :returns: :data:`True` if the value is a Unicode string, :data:`False` otherwise. + """ + return isinstance(value, unicode) + + +def on_macos(): + """ + Check if we're running on Apple MacOS. + + :returns: :data:`True` if running MacOS, :data:`False` otherwise. + """ + return sys.platform.startswith('darwin') + + +def on_windows(): + """ + Check if we're running on the Microsoft Windows OS. + + :returns: :data:`True` if running Windows, :data:`False` otherwise. + """ + return sys.platform.startswith('win') diff --git a/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/deprecation.py b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/deprecation.py new file mode 100644 index 0000000000000000000000000000000000000000..f2012bbd6f3ddd9b955f7a25010cd78ece431c6a --- /dev/null +++ b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/deprecation.py @@ -0,0 +1,251 @@ +# Human friendly input/output in Python. +# +# Author: Peter Odding +# Last Change: March 2, 2020 +# URL: https://humanfriendly.readthedocs.io + +""" +Support for deprecation warnings when importing names from old locations. + +When software evolves, things tend to move around. This is usually detrimental +to backwards compatibility (in Python this primarily manifests itself as +:exc:`~exceptions.ImportError` exceptions). + +While backwards compatibility is very important, it should not get in the way +of progress. It would be great to have the agility to move things around +without breaking backwards compatibility. + +This is where the :mod:`humanfriendly.deprecation` module comes in: It enables +the definition of backwards compatible aliases that emit a deprecation warning +when they are accessed. + +The way it works is that it wraps the original module in an :class:`DeprecationProxy` +object that defines a :func:`~DeprecationProxy.__getattr__()` special method to +override attribute access of the module. +""" + +# Standard library modules. +import collections +import functools +import importlib +import inspect +import sys +import types +import warnings + +# Modules included in our package. +from humanfriendly.text import format + +# Registry of known aliases (used by humanfriendly.sphinx). +REGISTRY = collections.defaultdict(dict) + +# Public identifiers that require documentation. +__all__ = ("DeprecationProxy", "define_aliases", "deprecated_args", "get_aliases", "is_method") + + +def define_aliases(module_name, **aliases): + """ + Update a module with backwards compatible aliases. + + :param module_name: The ``__name__`` of the module (a string). + :param aliases: Each keyword argument defines an alias. The values + are expected to be "dotted paths" (strings). + + The behavior of this function depends on whether the Sphinx documentation + generator is active, because the use of :class:`DeprecationProxy` to shadow the + real module in :data:`sys.modules` has the unintended side effect of + breaking autodoc support for ``:data:`` members (module variables). + + To avoid breaking Sphinx the proxy object is omitted and instead the + aliased names are injected into the original module namespace, to make sure + that imports can be satisfied when the documentation is being rendered. + + If you run into cyclic dependencies caused by :func:`define_aliases()` when + running Sphinx, you can try moving the call to :func:`define_aliases()` to + the bottom of the Python module you're working on. + """ + module = sys.modules[module_name] + proxy = DeprecationProxy(module, aliases) + # Populate the registry of aliases. + for name, target in aliases.items(): + REGISTRY[module.__name__][name] = target + # Avoid confusing Sphinx. + if "sphinx" in sys.modules: + for name, target in aliases.items(): + setattr(module, name, proxy.resolve(target)) + else: + # Install a proxy object to raise DeprecationWarning. + sys.modules[module_name] = proxy + + +def get_aliases(module_name): + """ + Get the aliases defined by a module. + + :param module_name: The ``__name__`` of the module (a string). + :returns: A dictionary with string keys and values: + + 1. Each key gives the name of an alias + created for backwards compatibility. + + 2. Each value gives the dotted path of + the proper location of the identifier. + + An empty dictionary is returned for modules that + don't define any backwards compatible aliases. + """ + return REGISTRY.get(module_name, {}) + + +def deprecated_args(*names): + """ + Deprecate positional arguments without dropping backwards compatibility. + + :param names: + + The positional arguments to :func:`deprecated_args()` give the names of + the positional arguments that the to-be-decorated function should warn + about being deprecated and translate to keyword arguments. + + :returns: A decorator function specialized to `names`. + + The :func:`deprecated_args()` decorator function was created to make it + easy to switch from positional arguments to keyword arguments [#]_ while + preserving backwards compatibility [#]_ and informing call sites + about the change. + + .. [#] Increased flexibility is the main reason why I find myself switching + from positional arguments to (optional) keyword arguments as my code + evolves to support more use cases. + + .. [#] In my experience positional argument order implicitly becomes part + of API compatibility whether intended or not. While this makes sense + for functions that over time adopt more and more optional arguments, + at a certain point it becomes an inconvenience to code maintenance. + + Here's an example of how to use the decorator:: + + @deprecated_args('text') + def report_choice(**options): + print(options['text']) + + When the decorated function is called with positional arguments + a deprecation warning is given:: + + >>> report_choice('this will give a deprecation warning') + DeprecationWarning: report_choice has deprecated positional arguments, please switch to keyword arguments + this will give a deprecation warning + + But when the function is called with keyword arguments no deprecation + warning is emitted:: + + >>> report_choice(text='this will not give a deprecation warning') + this will not give a deprecation warning + """ + def decorator(function): + def translate(args, kw): + # Raise TypeError when too many positional arguments are passed to the decorated function. + if len(args) > len(names): + raise TypeError( + format( + "{name} expected at most {limit} arguments, got {count}", + name=function.__name__, + limit=len(names), + count=len(args), + ) + ) + # Emit a deprecation warning when positional arguments are used. + if args: + warnings.warn( + format( + "{name} has deprecated positional arguments, please switch to keyword arguments", + name=function.__name__, + ), + category=DeprecationWarning, + stacklevel=3, + ) + # Translate positional arguments to keyword arguments. + for name, value in zip(names, args): + kw[name] = value + if is_method(function): + @functools.wraps(function) + def wrapper(*args, **kw): + """Wrapper for instance methods.""" + args = list(args) + self = args.pop(0) + translate(args, kw) + return function(self, **kw) + else: + @functools.wraps(function) + def wrapper(*args, **kw): + """Wrapper for module level functions.""" + translate(args, kw) + return function(**kw) + return wrapper + return decorator + + +def is_method(function): + """Check if the expected usage of the given function is as an instance method.""" + try: + # Python 3.3 and newer. + signature = inspect.signature(function) + return "self" in signature.parameters + except AttributeError: + # Python 3.2 and older. + metadata = inspect.getargspec(function) + return "self" in metadata.args + + +class DeprecationProxy(types.ModuleType): + + """Emit deprecation warnings for imports that should be updated.""" + + def __init__(self, module, aliases): + """ + Initialize an :class:`DeprecationProxy` object. + + :param module: The original module object. + :param aliases: A dictionary of aliases. + """ + # Initialize our superclass. + super(DeprecationProxy, self).__init__(name=module.__name__) + # Store initializer arguments. + self.module = module + self.aliases = aliases + + def __getattr__(self, name): + """ + Override module attribute lookup. + + :param name: The name to look up (a string). + :returns: The attribute value. + """ + # Check if the given name is an alias. + target = self.aliases.get(name) + if target is not None: + # Emit the deprecation warning. + warnings.warn( + format("%s.%s was moved to %s, please update your imports", self.module.__name__, name, target), + category=DeprecationWarning, + stacklevel=2, + ) + # Resolve the dotted path. + return self.resolve(target) + # Look up the name in the original module namespace. + value = getattr(self.module, name, None) + if value is not None: + return value + # Fall back to the default behavior. + raise AttributeError(format("module '%s' has no attribute '%s'", self.module.__name__, name)) + + def resolve(self, target): + """ + Look up the target of an alias. + + :param target: The fully qualified dotted path (a string). + :returns: The value of the given target. + """ + module_name, _, member = target.rpartition(".") + module = importlib.import_module(module_name) + return getattr(module, member) diff --git a/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/sphinx.py b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/sphinx.py new file mode 100644 index 0000000000000000000000000000000000000000..cf5d1b393567ed58457c490186d908c529449df3 --- /dev/null +++ b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/sphinx.py @@ -0,0 +1,315 @@ +# Human friendly input/output in Python. +# +# Author: Peter Odding +# Last Change: June 11, 2021 +# URL: https://humanfriendly.readthedocs.io + +""" +Customizations for and integration with the Sphinx_ documentation generator. + +The :mod:`humanfriendly.sphinx` module uses the `Sphinx extension API`_ to +customize the process of generating Sphinx based Python documentation. To +explore the functionality this module offers its best to start reading +from the :func:`setup()` function. + +.. _Sphinx: http://www.sphinx-doc.org/ +.. _Sphinx extension API: http://sphinx-doc.org/extdev/appapi.html +""" + +# Standard library modules. +import logging +import types + +# External dependencies (if Sphinx is installed docutils will be installed). +import docutils.nodes +import docutils.utils + +# Modules included in our package. +from humanfriendly.deprecation import get_aliases +from humanfriendly.text import compact, dedent, format +from humanfriendly.usage import USAGE_MARKER, render_usage + +# Public identifiers that require documentation. +__all__ = ( + "deprecation_note_callback", + "enable_deprecation_notes", + "enable_man_role", + "enable_pypi_role", + "enable_special_methods", + "enable_usage_formatting", + "logger", + "man_role", + "pypi_role", + "setup", + "special_methods_callback", + "usage_message_callback", +) + +# Initialize a logger for this module. +logger = logging.getLogger(__name__) + + +def deprecation_note_callback(app, what, name, obj, options, lines): + """ + Automatically document aliases defined using :func:`~humanfriendly.deprecation.define_aliases()`. + + Refer to :func:`enable_deprecation_notes()` to enable the use of this + function (you probably don't want to call :func:`deprecation_note_callback()` + directly). + + This function implements a callback for ``autodoc-process-docstring`` that + reformats module docstrings to append an overview of aliases defined by the + module. + + The parameters expected by this function are those defined for Sphinx event + callback functions (i.e. I'm not going to document them here :-). + """ + if isinstance(obj, types.ModuleType) and lines: + aliases = get_aliases(obj.__name__) + if aliases: + # Convert the existing docstring to a string and remove leading + # indentation from that string, otherwise our generated content + # would have to match the existing indentation in order not to + # break docstring parsing (because indentation is significant + # in the reStructuredText format). + blocks = [dedent("\n".join(lines))] + # Use an admonition to group the deprecated aliases together and + # to distinguish them from the autodoc entries that follow. + blocks.append(".. note:: Deprecated names") + indent = " " * 3 + if len(aliases) == 1: + explanation = """ + The following alias exists to preserve backwards compatibility, + however a :exc:`~exceptions.DeprecationWarning` is triggered + when it is accessed, because this alias will be removed + in a future release. + """ + else: + explanation = """ + The following aliases exist to preserve backwards compatibility, + however a :exc:`~exceptions.DeprecationWarning` is triggered + when they are accessed, because these aliases will be + removed in a future release. + """ + blocks.append(indent + compact(explanation)) + for name, target in aliases.items(): + blocks.append(format("%s.. data:: %s", indent, name)) + blocks.append(format("%sAlias for :obj:`%s`.", indent * 2, target)) + update_lines(lines, "\n\n".join(blocks)) + + +def enable_deprecation_notes(app): + """ + Enable documenting backwards compatibility aliases using the autodoc_ extension. + + :param app: The Sphinx application object. + + This function connects the :func:`deprecation_note_callback()` function to + ``autodoc-process-docstring`` events. + + .. _autodoc: http://www.sphinx-doc.org/en/stable/ext/autodoc.html + """ + app.connect("autodoc-process-docstring", deprecation_note_callback) + + +def enable_man_role(app): + """ + Enable the ``:man:`` role for linking to Debian Linux manual pages. + + :param app: The Sphinx application object. + + This function registers the :func:`man_role()` function to handle the + ``:man:`` role. + """ + app.add_role("man", man_role) + + +def enable_pypi_role(app): + """ + Enable the ``:pypi:`` role for linking to the Python Package Index. + + :param app: The Sphinx application object. + + This function registers the :func:`pypi_role()` function to handle the + ``:pypi:`` role. + """ + app.add_role("pypi", pypi_role) + + +def enable_special_methods(app): + """ + Enable documenting "special methods" using the autodoc_ extension. + + :param app: The Sphinx application object. + + This function connects the :func:`special_methods_callback()` function to + ``autodoc-skip-member`` events. + + .. _autodoc: http://www.sphinx-doc.org/en/stable/ext/autodoc.html + """ + app.connect("autodoc-skip-member", special_methods_callback) + + +def enable_usage_formatting(app): + """ + Reformat human friendly usage messages to reStructuredText_. + + :param app: The Sphinx application object (as given to ``setup()``). + + This function connects the :func:`usage_message_callback()` function to + ``autodoc-process-docstring`` events. + + .. _reStructuredText: https://en.wikipedia.org/wiki/ReStructuredText + """ + app.connect("autodoc-process-docstring", usage_message_callback) + + +def man_role(role, rawtext, text, lineno, inliner, options={}, content=[]): + """ + Convert a Linux manual topic to a hyperlink. + + Using the ``:man:`` role is very simple, here's an example: + + .. code-block:: rst + + See the :man:`python` documentation. + + This results in the following: + + See the :man:`python` documentation. + + As the example shows you can use the role inline, embedded in sentences of + text. In the generated documentation the ``:man:`` text is omitted and a + hyperlink pointing to the Debian Linux manual pages is emitted. + """ + man_url = "https://manpages.debian.org/%s" % text + reference = docutils.nodes.reference(rawtext, docutils.utils.unescape(text), refuri=man_url, **options) + return [reference], [] + + +def pypi_role(role, rawtext, text, lineno, inliner, options={}, content=[]): + """ + Generate hyperlinks to the Python Package Index. + + Using the ``:pypi:`` role is very simple, here's an example: + + .. code-block:: rst + + See the :pypi:`humanfriendly` package. + + This results in the following: + + See the :pypi:`humanfriendly` package. + + As the example shows you can use the role inline, embedded in sentences of + text. In the generated documentation the ``:pypi:`` text is omitted and a + hyperlink pointing to the Python Package Index is emitted. + """ + pypi_url = "https://pypi.org/project/%s/" % text + reference = docutils.nodes.reference(rawtext, docutils.utils.unescape(text), refuri=pypi_url, **options) + return [reference], [] + + +def setup(app): + """ + Enable all of the provided Sphinx_ customizations. + + :param app: The Sphinx application object. + + The :func:`setup()` function makes it easy to enable all of the Sphinx + customizations provided by the :mod:`humanfriendly.sphinx` module with the + least amount of code. All you need to do is to add the module name to the + ``extensions`` variable in your ``conf.py`` file: + + .. code-block:: python + + # Sphinx extension module names. + extensions = [ + 'sphinx.ext.autodoc', + 'sphinx.ext.doctest', + 'sphinx.ext.intersphinx', + 'humanfriendly.sphinx', + ] + + When Sphinx sees the :mod:`humanfriendly.sphinx` name it will import the + module and call its :func:`setup()` function. This function will then call + the following: + + - :func:`enable_deprecation_notes()` + - :func:`enable_man_role()` + - :func:`enable_pypi_role()` + - :func:`enable_special_methods()` + - :func:`enable_usage_formatting()` + + Of course more functionality may be added at a later stage. If you don't + like that idea you may be better of calling the individual functions from + your own ``setup()`` function. + """ + from humanfriendly import __version__ + + enable_deprecation_notes(app) + enable_man_role(app) + enable_pypi_role(app) + enable_special_methods(app) + enable_usage_formatting(app) + + return dict(parallel_read_safe=True, parallel_write_safe=True, version=__version__) + + +def special_methods_callback(app, what, name, obj, skip, options): + """ + Enable documenting "special methods" using the autodoc_ extension. + + Refer to :func:`enable_special_methods()` to enable the use of this + function (you probably don't want to call + :func:`special_methods_callback()` directly). + + This function implements a callback for ``autodoc-skip-member`` events to + include documented "special methods" (method names with two leading and two + trailing underscores) in your documentation. The result is similar to the + use of the ``special-members`` flag with one big difference: Special + methods are included but other types of members are ignored. This means + that attributes like ``__weakref__`` will always be ignored (this was my + main annoyance with the ``special-members`` flag). + + The parameters expected by this function are those defined for Sphinx event + callback functions (i.e. I'm not going to document them here :-). + """ + if getattr(obj, "__doc__", None) and isinstance(obj, (types.FunctionType, types.MethodType)): + return False + else: + return skip + + +def update_lines(lines, text): + """Private helper for ``autodoc-process-docstring`` callbacks.""" + while lines: + lines.pop() + lines.extend(text.splitlines()) + + +def usage_message_callback(app, what, name, obj, options, lines): + """ + Reformat human friendly usage messages to reStructuredText_. + + Refer to :func:`enable_usage_formatting()` to enable the use of this + function (you probably don't want to call :func:`usage_message_callback()` + directly). + + This function implements a callback for ``autodoc-process-docstring`` that + reformats module docstrings using :func:`.render_usage()` so that Sphinx + doesn't mangle usage messages that were written to be human readable + instead of machine readable. Only module docstrings whose first line starts + with :data:`.USAGE_MARKER` are reformatted. + + The parameters expected by this function are those defined for Sphinx event + callback functions (i.e. I'm not going to document them here :-). + """ + # Make sure we only modify the docstrings of modules. + if isinstance(obj, types.ModuleType) and lines: + # Make sure we only modify docstrings containing a usage message. + if lines[0].startswith(USAGE_MARKER): + # Convert the usage message to reStructuredText. + text = render_usage("\n".join(lines)) + # Fill up the buffer with our modified docstring. + update_lines(lines, text) diff --git a/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/tables.py b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/tables.py new file mode 100644 index 0000000000000000000000000000000000000000..3a32ba3b3f6dc9866e74b1f0ea7ea21a01bc81e0 --- /dev/null +++ b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/tables.py @@ -0,0 +1,341 @@ +# Human friendly input/output in Python. +# +# Author: Peter Odding +# Last Change: February 16, 2020 +# URL: https://humanfriendly.readthedocs.io + +""" +Functions that render ASCII tables. + +Some generic notes about the table formatting functions in this module: + +- These functions were not written with performance in mind (*at all*) because + they're intended to format tabular data to be presented on a terminal. If + someone were to run into a performance problem using these functions, they'd + be printing so much tabular data to the terminal that a human wouldn't be + able to digest the tabular data anyway, so the point is moot :-). + +- These functions ignore ANSI escape sequences (at least the ones generated by + the :mod:`~humanfriendly.terminal` module) in the calculation of columns + widths. On reason for this is that column names are highlighted in color when + connected to a terminal. It also means that you can use ANSI escape sequences + to highlight certain column's values if you feel like it (for example to + highlight deviations from the norm in an overview of calculated values). +""" + +# Standard library modules. +import collections +import re + +# Modules included in our package. +from humanfriendly.compat import coerce_string +from humanfriendly.terminal import ( + ansi_strip, + ansi_width, + ansi_wrap, + terminal_supports_colors, + find_terminal_size, + HIGHLIGHT_COLOR, +) + +# Public identifiers that require documentation. +__all__ = ( + 'format_pretty_table', + 'format_robust_table', + 'format_rst_table', + 'format_smart_table', +) + +# Compiled regular expression pattern to recognize table columns containing +# numeric data (integer and/or floating point numbers). Used to right-align the +# contents of such columns. +# +# Pre-emptive snarky comment: This pattern doesn't match every possible +# floating point number notation!?!1!1 +# +# Response: I know, that's intentional. The use of this regular expression +# pattern has a very high DWIM level and weird floating point notations do not +# fall under the DWIM umbrella :-). +NUMERIC_DATA_PATTERN = re.compile(r'^\d+(\.\d+)?$') + + +def format_smart_table(data, column_names): + """ + Render tabular data using the most appropriate representation. + + :param data: An iterable (e.g. a :func:`tuple` or :class:`list`) + containing the rows of the table, where each row is an + iterable containing the columns of the table (strings). + :param column_names: An iterable of column names (strings). + :returns: The rendered table (a string). + + If you want an easy way to render tabular data on a terminal in a human + friendly format then this function is for you! It works as follows: + + - If the input data doesn't contain any line breaks the function + :func:`format_pretty_table()` is used to render a pretty table. If the + resulting table fits in the terminal without wrapping the rendered pretty + table is returned. + + - If the input data does contain line breaks or if a pretty table would + wrap (given the width of the terminal) then the function + :func:`format_robust_table()` is used to render a more robust table that + can deal with data containing line breaks and long text. + """ + # Normalize the input in case we fall back from a pretty table to a robust + # table (in which case we'll definitely iterate the input more than once). + data = [normalize_columns(r) for r in data] + column_names = normalize_columns(column_names) + # Make sure the input data doesn't contain any line breaks (because pretty + # tables break horribly when a column's text contains a line break :-). + if not any(any('\n' in c for c in r) for r in data): + # Render a pretty table. + pretty_table = format_pretty_table(data, column_names) + # Check if the pretty table fits in the terminal. + table_width = max(map(ansi_width, pretty_table.splitlines())) + num_rows, num_columns = find_terminal_size() + if table_width <= num_columns: + # The pretty table fits in the terminal without wrapping! + return pretty_table + # Fall back to a robust table when a pretty table won't work. + return format_robust_table(data, column_names) + + +def format_pretty_table(data, column_names=None, horizontal_bar='-', vertical_bar='|'): + """ + Render a table using characters like dashes and vertical bars to emulate borders. + + :param data: An iterable (e.g. a :func:`tuple` or :class:`list`) + containing the rows of the table, where each row is an + iterable containing the columns of the table (strings). + :param column_names: An iterable of column names (strings). + :param horizontal_bar: The character used to represent a horizontal bar (a + string). + :param vertical_bar: The character used to represent a vertical bar (a + string). + :returns: The rendered table (a string). + + Here's an example: + + >>> from humanfriendly.tables import format_pretty_table + >>> column_names = ['Version', 'Uploaded on', 'Downloads'] + >>> humanfriendly_releases = [ + ... ['1.23', '2015-05-25', '218'], + ... ['1.23.1', '2015-05-26', '1354'], + ... ['1.24', '2015-05-26', '223'], + ... ['1.25', '2015-05-26', '4319'], + ... ['1.25.1', '2015-06-02', '197'], + ... ] + >>> print(format_pretty_table(humanfriendly_releases, column_names)) + ------------------------------------- + | Version | Uploaded on | Downloads | + ------------------------------------- + | 1.23 | 2015-05-25 | 218 | + | 1.23.1 | 2015-05-26 | 1354 | + | 1.24 | 2015-05-26 | 223 | + | 1.25 | 2015-05-26 | 4319 | + | 1.25.1 | 2015-06-02 | 197 | + ------------------------------------- + + Notes about the resulting table: + + - If a column contains numeric data (integer and/or floating point + numbers) in all rows (ignoring column names of course) then the content + of that column is right-aligned, as can be seen in the example above. The + idea here is to make it easier to compare the numbers in different + columns to each other. + + - The column names are highlighted in color so they stand out a bit more + (see also :data:`.HIGHLIGHT_COLOR`). The following screen shot shows what + that looks like (my terminals are always set to white text on a black + background): + + .. image:: images/pretty-table.png + """ + # Normalize the input because we'll have to iterate it more than once. + data = [normalize_columns(r, expandtabs=True) for r in data] + if column_names is not None: + column_names = normalize_columns(column_names) + if column_names: + if terminal_supports_colors(): + column_names = [highlight_column_name(n) for n in column_names] + data.insert(0, column_names) + # Calculate the maximum width of each column. + widths = collections.defaultdict(int) + numeric_data = collections.defaultdict(list) + for row_index, row in enumerate(data): + for column_index, column in enumerate(row): + widths[column_index] = max(widths[column_index], ansi_width(column)) + if not (column_names and row_index == 0): + numeric_data[column_index].append(bool(NUMERIC_DATA_PATTERN.match(ansi_strip(column)))) + # Create a horizontal bar of dashes as a delimiter. + line_delimiter = horizontal_bar * (sum(widths.values()) + len(widths) * 3 + 1) + # Start the table with a vertical bar. + lines = [line_delimiter] + # Format the rows and columns. + for row_index, row in enumerate(data): + line = [vertical_bar] + for column_index, column in enumerate(row): + padding = ' ' * (widths[column_index] - ansi_width(column)) + if all(numeric_data[column_index]): + line.append(' ' + padding + column + ' ') + else: + line.append(' ' + column + padding + ' ') + line.append(vertical_bar) + lines.append(u''.join(line)) + if column_names and row_index == 0: + lines.append(line_delimiter) + # End the table with a vertical bar. + lines.append(line_delimiter) + # Join the lines, returning a single string. + return u'\n'.join(lines) + + +def format_robust_table(data, column_names): + """ + Render tabular data with one column per line (allowing columns with line breaks). + + :param data: An iterable (e.g. a :func:`tuple` or :class:`list`) + containing the rows of the table, where each row is an + iterable containing the columns of the table (strings). + :param column_names: An iterable of column names (strings). + :returns: The rendered table (a string). + + Here's an example: + + >>> from humanfriendly.tables import format_robust_table + >>> column_names = ['Version', 'Uploaded on', 'Downloads'] + >>> humanfriendly_releases = [ + ... ['1.23', '2015-05-25', '218'], + ... ['1.23.1', '2015-05-26', '1354'], + ... ['1.24', '2015-05-26', '223'], + ... ['1.25', '2015-05-26', '4319'], + ... ['1.25.1', '2015-06-02', '197'], + ... ] + >>> print(format_robust_table(humanfriendly_releases, column_names)) + ----------------------- + Version: 1.23 + Uploaded on: 2015-05-25 + Downloads: 218 + ----------------------- + Version: 1.23.1 + Uploaded on: 2015-05-26 + Downloads: 1354 + ----------------------- + Version: 1.24 + Uploaded on: 2015-05-26 + Downloads: 223 + ----------------------- + Version: 1.25 + Uploaded on: 2015-05-26 + Downloads: 4319 + ----------------------- + Version: 1.25.1 + Uploaded on: 2015-06-02 + Downloads: 197 + ----------------------- + + The column names are highlighted in bold font and color so they stand out a + bit more (see :data:`.HIGHLIGHT_COLOR`). + """ + blocks = [] + column_names = ["%s:" % n for n in normalize_columns(column_names)] + if terminal_supports_colors(): + column_names = [highlight_column_name(n) for n in column_names] + # Convert each row into one or more `name: value' lines (one per column) + # and group each `row of lines' into a block (i.e. rows become blocks). + for row in data: + lines = [] + for column_index, column_text in enumerate(normalize_columns(row)): + stripped_column = column_text.strip() + if '\n' not in stripped_column: + # Columns without line breaks are formatted inline. + lines.append("%s %s" % (column_names[column_index], stripped_column)) + else: + # Columns with line breaks could very well contain indented + # lines, so we'll put the column name on a separate line. This + # way any indentation remains intact, and it's easier to + # copy/paste the text. + lines.append(column_names[column_index]) + lines.extend(column_text.rstrip().splitlines()) + blocks.append(lines) + # Calculate the width of the row delimiter. + num_rows, num_columns = find_terminal_size() + longest_line = max(max(map(ansi_width, lines)) for lines in blocks) + delimiter = u"\n%s\n" % ('-' * min(longest_line, num_columns)) + # Force a delimiter at the start and end of the table. + blocks.insert(0, "") + blocks.append("") + # Embed the row delimiter between every two blocks. + return delimiter.join(u"\n".join(b) for b in blocks).strip() + + +def format_rst_table(data, column_names=None): + """ + Render a table in reStructuredText_ format. + + :param data: An iterable (e.g. a :func:`tuple` or :class:`list`) + containing the rows of the table, where each row is an + iterable containing the columns of the table (strings). + :param column_names: An iterable of column names (strings). + :returns: The rendered table (a string). + + Here's an example: + + >>> from humanfriendly.tables import format_rst_table + >>> column_names = ['Version', 'Uploaded on', 'Downloads'] + >>> humanfriendly_releases = [ + ... ['1.23', '2015-05-25', '218'], + ... ['1.23.1', '2015-05-26', '1354'], + ... ['1.24', '2015-05-26', '223'], + ... ['1.25', '2015-05-26', '4319'], + ... ['1.25.1', '2015-06-02', '197'], + ... ] + >>> print(format_rst_table(humanfriendly_releases, column_names)) + ======= =========== ========= + Version Uploaded on Downloads + ======= =========== ========= + 1.23 2015-05-25 218 + 1.23.1 2015-05-26 1354 + 1.24 2015-05-26 223 + 1.25 2015-05-26 4319 + 1.25.1 2015-06-02 197 + ======= =========== ========= + + .. _reStructuredText: https://en.wikipedia.org/wiki/ReStructuredText + """ + data = [normalize_columns(r) for r in data] + if column_names: + data.insert(0, normalize_columns(column_names)) + # Calculate the maximum width of each column. + widths = collections.defaultdict(int) + for row in data: + for index, column in enumerate(row): + widths[index] = max(widths[index], len(column)) + # Pad the columns using whitespace. + for row in data: + for index, column in enumerate(row): + if index < (len(row) - 1): + row[index] = column.ljust(widths[index]) + # Add table markers. + delimiter = ['=' * w for i, w in sorted(widths.items())] + if column_names: + data.insert(1, delimiter) + data.insert(0, delimiter) + data.append(delimiter) + # Join the lines and columns together. + return '\n'.join(' '.join(r) for r in data) + + +def normalize_columns(row, expandtabs=False): + results = [] + for value in row: + text = coerce_string(value) + if expandtabs: + text = text.expandtabs() + results.append(text) + return results + + +def highlight_column_name(name): + return ansi_wrap(name, bold=True, color=HIGHLIGHT_COLOR) diff --git a/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/terminal/__init__.py b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/terminal/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ba9739ccb22e5708458c453eeb366de77d0e4b4d --- /dev/null +++ b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/terminal/__init__.py @@ -0,0 +1,776 @@ +# Human friendly input/output in Python. +# +# Author: Peter Odding +# Last Change: March 1, 2020 +# URL: https://humanfriendly.readthedocs.io + +""" +Interaction with interactive text terminals. + +The :mod:`~humanfriendly.terminal` module makes it easy to interact with +interactive text terminals and format text for rendering on such terminals. If +the terms used in the documentation of this module don't make sense to you then +please refer to the `Wikipedia article on ANSI escape sequences`_ for details +about how ANSI escape sequences work. + +This module was originally developed for use on UNIX systems, but since then +Windows 10 gained native support for ANSI escape sequences and this module was +enhanced to recognize and support this. For details please refer to the +:func:`enable_ansi_support()` function. + +.. _Wikipedia article on ANSI escape sequences: http://en.wikipedia.org/wiki/ANSI_escape_code#Sequence_elements +""" + +# Standard library modules. +import codecs +import numbers +import os +import platform +import re +import subprocess +import sys + +# The `fcntl' module is platform specific so importing it may give an error. We +# hide this implementation detail from callers by handling the import error and +# setting a flag instead. +try: + import fcntl + import termios + import struct + HAVE_IOCTL = True +except ImportError: + HAVE_IOCTL = False + +# Modules included in our package. +from humanfriendly.compat import coerce_string, is_unicode, on_windows, which +from humanfriendly.decorators import cached +from humanfriendly.deprecation import define_aliases +from humanfriendly.text import concatenate, format +from humanfriendly.usage import format_usage + +# Public identifiers that require documentation. +__all__ = ( + 'ANSI_COLOR_CODES', + 'ANSI_CSI', + 'ANSI_ERASE_LINE', + 'ANSI_HIDE_CURSOR', + 'ANSI_RESET', + 'ANSI_SGR', + 'ANSI_SHOW_CURSOR', + 'ANSI_TEXT_STYLES', + 'CLEAN_OUTPUT_PATTERN', + 'DEFAULT_COLUMNS', + 'DEFAULT_ENCODING', + 'DEFAULT_LINES', + 'HIGHLIGHT_COLOR', + 'ansi_strip', + 'ansi_style', + 'ansi_width', + 'ansi_wrap', + 'auto_encode', + 'clean_terminal_output', + 'connected_to_terminal', + 'enable_ansi_support', + 'find_terminal_size', + 'find_terminal_size_using_ioctl', + 'find_terminal_size_using_stty', + 'get_pager_command', + 'have_windows_native_ansi_support', + 'message', + 'output', + 'readline_strip', + 'readline_wrap', + 'show_pager', + 'terminal_supports_colors', + 'usage', + 'warning', +) + +ANSI_CSI = '\x1b[' +"""The ANSI "Control Sequence Introducer" (a string).""" + +ANSI_SGR = 'm' +"""The ANSI "Select Graphic Rendition" sequence (a string).""" + +ANSI_ERASE_LINE = '%sK' % ANSI_CSI +"""The ANSI escape sequence to erase the current line (a string).""" + +ANSI_RESET = '%s0%s' % (ANSI_CSI, ANSI_SGR) +"""The ANSI escape sequence to reset styling (a string).""" + +ANSI_HIDE_CURSOR = '%s?25l' % ANSI_CSI +"""The ANSI escape sequence to hide the text cursor (a string).""" + +ANSI_SHOW_CURSOR = '%s?25h' % ANSI_CSI +"""The ANSI escape sequence to show the text cursor (a string).""" + +ANSI_COLOR_CODES = dict(black=0, red=1, green=2, yellow=3, blue=4, magenta=5, cyan=6, white=7) +""" +A dictionary with (name, number) pairs of `portable color codes`_. Used by +:func:`ansi_style()` to generate ANSI escape sequences that change font color. + +.. _portable color codes: http://en.wikipedia.org/wiki/ANSI_escape_code#Colors +""" + +ANSI_TEXT_STYLES = dict(bold=1, faint=2, italic=3, underline=4, inverse=7, strike_through=9) +""" +A dictionary with (name, number) pairs of text styles (effects). Used by +:func:`ansi_style()` to generate ANSI escape sequences that change text +styles. Only widely supported text styles are included here. +""" + +CLEAN_OUTPUT_PATTERN = re.compile(u'(\r|\n|\b|%s)' % re.escape(ANSI_ERASE_LINE)) +""" +A compiled regular expression used to separate significant characters from other text. + +This pattern is used by :func:`clean_terminal_output()` to split terminal +output into regular text versus backspace, carriage return and line feed +characters and ANSI 'erase line' escape sequences. +""" + +DEFAULT_LINES = 25 +"""The default number of lines in a terminal (an integer).""" + +DEFAULT_COLUMNS = 80 +"""The default number of columns in a terminal (an integer).""" + +DEFAULT_ENCODING = 'UTF-8' +"""The output encoding for Unicode strings.""" + +HIGHLIGHT_COLOR = os.environ.get('HUMANFRIENDLY_HIGHLIGHT_COLOR', 'green') +""" +The color used to highlight important tokens in formatted text (e.g. the usage +message of the ``humanfriendly`` program). If the environment variable +``$HUMANFRIENDLY_HIGHLIGHT_COLOR`` is set it determines the value of +:data:`HIGHLIGHT_COLOR`. +""" + + +def ansi_strip(text, readline_hints=True): + """ + Strip ANSI escape sequences from the given string. + + :param text: The text from which ANSI escape sequences should be removed (a + string). + :param readline_hints: If :data:`True` then :func:`readline_strip()` is + used to remove `readline hints`_ from the string. + :returns: The text without ANSI escape sequences (a string). + """ + pattern = '%s.*?%s' % (re.escape(ANSI_CSI), re.escape(ANSI_SGR)) + text = re.sub(pattern, '', text) + if readline_hints: + text = readline_strip(text) + return text + + +def ansi_style(**kw): + """ + Generate ANSI escape sequences for the given color and/or style(s). + + :param color: The foreground color. Three types of values are supported: + + - The name of a color (one of the strings 'black', 'red', + 'green', 'yellow', 'blue', 'magenta', 'cyan' or 'white'). + - An integer that refers to the 256 color mode palette. + - A tuple or list with three integers representing an RGB + (red, green, blue) value. + + The value :data:`None` (the default) means no escape + sequence to switch color will be emitted. + :param background: The background color (see the description + of the `color` argument). + :param bright: Use high intensity colors instead of default colors + (a boolean, defaults to :data:`False`). + :param readline_hints: If :data:`True` then :func:`readline_wrap()` is + applied to the generated ANSI escape sequences (the + default is :data:`False`). + :param kw: Any additional keyword arguments are expected to match a key + in the :data:`ANSI_TEXT_STYLES` dictionary. If the argument's + value evaluates to :data:`True` the respective style will be + enabled. + :returns: The ANSI escape sequences to enable the requested text styles or + an empty string if no styles were requested. + :raises: :exc:`~exceptions.ValueError` when an invalid color name is given. + + Even though only eight named colors are supported, the use of `bright=True` + and `faint=True` increases the number of available colors to around 24 (it + may be slightly lower, for example because faint black is just black). + + **Support for 8-bit colors** + + In `release 4.7`_ support for 256 color mode was added. While this + significantly increases the available colors it's not very human friendly + in usage because you need to look up color codes in the `256 color mode + palette `_. + + You can use the ``humanfriendly --demo`` command to get a demonstration of + the available colors, see also the screen shot below. Note that the small + font size in the screen shot was so that the demonstration of 256 color + mode support would fit into a single screen shot without scrolling :-) + (I wasn't feeling very creative). + + .. image:: images/ansi-demo.png + + **Support for 24-bit colors** + + In `release 4.14`_ support for 24-bit colors was added by accepting a tuple + or list with three integers representing the RGB (red, green, blue) value + of a color. This is not included in the demo because rendering millions of + colors was deemed unpractical ;-). + + .. _release 4.7: http://humanfriendly.readthedocs.io/en/latest/changelog.html#release-4-7-2018-01-14 + .. _release 4.14: http://humanfriendly.readthedocs.io/en/latest/changelog.html#release-4-14-2018-07-13 + """ + # Start with sequences that change text styles. + sequences = [ANSI_TEXT_STYLES[k] for k, v in kw.items() if k in ANSI_TEXT_STYLES and v] + # Append the color code (if any). + for color_type in 'color', 'background': + color_value = kw.get(color_type) + if isinstance(color_value, (tuple, list)): + if len(color_value) != 3: + msg = "Invalid color value %r! (expected tuple or list with three numbers)" + raise ValueError(msg % color_value) + sequences.append(48 if color_type == 'background' else 38) + sequences.append(2) + sequences.extend(map(int, color_value)) + elif isinstance(color_value, numbers.Number): + # Numeric values are assumed to be 256 color codes. + sequences.extend(( + 39 if color_type == 'background' else 38, + 5, int(color_value) + )) + elif color_value: + # Other values are assumed to be strings containing one of the known color names. + if color_value not in ANSI_COLOR_CODES: + msg = "Invalid color value %r! (expected an integer or one of the strings %s)" + raise ValueError(msg % (color_value, concatenate(map(repr, sorted(ANSI_COLOR_CODES))))) + # Pick the right offset for foreground versus background + # colors and regular intensity versus bright colors. + offset = ( + (100 if kw.get('bright') else 40) + if color_type == 'background' + else (90 if kw.get('bright') else 30) + ) + # Combine the offset and color code into a single integer. + sequences.append(offset + ANSI_COLOR_CODES[color_value]) + if sequences: + encoded = ANSI_CSI + ';'.join(map(str, sequences)) + ANSI_SGR + return readline_wrap(encoded) if kw.get('readline_hints') else encoded + else: + return '' + + +def ansi_width(text): + """ + Calculate the effective width of the given text (ignoring ANSI escape sequences). + + :param text: The text whose width should be calculated (a string). + :returns: The width of the text without ANSI escape sequences (an + integer). + + This function uses :func:`ansi_strip()` to strip ANSI escape sequences from + the given string and returns the length of the resulting string. + """ + return len(ansi_strip(text)) + + +def ansi_wrap(text, **kw): + """ + Wrap text in ANSI escape sequences for the given color and/or style(s). + + :param text: The text to wrap (a string). + :param kw: Any keyword arguments are passed to :func:`ansi_style()`. + :returns: The result of this function depends on the keyword arguments: + + - If :func:`ansi_style()` generates an ANSI escape sequence based + on the keyword arguments, the given text is prefixed with the + generated ANSI escape sequence and suffixed with + :data:`ANSI_RESET`. + + - If :func:`ansi_style()` returns an empty string then the text + given by the caller is returned unchanged. + """ + start_sequence = ansi_style(**kw) + if start_sequence: + end_sequence = ANSI_RESET + if kw.get('readline_hints'): + end_sequence = readline_wrap(end_sequence) + return start_sequence + text + end_sequence + else: + return text + + +def auto_encode(stream, text, *args, **kw): + """ + Reliably write Unicode strings to the terminal. + + :param stream: The file-like object to write to (a value like + :data:`sys.stdout` or :data:`sys.stderr`). + :param text: The text to write to the stream (a string). + :param args: Refer to :func:`~humanfriendly.text.format()`. + :param kw: Refer to :func:`~humanfriendly.text.format()`. + + Renders the text using :func:`~humanfriendly.text.format()` and writes it + to the given stream. If an :exc:`~exceptions.UnicodeEncodeError` is + encountered in doing so, the text is encoded using :data:`DEFAULT_ENCODING` + and the write is retried. The reasoning behind this rather blunt approach + is that it's preferable to get output on the command line in the wrong + encoding then to have the Python program blow up with a + :exc:`~exceptions.UnicodeEncodeError` exception. + """ + text = format(text, *args, **kw) + try: + stream.write(text) + except UnicodeEncodeError: + stream.write(codecs.encode(text, DEFAULT_ENCODING)) + + +def clean_terminal_output(text): + """ + Clean up the terminal output of a command. + + :param text: The raw text with special characters (a Unicode string). + :returns: A list of Unicode strings (one for each line). + + This function emulates the effect of backspace (0x08), carriage return + (0x0D) and line feed (0x0A) characters and the ANSI 'erase line' escape + sequence on interactive terminals. It's intended to clean up command output + that was originally meant to be rendered on an interactive terminal and + that has been captured using e.g. the :man:`script` program [#]_ or the + :mod:`pty` module [#]_. + + .. [#] My coloredlogs_ package supports the ``coloredlogs --to-html`` + command which uses :man:`script` to fool a subprocess into thinking + that it's connected to an interactive terminal (in order to get it + to emit ANSI escape sequences). + + .. [#] My capturer_ package uses the :mod:`pty` module to fool the current + process and subprocesses into thinking they are connected to an + interactive terminal (in order to get them to emit ANSI escape + sequences). + + **Some caveats about the use of this function:** + + - Strictly speaking the effect of carriage returns cannot be emulated + outside of an actual terminal due to the interaction between overlapping + output, terminal widths and line wrapping. The goal of this function is + to sanitize noise in terminal output while preserving useful output. + Think of it as a useful and pragmatic but possibly lossy conversion. + + - The algorithm isn't smart enough to properly handle a pair of ANSI escape + sequences that open before a carriage return and close after the last + carriage return in a linefeed delimited string; the resulting string will + contain only the closing end of the ANSI escape sequence pair. Tracking + this kind of complexity requires a state machine and proper parsing. + + .. _capturer: https://pypi.org/project/capturer + .. _coloredlogs: https://pypi.org/project/coloredlogs + """ + cleaned_lines = [] + current_line = '' + current_position = 0 + for token in CLEAN_OUTPUT_PATTERN.split(text): + if token == '\r': + # Seek back to the start of the current line. + current_position = 0 + elif token == '\b': + # Seek back one character in the current line. + current_position = max(0, current_position - 1) + else: + if token == '\n': + # Capture the current line. + cleaned_lines.append(current_line) + if token in ('\n', ANSI_ERASE_LINE): + # Clear the current line. + current_line = '' + current_position = 0 + elif token: + # Merge regular output into the current line. + new_position = current_position + len(token) + prefix = current_line[:current_position] + suffix = current_line[new_position:] + current_line = prefix + token + suffix + current_position = new_position + # Capture the last line (if any). + cleaned_lines.append(current_line) + # Remove any empty trailing lines. + while cleaned_lines and not cleaned_lines[-1]: + cleaned_lines.pop(-1) + return cleaned_lines + + +def connected_to_terminal(stream=None): + """ + Check if a stream is connected to a terminal. + + :param stream: The stream to check (a file-like object, + defaults to :data:`sys.stdout`). + :returns: :data:`True` if the stream is connected to a terminal, + :data:`False` otherwise. + + See also :func:`terminal_supports_colors()`. + """ + stream = sys.stdout if stream is None else stream + try: + return stream.isatty() + except Exception: + return False + + +@cached +def enable_ansi_support(): + """ + Try to enable support for ANSI escape sequences (required on Windows). + + :returns: :data:`True` if ANSI is supported, :data:`False` otherwise. + + This functions checks for the following supported configurations, in the + given order: + + 1. On Windows, if :func:`have_windows_native_ansi_support()` confirms + native support for ANSI escape sequences :mod:`ctypes` will be used to + enable this support. + + 2. On Windows, if the environment variable ``$ANSICON`` is set nothing is + done because it is assumed that support for ANSI escape sequences has + already been enabled via `ansicon `_. + + 3. On Windows, an attempt is made to import and initialize the Python + package :pypi:`colorama` instead (of course for this to work + :pypi:`colorama` has to be installed). + + 4. On other platforms this function calls :func:`connected_to_terminal()` + to determine whether ANSI escape sequences are supported (that is to + say all platforms that are not Windows are assumed to support ANSI + escape sequences natively, without weird contortions like above). + + This makes it possible to call :func:`enable_ansi_support()` + unconditionally without checking the current platform. + + The :func:`~humanfriendly.decorators.cached` decorator is used to ensure + that this function is only executed once, but its return value remains + available on later calls. + """ + if have_windows_native_ansi_support(): + import ctypes + ctypes.windll.kernel32.SetConsoleMode(ctypes.windll.kernel32.GetStdHandle(-11), 7) + ctypes.windll.kernel32.SetConsoleMode(ctypes.windll.kernel32.GetStdHandle(-12), 7) + return True + elif on_windows(): + if 'ANSICON' in os.environ: + return True + try: + import colorama + colorama.init() + return True + except ImportError: + return False + else: + return connected_to_terminal() + + +def find_terminal_size(): + """ + Determine the number of lines and columns visible in the terminal. + + :returns: A tuple of two integers with the line and column count. + + The result of this function is based on the first of the following three + methods that works: + + 1. First :func:`find_terminal_size_using_ioctl()` is tried, + 2. then :func:`find_terminal_size_using_stty()` is tried, + 3. finally :data:`DEFAULT_LINES` and :data:`DEFAULT_COLUMNS` are returned. + + .. note:: The :func:`find_terminal_size()` function performs the steps + above every time it is called, the result is not cached. This is + because the size of a virtual terminal can change at any time and + the result of :func:`find_terminal_size()` should be correct. + + `Pre-emptive snarky comment`_: It's possible to cache the result + of this function and use :mod:`signal.SIGWINCH ` to + refresh the cached values! + + Response: As a library I don't consider it the role of the + :mod:`humanfriendly.terminal` module to install a process wide + signal handler ... + + .. _Pre-emptive snarky comment: http://blogs.msdn.com/b/oldnewthing/archive/2008/01/30/7315957.aspx + """ + # The first method. Any of the standard streams may have been redirected + # somewhere and there's no telling which, so we'll just try them all. + for stream in sys.stdin, sys.stdout, sys.stderr: + try: + result = find_terminal_size_using_ioctl(stream) + if min(result) >= 1: + return result + except Exception: + pass + # The second method. + try: + result = find_terminal_size_using_stty() + if min(result) >= 1: + return result + except Exception: + pass + # Fall back to conservative defaults. + return DEFAULT_LINES, DEFAULT_COLUMNS + + +def find_terminal_size_using_ioctl(stream): + """ + Find the terminal size using :func:`fcntl.ioctl()`. + + :param stream: A stream connected to the terminal (a file object with a + ``fileno`` attribute). + :returns: A tuple of two integers with the line and column count. + :raises: This function can raise exceptions but I'm not going to document + them here, you should be using :func:`find_terminal_size()`. + + Based on an `implementation found on StackOverflow `_. + """ + if not HAVE_IOCTL: + raise NotImplementedError("It looks like the `fcntl' module is not available!") + h, w, hp, wp = struct.unpack('HHHH', fcntl.ioctl(stream, termios.TIOCGWINSZ, struct.pack('HHHH', 0, 0, 0, 0))) + return h, w + + +def find_terminal_size_using_stty(): + """ + Find the terminal size using the external command ``stty size``. + + :param stream: A stream connected to the terminal (a file object). + :returns: A tuple of two integers with the line and column count. + :raises: This function can raise exceptions but I'm not going to document + them here, you should be using :func:`find_terminal_size()`. + """ + stty = subprocess.Popen(['stty', 'size'], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + stdout, stderr = stty.communicate() + tokens = stdout.split() + if len(tokens) != 2: + raise Exception("Invalid output from `stty size'!") + return tuple(map(int, tokens)) + + +def get_pager_command(text=None): + """ + Get the command to show a text on the terminal using a pager. + + :param text: The text to print to the terminal (a string). + :returns: A list of strings with the pager command and arguments. + + The use of a pager helps to avoid the wall of text effect where the user + has to scroll up to see where the output began (not very user friendly). + + If the given text contains ANSI escape sequences the command ``less + --RAW-CONTROL-CHARS`` is used, otherwise the environment variable + ``$PAGER`` is used (if ``$PAGER`` isn't set :man:`less` is used). + + When the selected pager is :man:`less`, the following options are used to + make the experience more user friendly: + + - ``--quit-if-one-screen`` causes :man:`less` to automatically exit if the + entire text can be displayed on the first screen. This makes the use of a + pager transparent for smaller texts (because the operator doesn't have to + quit the pager). + + - ``--no-init`` prevents :man:`less` from clearing the screen when it + exits. This ensures that the operator gets a chance to review the text + (for example a usage message) after quitting the pager, while composing + the next command. + """ + # Compose the pager command. + if text and ANSI_CSI in text: + command_line = ['less', '--RAW-CONTROL-CHARS'] + else: + command_line = [os.environ.get('PAGER', 'less')] + # Pass some additional options to `less' (to make it more + # user friendly) without breaking support for other pagers. + if os.path.basename(command_line[0]) == 'less': + command_line.append('--no-init') + command_line.append('--quit-if-one-screen') + return command_line + + +@cached +def have_windows_native_ansi_support(): + """ + Check if we're running on a Windows 10 release with native support for ANSI escape sequences. + + :returns: :data:`True` if so, :data:`False` otherwise. + + The :func:`~humanfriendly.decorators.cached` decorator is used as a minor + performance optimization. Semantically this should have zero impact because + the answer doesn't change in the lifetime of a computer process. + """ + if on_windows(): + try: + # I can't be 100% sure this will never break and I'm not in a + # position to test it thoroughly either, so I decided that paying + # the price of one additional try / except statement is worth the + # additional peace of mind :-). + components = tuple(int(c) for c in platform.version().split('.')) + return components >= (10, 0, 14393) + except Exception: + pass + return False + + +def message(text, *args, **kw): + """ + Print a formatted message to the standard error stream. + + For details about argument handling please refer to + :func:`~humanfriendly.text.format()`. + + Renders the message using :func:`~humanfriendly.text.format()` and writes + the resulting string (followed by a newline) to :data:`sys.stderr` using + :func:`auto_encode()`. + """ + auto_encode(sys.stderr, coerce_string(text) + '\n', *args, **kw) + + +def output(text, *args, **kw): + """ + Print a formatted message to the standard output stream. + + For details about argument handling please refer to + :func:`~humanfriendly.text.format()`. + + Renders the message using :func:`~humanfriendly.text.format()` and writes + the resulting string (followed by a newline) to :data:`sys.stdout` using + :func:`auto_encode()`. + """ + auto_encode(sys.stdout, coerce_string(text) + '\n', *args, **kw) + + +def readline_strip(expr): + """ + Remove `readline hints`_ from a string. + + :param text: The text to strip (a string). + :returns: The stripped text. + """ + return expr.replace('\001', '').replace('\002', '') + + +def readline_wrap(expr): + """ + Wrap an ANSI escape sequence in `readline hints`_. + + :param text: The text with the escape sequence to wrap (a string). + :returns: The wrapped text. + + .. _readline hints: http://superuser.com/a/301355 + """ + return '\001' + expr + '\002' + + +def show_pager(formatted_text, encoding=DEFAULT_ENCODING): + """ + Print a large text to the terminal using a pager. + + :param formatted_text: The text to print to the terminal (a string). + :param encoding: The name of the text encoding used to encode the formatted + text if the formatted text is a Unicode string (a string, + defaults to :data:`DEFAULT_ENCODING`). + + When :func:`connected_to_terminal()` returns :data:`True` a pager is used + to show the text on the terminal, otherwise the text is printed directly + without invoking a pager. + + The use of a pager helps to avoid the wall of text effect where the user + has to scroll up to see where the output began (not very user friendly). + + Refer to :func:`get_pager_command()` for details about the command line + that's used to invoke the pager. + """ + if connected_to_terminal(): + # Make sure the selected pager command is available. + command_line = get_pager_command(formatted_text) + if which(command_line[0]): + pager = subprocess.Popen(command_line, stdin=subprocess.PIPE) + if is_unicode(formatted_text): + formatted_text = formatted_text.encode(encoding) + pager.communicate(input=formatted_text) + return + output(formatted_text) + + +def terminal_supports_colors(stream=None): + """ + Check if a stream is connected to a terminal that supports ANSI escape sequences. + + :param stream: The stream to check (a file-like object, + defaults to :data:`sys.stdout`). + :returns: :data:`True` if the terminal supports ANSI escape sequences, + :data:`False` otherwise. + + This function was originally inspired by the implementation of + `django.core.management.color.supports_color() + `_ + but has since evolved significantly. + """ + if on_windows(): + # On Windows support for ANSI escape sequences is not a given. + have_ansicon = 'ANSICON' in os.environ + have_colorama = 'colorama' in sys.modules + have_native_support = have_windows_native_ansi_support() + if not (have_ansicon or have_colorama or have_native_support): + return False + return connected_to_terminal(stream) + + +def usage(usage_text): + """ + Print a human friendly usage message to the terminal. + + :param text: The usage message to print (a string). + + This function does two things: + + 1. If :data:`sys.stdout` is connected to a terminal (see + :func:`connected_to_terminal()`) then the usage message is formatted + using :func:`.format_usage()`. + 2. The usage message is shown using a pager (see :func:`show_pager()`). + """ + if terminal_supports_colors(sys.stdout): + usage_text = format_usage(usage_text) + show_pager(usage_text) + + +def warning(text, *args, **kw): + """ + Show a warning message on the terminal. + + For details about argument handling please refer to + :func:`~humanfriendly.text.format()`. + + Renders the message using :func:`~humanfriendly.text.format()` and writes + the resulting string (followed by a newline) to :data:`sys.stderr` using + :func:`auto_encode()`. + + If :data:`sys.stderr` is connected to a terminal that supports colors, + :func:`ansi_wrap()` is used to color the message in a red font (to make + the warning stand out from surrounding text). + """ + text = coerce_string(text) + if terminal_supports_colors(sys.stderr): + text = ansi_wrap(text, color='red') + auto_encode(sys.stderr, text + '\n', *args, **kw) + + +# Define aliases for backwards compatibility. +define_aliases( + module_name=__name__, + # In humanfriendly 1.31 the find_meta_variables() and format_usage() + # functions were extracted to the new module humanfriendly.usage. + find_meta_variables='humanfriendly.usage.find_meta_variables', + format_usage='humanfriendly.usage.format_usage', + # In humanfriendly 8.0 the html_to_ansi() function and HTMLConverter + # class were extracted to the new module humanfriendly.terminal.html. + html_to_ansi='humanfriendly.terminal.html.html_to_ansi', + HTMLConverter='humanfriendly.terminal.html.HTMLConverter', +) diff --git a/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/terminal/__pycache__/__init__.cpython-310.pyc b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/terminal/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f03d073b4ba6f2fbf7eeb862b69da374abce02e6 Binary files /dev/null and b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/terminal/__pycache__/__init__.cpython-310.pyc differ diff --git a/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/terminal/__pycache__/html.cpython-310.pyc b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/terminal/__pycache__/html.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2cbf258b865b91eadcd33681172c66db5d558729 Binary files /dev/null and b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/terminal/__pycache__/html.cpython-310.pyc differ diff --git a/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/terminal/__pycache__/spinners.cpython-310.pyc b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/terminal/__pycache__/spinners.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..35240ba5b8087485fdb72a6f4be6180d56123f9e Binary files /dev/null and b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/terminal/__pycache__/spinners.cpython-310.pyc differ diff --git a/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/terminal/html.py b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/terminal/html.py new file mode 100644 index 0000000000000000000000000000000000000000..4214e09e7069a8a3e4a96cdc870c78db91f4fe13 --- /dev/null +++ b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/terminal/html.py @@ -0,0 +1,423 @@ +# Human friendly input/output in Python. +# +# Author: Peter Odding +# Last Change: February 29, 2020 +# URL: https://humanfriendly.readthedocs.io + +"""Convert HTML with simple text formatting to text with ANSI escape sequences.""" + +# Standard library modules. +import re + +# Modules included in our package. +from humanfriendly.compat import HTMLParser, StringIO, name2codepoint, unichr +from humanfriendly.text import compact_empty_lines +from humanfriendly.terminal import ANSI_COLOR_CODES, ANSI_RESET, ansi_style + +# Public identifiers that require documentation. +__all__ = ('HTMLConverter', 'html_to_ansi') + + +def html_to_ansi(data, callback=None): + """ + Convert HTML with simple text formatting to text with ANSI escape sequences. + + :param data: The HTML to convert (a string). + :param callback: Optional callback to pass to :class:`HTMLConverter`. + :returns: Text with ANSI escape sequences (a string). + + Please refer to the documentation of the :class:`HTMLConverter` class for + details about the conversion process (like which tags are supported) and an + example with a screenshot. + """ + converter = HTMLConverter(callback=callback) + return converter(data) + + +class HTMLConverter(HTMLParser): + + """ + Convert HTML with simple text formatting to text with ANSI escape sequences. + + The following text styles are supported: + + - Bold: ````, ```` and ```` + - Italic: ````, ```` and ```` + - Strike-through: ````, ```` and ```` + - Underline: ````, ```` and ```` + + Colors can be specified as follows: + + - Foreground color: ```` + - Background color: ```` + + Here's a small demonstration: + + .. code-block:: python + + from humanfriendly.text import dedent + from humanfriendly.terminal import html_to_ansi + + print(html_to_ansi(dedent(''' + Hello world! + Is this thing on? + I guess I can underline or strike-through text? + And what about color? + '''))) + + rainbow_colors = [ + '#FF0000', '#E2571E', '#FF7F00', '#FFFF00', '#00FF00', + '#96BF33', '#0000FF', '#4B0082', '#8B00FF', '#FFFFFF', + ] + html_rainbow = "".join('o' % c for c in rainbow_colors) + print(html_to_ansi("Let's try a rainbow: %s" % html_rainbow)) + + Here's what the results look like: + + .. image:: images/html-to-ansi.png + + Some more details: + + - Nested tags are supported, within reasonable limits. + + - Text in ```` and ``
`` tags will be highlighted in a
+      different color from the main text (currently this is yellow).
+
+    - ``TEXT`` is converted to the format "TEXT (URL)" where
+      the uppercase symbols are highlighted in light blue with an underline.
+
+    - ``
``, ``

`` and ``

`` tags are considered block level tags
+      and are wrapped in vertical whitespace to prevent their content from
+      "running into" surrounding text. This may cause runs of multiple empty
+      lines to be emitted. As a *workaround* the :func:`__call__()` method
+      will automatically call :func:`.compact_empty_lines()` on the generated
+      output before returning it to the caller. Of course this won't work
+      when `output` is set to something like :data:`sys.stdout`.
+
+    - ``
`` is converted to a single plain text line break. + + Implementation notes: + + - A list of dictionaries with style information is used as a stack where + new styling can be pushed and a pop will restore the previous styling. + When new styling is pushed, it is merged with (but overrides) the current + styling. + + - If you're going to be converting a lot of HTML it might be useful from + a performance standpoint to re-use an existing :class:`HTMLConverter` + object for unrelated HTML fragments, in this case take a look at the + :func:`__call__()` method (it makes this use case very easy). + + .. versionadded:: 4.15 + :class:`humanfriendly.terminal.HTMLConverter` was added to the + `humanfriendly` package during the initial development of my new + `chat-archive `_ project, whose + command line interface makes for a great demonstration of the + flexibility that this feature provides (hint: check out how the search + keyword highlighting combines with the regular highlighting). + """ + + BLOCK_TAGS = ('div', 'p', 'pre') + """The names of tags that are padded with vertical whitespace.""" + + def __init__(self, *args, **kw): + """ + Initialize an :class:`HTMLConverter` object. + + :param callback: Optional keyword argument to specify a function that + will be called to process text fragments before they + are emitted on the output stream. Note that link text + and preformatted text fragments are not processed by + this callback. + :param output: Optional keyword argument to redirect the output to the + given file-like object. If this is not given a new + :class:`~python3:io.StringIO` object is created. + """ + # Hide our optional keyword arguments from the superclass. + self.callback = kw.pop("callback", None) + self.output = kw.pop("output", None) + # Initialize the superclass. + HTMLParser.__init__(self, *args, **kw) + + def __call__(self, data): + """ + Reset the parser, convert some HTML and get the text with ANSI escape sequences. + + :param data: The HTML to convert to text (a string). + :returns: The converted text (only in case `output` is + a :class:`~python3:io.StringIO` object). + """ + self.reset() + self.feed(data) + self.close() + if isinstance(self.output, StringIO): + return compact_empty_lines(self.output.getvalue()) + + @property + def current_style(self): + """Get the current style from the top of the stack (a dictionary).""" + return self.stack[-1] if self.stack else {} + + def close(self): + """ + Close previously opened ANSI escape sequences. + + This method overrides the same method in the superclass to ensure that + an :data:`.ANSI_RESET` code is emitted when parsing reaches the end of + the input but a style is still active. This is intended to prevent + malformed HTML from messing up terminal output. + """ + if any(self.stack): + self.output.write(ANSI_RESET) + self.stack = [] + HTMLParser.close(self) + + def emit_style(self, style=None): + """ + Emit an ANSI escape sequence for the given or current style to the output stream. + + :param style: A dictionary with arguments for :func:`.ansi_style()` or + :data:`None`, in which case the style at the top of the + stack is emitted. + """ + # Clear the current text styles. + self.output.write(ANSI_RESET) + # Apply a new text style? + style = self.current_style if style is None else style + if style: + self.output.write(ansi_style(**style)) + + def handle_charref(self, value): + """ + Process a decimal or hexadecimal numeric character reference. + + :param value: The decimal or hexadecimal value (a string). + """ + self.output.write(unichr(int(value[1:], 16) if value.startswith('x') else int(value))) + + def handle_data(self, data): + """ + Process textual data. + + :param data: The decoded text (a string). + """ + if self.link_url: + # Link text is captured literally so that we can reliably check + # whether the text and the URL of the link are the same string. + self.link_text = data + elif self.callback and self.preformatted_text_level == 0: + # Text that is not part of a link and not preformatted text is + # passed to the user defined callback to allow for arbitrary + # pre-processing. + data = self.callback(data) + # All text is emitted unmodified on the output stream. + self.output.write(data) + + def handle_endtag(self, tag): + """ + Process the end of an HTML tag. + + :param tag: The name of the tag (a string). + """ + if tag in ('a', 'b', 'code', 'del', 'em', 'i', 'ins', 'pre', 's', 'strong', 'span', 'u'): + old_style = self.current_style + # The following conditional isn't necessary for well formed + # HTML but prevents raising exceptions on malformed HTML. + if self.stack: + self.stack.pop(-1) + new_style = self.current_style + if tag == 'a': + if self.urls_match(self.link_text, self.link_url): + # Don't render the URL when it's part of the link text. + self.emit_style(new_style) + else: + self.emit_style(new_style) + self.output.write(' (') + self.emit_style(old_style) + self.output.write(self.render_url(self.link_url)) + self.emit_style(new_style) + self.output.write(')') + else: + self.emit_style(new_style) + if tag in ('code', 'pre'): + self.preformatted_text_level -= 1 + if tag in self.BLOCK_TAGS: + # Emit an empty line after block level tags. + self.output.write('\n\n') + + def handle_entityref(self, name): + """ + Process a named character reference. + + :param name: The name of the character reference (a string). + """ + self.output.write(unichr(name2codepoint[name])) + + def handle_starttag(self, tag, attrs): + """ + Process the start of an HTML tag. + + :param tag: The name of the tag (a string). + :param attrs: A list of tuples with two strings each. + """ + if tag in self.BLOCK_TAGS: + # Emit an empty line before block level tags. + self.output.write('\n\n') + if tag == 'a': + self.push_styles(color='blue', bright=True, underline=True) + # Store the URL that the link points to for later use, so that we + # can render the link text before the URL (with the reasoning that + # this is the most intuitive way to present a link in a plain text + # interface). + self.link_url = next((v for n, v in attrs if n == 'href'), '') + elif tag == 'b' or tag == 'strong': + self.push_styles(bold=True) + elif tag == 'br': + self.output.write('\n') + elif tag == 'code' or tag == 'pre': + self.push_styles(color='yellow') + self.preformatted_text_level += 1 + elif tag == 'del' or tag == 's': + self.push_styles(strike_through=True) + elif tag == 'em' or tag == 'i': + self.push_styles(italic=True) + elif tag == 'ins' or tag == 'u': + self.push_styles(underline=True) + elif tag == 'span': + styles = {} + css = next((v for n, v in attrs if n == 'style'), "") + for rule in css.split(';'): + name, _, value = rule.partition(':') + name = name.strip() + value = value.strip() + if name == 'background-color': + styles['background'] = self.parse_color(value) + elif name == 'color': + styles['color'] = self.parse_color(value) + elif name == 'font-style' and value == 'italic': + styles['italic'] = True + elif name == 'font-weight' and value == 'bold': + styles['bold'] = True + elif name == 'text-decoration' and value == 'line-through': + styles['strike_through'] = True + elif name == 'text-decoration' and value == 'underline': + styles['underline'] = True + self.push_styles(**styles) + + def normalize_url(self, url): + """ + Normalize a URL to enable string equality comparison. + + :param url: The URL to normalize (a string). + :returns: The normalized URL (a string). + """ + return re.sub('^mailto:', '', url) + + def parse_color(self, value): + """ + Convert a CSS color to something that :func:`.ansi_style()` understands. + + :param value: A string like ``rgb(1,2,3)``, ``#AABBCC`` or ``yellow``. + :returns: A color value supported by :func:`.ansi_style()` or :data:`None`. + """ + # Parse an 'rgb(N,N,N)' expression. + if value.startswith('rgb'): + tokens = re.findall(r'\d+', value) + if len(tokens) == 3: + return tuple(map(int, tokens)) + # Parse an '#XXXXXX' expression. + elif value.startswith('#'): + value = value[1:] + length = len(value) + if length == 6: + # Six hex digits (proper notation). + return ( + int(value[:2], 16), + int(value[2:4], 16), + int(value[4:6], 16), + ) + elif length == 3: + # Three hex digits (shorthand). + return ( + int(value[0], 16), + int(value[1], 16), + int(value[2], 16), + ) + # Try to recognize a named color. + value = value.lower() + if value in ANSI_COLOR_CODES: + return value + + def push_styles(self, **changes): + """ + Push new style information onto the stack. + + :param changes: Any keyword arguments are passed on to :func:`.ansi_style()`. + + This method is a helper for :func:`handle_starttag()` + that does the following: + + 1. Make a copy of the current styles (from the top of the stack), + 2. Apply the given `changes` to the copy of the current styles, + 3. Add the new styles to the stack, + 4. Emit the appropriate ANSI escape sequence to the output stream. + """ + prototype = self.current_style + if prototype: + new_style = dict(prototype) + new_style.update(changes) + else: + new_style = changes + self.stack.append(new_style) + self.emit_style(new_style) + + def render_url(self, url): + """ + Prepare a URL for rendering on the terminal. + + :param url: The URL to simplify (a string). + :returns: The simplified URL (a string). + + This method pre-processes a URL before rendering on the terminal. The + following modifications are made: + + - The ``mailto:`` prefix is stripped. + - Spaces are converted to ``%20``. + - A trailing parenthesis is converted to ``%29``. + """ + url = re.sub('^mailto:', '', url) + url = re.sub(' ', '%20', url) + url = re.sub(r'\)$', '%29', url) + return url + + def reset(self): + """ + Reset the state of the HTML parser and ANSI converter. + + When `output` is a :class:`~python3:io.StringIO` object a new + instance will be created (and the old one garbage collected). + """ + # Reset the state of the superclass. + HTMLParser.reset(self) + # Reset our instance variables. + self.link_text = None + self.link_url = None + self.preformatted_text_level = 0 + if self.output is None or isinstance(self.output, StringIO): + # If the caller specified something like output=sys.stdout then it + # doesn't make much sense to negate that choice here in reset(). + self.output = StringIO() + self.stack = [] + + def urls_match(self, a, b): + """ + Compare two URLs for equality using :func:`normalize_url()`. + + :param a: A string containing a URL. + :param b: A string containing a URL. + :returns: :data:`True` if the URLs are the same, :data:`False` otherwise. + + This method is used by :func:`handle_endtag()` to omit the URL of a + hyperlink (````) when the link text is that same URL. + """ + return self.normalize_url(a) == self.normalize_url(b) diff --git a/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/terminal/spinners.py b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/terminal/spinners.py new file mode 100644 index 0000000000000000000000000000000000000000..e4dc55d3026790bf0b5e3e5f48f88373868804b5 --- /dev/null +++ b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/terminal/spinners.py @@ -0,0 +1,310 @@ +# Human friendly input/output in Python. +# +# Author: Peter Odding +# Last Change: March 1, 2020 +# URL: https://humanfriendly.readthedocs.io + +""" +Support for spinners that represent progress on interactive terminals. + +The :class:`Spinner` class shows a "spinner" on the terminal to let the user +know that something is happening during long running operations that would +otherwise be silent (leaving the user to wonder what they're waiting for). +Below are some visual examples that should illustrate the point. + +**Simple spinners:** + + Here's a screen capture that shows the simplest form of spinner: + + .. image:: images/spinner-basic.gif + :alt: Animated screen capture of a simple spinner. + + The following code was used to create the spinner above: + + .. code-block:: python + + import itertools + import time + from humanfriendly import Spinner + + with Spinner(label="Downloading") as spinner: + for i in itertools.count(): + # Do something useful here. + time.sleep(0.1) + # Advance the spinner. + spinner.step() + +**Spinners that show elapsed time:** + + Here's a spinner that shows the elapsed time since it started: + + .. image:: images/spinner-with-timer.gif + :alt: Animated screen capture of a spinner showing elapsed time. + + The following code was used to create the spinner above: + + .. code-block:: python + + import itertools + import time + from humanfriendly import Spinner, Timer + + with Spinner(label="Downloading", timer=Timer()) as spinner: + for i in itertools.count(): + # Do something useful here. + time.sleep(0.1) + # Advance the spinner. + spinner.step() + +**Spinners that show progress:** + + Here's a spinner that shows a progress percentage: + + .. image:: images/spinner-with-progress.gif + :alt: Animated screen capture of spinner showing progress. + + The following code was used to create the spinner above: + + .. code-block:: python + + import itertools + import random + import time + from humanfriendly import Spinner, Timer + + with Spinner(label="Downloading", total=100) as spinner: + progress = 0 + while progress < 100: + # Do something useful here. + time.sleep(0.1) + # Advance the spinner. + spinner.step(progress) + # Determine the new progress value. + progress += random.random() * 5 + +If you want to provide user feedback during a long running operation but it's +not practical to periodically call the :func:`~Spinner.step()` method consider +using :class:`AutomaticSpinner` instead. + +As you may already have noticed in the examples above, :class:`Spinner` objects +can be used as context managers to automatically call :func:`Spinner.clear()` +when the spinner ends. +""" + +# Standard library modules. +import multiprocessing +import sys +import time + +# Modules included in our package. +from humanfriendly import Timer +from humanfriendly.deprecation import deprecated_args +from humanfriendly.terminal import ANSI_ERASE_LINE + +# Public identifiers that require documentation. +__all__ = ("AutomaticSpinner", "GLYPHS", "MINIMUM_INTERVAL", "Spinner") + +GLYPHS = ["-", "\\", "|", "/"] +"""A list of strings with characters that together form a crude animation :-).""" + +MINIMUM_INTERVAL = 0.2 +"""Spinners are redrawn with a frequency no higher than this number (a floating point number of seconds).""" + + +class Spinner(object): + + """Show a spinner on the terminal as a simple means of feedback to the user.""" + + @deprecated_args('label', 'total', 'stream', 'interactive', 'timer') + def __init__(self, **options): + """ + Initialize a :class:`Spinner` object. + + :param label: + + The label for the spinner (a string or :data:`None`, defaults to + :data:`None`). + + :param total: + + The expected number of steps (an integer or :data:`None`). If this is + provided the spinner will show a progress percentage. + + :param stream: + + The output stream to show the spinner on (a file-like object, + defaults to :data:`sys.stderr`). + + :param interactive: + + :data:`True` to enable rendering of the spinner, :data:`False` to + disable (defaults to the result of ``stream.isatty()``). + + :param timer: + + A :class:`.Timer` object (optional). If this is given the spinner + will show the elapsed time according to the timer. + + :param interval: + + The spinner will be updated at most once every this many seconds + (a floating point number, defaults to :data:`MINIMUM_INTERVAL`). + + :param glyphs: + + A list of strings with single characters that are drawn in the same + place in succession to implement a simple animated effect (defaults + to :data:`GLYPHS`). + """ + # Store initializer arguments. + self.interactive = options.get('interactive') + self.interval = options.get('interval', MINIMUM_INTERVAL) + self.label = options.get('label') + self.states = options.get('glyphs', GLYPHS) + self.stream = options.get('stream', sys.stderr) + self.timer = options.get('timer') + self.total = options.get('total') + # Define instance variables. + self.counter = 0 + self.last_update = 0 + # Try to automatically discover whether the stream is connected to + # a terminal, but don't fail if no isatty() method is available. + if self.interactive is None: + try: + self.interactive = self.stream.isatty() + except Exception: + self.interactive = False + + def step(self, progress=0, label=None): + """ + Advance the spinner by one step and redraw it. + + :param progress: The number of the current step, relative to the total + given to the :class:`Spinner` constructor (an integer, + optional). If not provided the spinner will not show + progress. + :param label: The label to use while redrawing (a string, optional). If + not provided the label given to the :class:`Spinner` + constructor is used instead. + + This method advances the spinner by one step without starting a new + line, causing an animated effect which is very simple but much nicer + than waiting for a prompt which is completely silent for a long time. + + .. note:: This method uses time based rate limiting to avoid redrawing + the spinner too frequently. If you know you're dealing with + code that will call :func:`step()` at a high frequency, + consider using :func:`sleep()` to avoid creating the + equivalent of a busy loop that's rate limiting the spinner + 99% of the time. + """ + if self.interactive: + time_now = time.time() + if time_now - self.last_update >= self.interval: + self.last_update = time_now + state = self.states[self.counter % len(self.states)] + label = label or self.label + if not label: + raise Exception("No label set for spinner!") + elif self.total and progress: + label = "%s: %.2f%%" % (label, progress / (self.total / 100.0)) + elif self.timer and self.timer.elapsed_time > 2: + label = "%s (%s)" % (label, self.timer.rounded) + self.stream.write("%s %s %s ..\r" % (ANSI_ERASE_LINE, state, label)) + self.counter += 1 + + def sleep(self): + """ + Sleep for a short period before redrawing the spinner. + + This method is useful when you know you're dealing with code that will + call :func:`step()` at a high frequency. It will sleep for the interval + with which the spinner is redrawn (less than a second). This avoids + creating the equivalent of a busy loop that's rate limiting the + spinner 99% of the time. + + This method doesn't redraw the spinner, you still have to call + :func:`step()` in order to do that. + """ + time.sleep(MINIMUM_INTERVAL) + + def clear(self): + """ + Clear the spinner. + + The next line which is shown on the standard output or error stream + after calling this method will overwrite the line that used to show the + spinner. + """ + if self.interactive: + self.stream.write(ANSI_ERASE_LINE) + + def __enter__(self): + """ + Enable the use of spinners as context managers. + + :returns: The :class:`Spinner` object. + """ + return self + + def __exit__(self, exc_type=None, exc_value=None, traceback=None): + """Clear the spinner when leaving the context.""" + self.clear() + + +class AutomaticSpinner(object): + + """ + Show a spinner on the terminal that automatically starts animating. + + This class shows a spinner on the terminal (just like :class:`Spinner` + does) that automatically starts animating. This class should be used as a + context manager using the :keyword:`with` statement. The animation + continues for as long as the context is active. + + :class:`AutomaticSpinner` provides an alternative to :class:`Spinner` + for situations where it is not practical for the caller to periodically + call :func:`~Spinner.step()` to advance the animation, e.g. because + you're performing a blocking call and don't fancy implementing threading or + subprocess handling just to provide some user feedback. + + This works using the :mod:`multiprocessing` module by spawning a + subprocess to render the spinner while the main process is busy doing + something more useful. By using the :keyword:`with` statement you're + guaranteed that the subprocess is properly terminated at the appropriate + time. + """ + + def __init__(self, label, show_time=True): + """ + Initialize an automatic spinner. + + :param label: The label for the spinner (a string). + :param show_time: If this is :data:`True` (the default) then the spinner + shows elapsed time. + """ + self.label = label + self.show_time = show_time + self.shutdown_event = multiprocessing.Event() + self.subprocess = multiprocessing.Process(target=self._target) + + def __enter__(self): + """Enable the use of automatic spinners as context managers.""" + self.subprocess.start() + + def __exit__(self, exc_type=None, exc_value=None, traceback=None): + """Enable the use of automatic spinners as context managers.""" + self.shutdown_event.set() + self.subprocess.join() + + def _target(self): + try: + timer = Timer() if self.show_time else None + with Spinner(label=self.label, timer=timer) as spinner: + while not self.shutdown_event.is_set(): + spinner.step() + spinner.sleep() + except KeyboardInterrupt: + # Swallow Control-C signals without producing a nasty traceback that + # won't make any sense to the average user. + pass diff --git a/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/testing.py b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/testing.py new file mode 100644 index 0000000000000000000000000000000000000000..f6abddf07423faacdef2059601a9d52155c498e5 --- /dev/null +++ b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/testing.py @@ -0,0 +1,669 @@ +# Human friendly input/output in Python. +# +# Author: Peter Odding +# Last Change: March 6, 2020 +# URL: https://humanfriendly.readthedocs.io + +""" +Utility classes and functions that make it easy to write :mod:`unittest` compatible test suites. + +Over the years I've developed the habit of writing test suites for Python +projects using the :mod:`unittest` module. During those years I've come to know +:pypi:`pytest` and in fact I use :pypi:`pytest` to run my test suites (due to +its much better error reporting) but I've yet to publish a test suite that +*requires* :pypi:`pytest`. I have several reasons for doing so: + +- It's nice to keep my test suites as simple and accessible as possible and + not requiring a specific test runner is part of that attitude. + +- Whereas :mod:`unittest` is quite explicit, :pypi:`pytest` contains a lot of + magic, which kind of contradicts the Python mantra "explicit is better than + implicit" (IMHO). +""" + +# Standard library module +import functools +import logging +import os +import pipes +import shutil +import sys +import tempfile +import time +import unittest + +# Modules included in our package. +from humanfriendly.compat import StringIO +from humanfriendly.text import random_string + +# Initialize a logger for this module. +logger = logging.getLogger(__name__) + +# A unique object reference used to detect missing attributes. +NOTHING = object() + +# Public identifiers that require documentation. +__all__ = ( + 'CallableTimedOut', + 'CaptureBuffer', + 'CaptureOutput', + 'ContextManager', + 'CustomSearchPath', + 'MockedProgram', + 'PatchedAttribute', + 'PatchedItem', + 'TemporaryDirectory', + 'TestCase', + 'configure_logging', + 'make_dirs', + 'retry', + 'run_cli', + 'skip_on_raise', + 'touch', +) + + +def configure_logging(log_level=logging.DEBUG): + """configure_logging(log_level=logging.DEBUG) + Automatically configure logging to the terminal. + + :param log_level: The log verbosity (a number, defaults + to :mod:`logging.DEBUG `). + + When :mod:`coloredlogs` is installed :func:`coloredlogs.install()` will be + used to configure logging to the terminal. When this fails with an + :exc:`~exceptions.ImportError` then :func:`logging.basicConfig()` is used + as a fall back. + """ + try: + import coloredlogs + coloredlogs.install(level=log_level) + except ImportError: + logging.basicConfig( + level=log_level, + format='%(asctime)s %(name)s[%(process)d] %(levelname)s %(message)s', + datefmt='%Y-%m-%d %H:%M:%S') + + +def make_dirs(pathname): + """ + Create missing directories. + + :param pathname: The pathname of a directory (a string). + """ + if not os.path.isdir(pathname): + os.makedirs(pathname) + + +def retry(func, timeout=60, exc_type=AssertionError): + """retry(func, timeout=60, exc_type=AssertionError) + Retry a function until assertions no longer fail. + + :param func: A callable. When the callable returns + :data:`False` it will also be retried. + :param timeout: The number of seconds after which to abort (a number, + defaults to 60). + :param exc_type: The type of exceptions to retry (defaults + to :exc:`~exceptions.AssertionError`). + :returns: The value returned by `func`. + :raises: Once the timeout has expired :func:`retry()` will raise the + previously retried assertion error. When `func` keeps returning + :data:`False` until `timeout` expires :exc:`CallableTimedOut` + will be raised. + + This function sleeps between retries to avoid claiming CPU cycles we don't + need. It starts by sleeping for 0.1 second but adjusts this to one second + as the number of retries grows. + """ + pause = 0.1 + timeout += time.time() + while True: + try: + result = func() + if result is not False: + return result + except exc_type: + if time.time() > timeout: + raise + else: + if time.time() > timeout: + raise CallableTimedOut() + time.sleep(pause) + if pause < 1: + pause *= 2 + + +def run_cli(entry_point, *arguments, **options): + """ + Test a command line entry point. + + :param entry_point: The function that implements the command line interface + (a callable). + :param arguments: Any positional arguments (strings) become the command + line arguments (:data:`sys.argv` items 1-N). + :param options: The following keyword arguments are supported: + + **capture** + Whether to use :class:`CaptureOutput`. Defaults + to :data:`True` but can be disabled by passing + :data:`False` instead. + **input** + Refer to :class:`CaptureOutput`. + **merged** + Refer to :class:`CaptureOutput`. + **program_name** + Used to set :data:`sys.argv` item 0. + :returns: A tuple with two values: + + 1. The return code (an integer). + 2. The captured output (a string). + """ + # Add the `program_name' option to the arguments. + arguments = list(arguments) + arguments.insert(0, options.pop('program_name', sys.executable)) + # Log the command line arguments (and the fact that we're about to call the + # command line entry point function). + logger.debug("Calling command line entry point with arguments: %s", arguments) + # Prepare to capture the return code and output even if the command line + # interface raises an exception (whether the exception type is SystemExit + # or something else). + returncode = 0 + stdout = None + stderr = None + try: + # Temporarily override sys.argv. + with PatchedAttribute(sys, 'argv', arguments): + # Manipulate the standard input/output/error streams? + options['enabled'] = options.pop('capture', True) + with CaptureOutput(**options) as capturer: + try: + # Call the command line interface. + entry_point() + finally: + # Get the output even if an exception is raised. + stdout = capturer.stdout.getvalue() + stderr = capturer.stderr.getvalue() + # Reconfigure logging to the terminal because it is very + # likely that the entry point function has changed the + # configured log level. + configure_logging() + except BaseException as e: + if isinstance(e, SystemExit): + logger.debug("Intercepting return code %s from SystemExit exception.", e.code) + returncode = e.code + else: + logger.warning("Defaulting return code to 1 due to raised exception.", exc_info=True) + returncode = 1 + else: + logger.debug("Command line entry point returned successfully!") + # Always log the output captured on stdout/stderr, to make it easier to + # diagnose test failures (but avoid duplicate logging when merged=True). + is_merged = options.get('merged', False) + merged_streams = [('merged streams', stdout)] + separate_streams = [('stdout', stdout), ('stderr', stderr)] + streams = merged_streams if is_merged else separate_streams + for name, value in streams: + if value: + logger.debug("Output on %s:\n%s", name, value) + else: + logger.debug("No output on %s.", name) + return returncode, stdout + + +def skip_on_raise(*exc_types): + """ + Decorate a test function to translation specific exception types to :exc:`unittest.SkipTest`. + + :param exc_types: One or more positional arguments give the exception + types to be translated to :exc:`unittest.SkipTest`. + :returns: A decorator function specialized to `exc_types`. + """ + def decorator(function): + @functools.wraps(function) + def wrapper(*args, **kw): + try: + return function(*args, **kw) + except exc_types as e: + logger.debug("Translating exception to unittest.SkipTest ..", exc_info=True) + raise unittest.SkipTest("skipping test because %s was raised" % type(e)) + return wrapper + return decorator + + +def touch(filename): + """ + The equivalent of the UNIX :man:`touch` program in Python. + + :param filename: The pathname of the file to touch (a string). + + Note that missing directories are automatically created using + :func:`make_dirs()`. + """ + make_dirs(os.path.dirname(filename)) + with open(filename, 'a'): + os.utime(filename, None) + + +class CallableTimedOut(Exception): + + """Raised by :func:`retry()` when the timeout expires.""" + + +class ContextManager(object): + + """Base class to enable composition of context managers.""" + + def __enter__(self): + """Enable use as context managers.""" + return self + + def __exit__(self, exc_type=None, exc_value=None, traceback=None): + """Enable use as context managers.""" + + +class PatchedAttribute(ContextManager): + + """Context manager that temporary replaces an object attribute using :func:`setattr()`.""" + + def __init__(self, obj, name, value): + """ + Initialize a :class:`PatchedAttribute` object. + + :param obj: The object to patch. + :param name: An attribute name. + :param value: The value to set. + """ + self.object_to_patch = obj + self.attribute_to_patch = name + self.patched_value = value + self.original_value = NOTHING + + def __enter__(self): + """ + Replace (patch) the attribute. + + :returns: The object whose attribute was patched. + """ + # Enable composition of context managers. + super(PatchedAttribute, self).__enter__() + # Patch the object's attribute. + self.original_value = getattr(self.object_to_patch, self.attribute_to_patch, NOTHING) + setattr(self.object_to_patch, self.attribute_to_patch, self.patched_value) + return self.object_to_patch + + def __exit__(self, exc_type=None, exc_value=None, traceback=None): + """Restore the attribute to its original value.""" + # Enable composition of context managers. + super(PatchedAttribute, self).__exit__(exc_type, exc_value, traceback) + # Restore the object's attribute. + if self.original_value is NOTHING: + delattr(self.object_to_patch, self.attribute_to_patch) + else: + setattr(self.object_to_patch, self.attribute_to_patch, self.original_value) + + +class PatchedItem(ContextManager): + + """Context manager that temporary replaces an object item using :meth:`~object.__setitem__()`.""" + + def __init__(self, obj, item, value): + """ + Initialize a :class:`PatchedItem` object. + + :param obj: The object to patch. + :param item: The item to patch. + :param value: The value to set. + """ + self.object_to_patch = obj + self.item_to_patch = item + self.patched_value = value + self.original_value = NOTHING + + def __enter__(self): + """ + Replace (patch) the item. + + :returns: The object whose item was patched. + """ + # Enable composition of context managers. + super(PatchedItem, self).__enter__() + # Patch the object's item. + try: + self.original_value = self.object_to_patch[self.item_to_patch] + except KeyError: + self.original_value = NOTHING + self.object_to_patch[self.item_to_patch] = self.patched_value + return self.object_to_patch + + def __exit__(self, exc_type=None, exc_value=None, traceback=None): + """Restore the item to its original value.""" + # Enable composition of context managers. + super(PatchedItem, self).__exit__(exc_type, exc_value, traceback) + # Restore the object's item. + if self.original_value is NOTHING: + del self.object_to_patch[self.item_to_patch] + else: + self.object_to_patch[self.item_to_patch] = self.original_value + + +class TemporaryDirectory(ContextManager): + + """ + Easy temporary directory creation & cleanup using the :keyword:`with` statement. + + Here's an example of how to use this: + + .. code-block:: python + + with TemporaryDirectory() as directory: + # Do something useful here. + assert os.path.isdir(directory) + """ + + def __init__(self, **options): + """ + Initialize a :class:`TemporaryDirectory` object. + + :param options: Any keyword arguments are passed on to + :func:`tempfile.mkdtemp()`. + """ + self.mkdtemp_options = options + self.temporary_directory = None + + def __enter__(self): + """ + Create the temporary directory using :func:`tempfile.mkdtemp()`. + + :returns: The pathname of the directory (a string). + """ + # Enable composition of context managers. + super(TemporaryDirectory, self).__enter__() + # Create the temporary directory. + self.temporary_directory = tempfile.mkdtemp(**self.mkdtemp_options) + return self.temporary_directory + + def __exit__(self, exc_type=None, exc_value=None, traceback=None): + """Cleanup the temporary directory using :func:`shutil.rmtree()`.""" + # Enable composition of context managers. + super(TemporaryDirectory, self).__exit__(exc_type, exc_value, traceback) + # Cleanup the temporary directory. + if self.temporary_directory is not None: + shutil.rmtree(self.temporary_directory) + self.temporary_directory = None + + +class MockedHomeDirectory(PatchedItem, TemporaryDirectory): + + """ + Context manager to temporarily change ``$HOME`` (the current user's profile directory). + + This class is a composition of the :class:`PatchedItem` and + :class:`TemporaryDirectory` context managers. + """ + + def __init__(self): + """Initialize a :class:`MockedHomeDirectory` object.""" + PatchedItem.__init__(self, os.environ, 'HOME', os.environ.get('HOME')) + TemporaryDirectory.__init__(self) + + def __enter__(self): + """ + Activate the custom ``$PATH``. + + :returns: The pathname of the directory that has + been added to ``$PATH`` (a string). + """ + # Get the temporary directory. + directory = TemporaryDirectory.__enter__(self) + # Override the value to patch now that we have + # the pathname of the temporary directory. + self.patched_value = directory + # Temporary patch $HOME. + PatchedItem.__enter__(self) + # Pass the pathname of the temporary directory to the caller. + return directory + + def __exit__(self, exc_type=None, exc_value=None, traceback=None): + """Deactivate the custom ``$HOME``.""" + super(MockedHomeDirectory, self).__exit__(exc_type, exc_value, traceback) + + +class CustomSearchPath(PatchedItem, TemporaryDirectory): + + """ + Context manager to temporarily customize ``$PATH`` (the executable search path). + + This class is a composition of the :class:`PatchedItem` and + :class:`TemporaryDirectory` context managers. + """ + + def __init__(self, isolated=False): + """ + Initialize a :class:`CustomSearchPath` object. + + :param isolated: :data:`True` to clear the original search path, + :data:`False` to add the temporary directory to the + start of the search path. + """ + # Initialize our own instance variables. + self.isolated_search_path = isolated + # Selectively initialize our superclasses. + PatchedItem.__init__(self, os.environ, 'PATH', self.current_search_path) + TemporaryDirectory.__init__(self) + + def __enter__(self): + """ + Activate the custom ``$PATH``. + + :returns: The pathname of the directory that has + been added to ``$PATH`` (a string). + """ + # Get the temporary directory. + directory = TemporaryDirectory.__enter__(self) + # Override the value to patch now that we have + # the pathname of the temporary directory. + self.patched_value = ( + directory if self.isolated_search_path + else os.pathsep.join([directory] + self.current_search_path.split(os.pathsep)) + ) + # Temporary patch the $PATH. + PatchedItem.__enter__(self) + # Pass the pathname of the temporary directory to the caller + # because they may want to `install' custom executables. + return directory + + def __exit__(self, exc_type=None, exc_value=None, traceback=None): + """Deactivate the custom ``$PATH``.""" + super(CustomSearchPath, self).__exit__(exc_type, exc_value, traceback) + + @property + def current_search_path(self): + """The value of ``$PATH`` or :data:`os.defpath` (a string).""" + return os.environ.get('PATH', os.defpath) + + +class MockedProgram(CustomSearchPath): + + """ + Context manager to mock the existence of a program (executable). + + This class extends the functionality of :class:`CustomSearchPath`. + """ + + def __init__(self, name, returncode=0, script=None): + """ + Initialize a :class:`MockedProgram` object. + + :param name: The name of the program (a string). + :param returncode: The return code that the program should emit (a + number, defaults to zero). + :param script: Shell script code to include in the mocked program (a + string or :data:`None`). This can be used to mock a + program that is expected to generate specific output. + """ + # Initialize our own instance variables. + self.program_name = name + self.program_returncode = returncode + self.program_script = script + self.program_signal_file = None + # Initialize our superclasses. + super(MockedProgram, self).__init__() + + def __enter__(self): + """ + Create the mock program. + + :returns: The pathname of the directory that has + been added to ``$PATH`` (a string). + """ + directory = super(MockedProgram, self).__enter__() + self.program_signal_file = os.path.join(directory, 'program-was-run-%s' % random_string(10)) + pathname = os.path.join(directory, self.program_name) + with open(pathname, 'w') as handle: + handle.write('#!/bin/sh\n') + handle.write('echo > %s\n' % pipes.quote(self.program_signal_file)) + if self.program_script: + handle.write('%s\n' % self.program_script.strip()) + handle.write('exit %i\n' % self.program_returncode) + os.chmod(pathname, 0o755) + return directory + + def __exit__(self, *args, **kw): + """ + Ensure that the mock program was run. + + :raises: :exc:`~exceptions.AssertionError` when + the mock program hasn't been run. + """ + try: + assert self.program_signal_file and os.path.isfile(self.program_signal_file), \ + ("It looks like %r was never run!" % self.program_name) + finally: + return super(MockedProgram, self).__exit__(*args, **kw) + + +class CaptureOutput(ContextManager): + + """ + Context manager that captures what's written to :data:`sys.stdout` and :data:`sys.stderr`. + + .. attribute:: stdin + + The :class:`~humanfriendly.compat.StringIO` object used to feed the standard input stream. + + .. attribute:: stdout + + The :class:`CaptureBuffer` object used to capture the standard output stream. + + .. attribute:: stderr + + The :class:`CaptureBuffer` object used to capture the standard error stream. + """ + + def __init__(self, merged=False, input='', enabled=True): + """ + Initialize a :class:`CaptureOutput` object. + + :param merged: :data:`True` to merge the streams, + :data:`False` to capture them separately. + :param input: The data that reads from :data:`sys.stdin` + should return (a string). + :param enabled: :data:`True` to enable capturing (the default), + :data:`False` otherwise. This makes it easy to + unconditionally use :class:`CaptureOutput` in + a :keyword:`with` block while preserving the + choice to opt out of capturing output. + """ + self.stdin = StringIO(input) + self.stdout = CaptureBuffer() + self.stderr = self.stdout if merged else CaptureBuffer() + self.patched_attributes = [] + if enabled: + self.patched_attributes.extend( + PatchedAttribute(sys, name, getattr(self, name)) + for name in ('stdin', 'stdout', 'stderr') + ) + + def __enter__(self): + """Start capturing what's written to :data:`sys.stdout` and :data:`sys.stderr`.""" + super(CaptureOutput, self).__enter__() + for context in self.patched_attributes: + context.__enter__() + return self + + def __exit__(self, exc_type=None, exc_value=None, traceback=None): + """Stop capturing what's written to :data:`sys.stdout` and :data:`sys.stderr`.""" + super(CaptureOutput, self).__exit__(exc_type, exc_value, traceback) + for context in self.patched_attributes: + context.__exit__(exc_type, exc_value, traceback) + + def get_lines(self): + """Get the contents of :attr:`stdout` split into separate lines.""" + return self.get_text().splitlines() + + def get_text(self): + """Get the contents of :attr:`stdout` as a Unicode string.""" + return self.stdout.get_text() + + def getvalue(self): + """Get the text written to :data:`sys.stdout`.""" + return self.stdout.getvalue() + + +class CaptureBuffer(StringIO): + + """ + Helper for :class:`CaptureOutput` to provide an easy to use API. + + The two methods defined by this subclass were specifically chosen to match + the names of the methods provided by my :pypi:`capturer` package which + serves a similar role as :class:`CaptureOutput` but knows how to simulate + an interactive terminal (tty). + """ + + def get_lines(self): + """Get the contents of the buffer split into separate lines.""" + return self.get_text().splitlines() + + def get_text(self): + """Get the contents of the buffer as a Unicode string.""" + return self.getvalue() + + +class TestCase(unittest.TestCase): + + """Subclass of :class:`unittest.TestCase` with automatic logging and other miscellaneous features.""" + + def __init__(self, *args, **kw): + """ + Initialize a :class:`TestCase` object. + + Any positional and/or keyword arguments are passed on to the + initializer of the superclass. + """ + super(TestCase, self).__init__(*args, **kw) + + def setUp(self, log_level=logging.DEBUG): + """setUp(log_level=logging.DEBUG) + Automatically configure logging to the terminal. + + :param log_level: Refer to :func:`configure_logging()`. + + The :func:`setUp()` method is automatically called by + :class:`unittest.TestCase` before each test method starts. + It does two things: + + - Logging to the terminal is configured using + :func:`configure_logging()`. + + - Before the test method starts a newline is emitted, to separate the + name of the test method (which will be printed to the terminal by + :mod:`unittest` or :pypi:`pytest`) from the first line of logging + output that the test method is likely going to generate. + """ + # Configure logging to the terminal. + configure_logging(log_level) + # Separate the name of the test method (printed by the superclass + # and/or py.test without a newline at the end) from the first line of + # logging output that the test method is likely going to generate. + sys.stderr.write("\n") diff --git a/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/text.py b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/text.py new file mode 100644 index 0000000000000000000000000000000000000000..a257a6a189ff70c95567e7765f8ed530bafca8c2 --- /dev/null +++ b/evalkit_tf446/lib/python3.10/site-packages/humanfriendly/text.py @@ -0,0 +1,449 @@ +# Human friendly input/output in Python. +# +# Author: Peter Odding +# Last Change: December 1, 2020 +# URL: https://humanfriendly.readthedocs.io + +""" +Simple text manipulation functions. + +The :mod:`~humanfriendly.text` module contains simple functions to manipulate text: + +- The :func:`concatenate()` and :func:`pluralize()` functions make it easy to + generate human friendly output. + +- The :func:`format()`, :func:`compact()` and :func:`dedent()` functions + provide a clean and simple to use syntax for composing large text fragments + with interpolated variables. + +- The :func:`tokenize()` function parses simple user input. +""" + +# Standard library modules. +import numbers +import random +import re +import string +import textwrap + +# Public identifiers that require documentation. +__all__ = ( + 'compact', + 'compact_empty_lines', + 'concatenate', + 'dedent', + 'format', + 'generate_slug', + 'is_empty_line', + 'join_lines', + 'pluralize', + 'pluralize_raw', + 'random_string', + 'split', + 'split_paragraphs', + 'tokenize', + 'trim_empty_lines', +) + + +def compact(text, *args, **kw): + ''' + Compact whitespace in a string. + + Trims leading and trailing whitespace, replaces runs of whitespace + characters with a single space and interpolates any arguments using + :func:`format()`. + + :param text: The text to compact (a string). + :param args: Any positional arguments are interpolated using :func:`format()`. + :param kw: Any keyword arguments are interpolated using :func:`format()`. + :returns: The compacted text (a string). + + Here's an example of how I like to use the :func:`compact()` function, this + is an example from a random unrelated project I'm working on at the moment:: + + raise PortDiscoveryError(compact(""" + Failed to discover port(s) that Apache is listening on! + Maybe I'm parsing the wrong configuration file? ({filename}) + """, filename=self.ports_config)) + + The combination of :func:`compact()` and Python's multi line strings allows + me to write long text fragments with interpolated variables that are easy + to write, easy to read and work well with Python's whitespace + sensitivity. + ''' + non_whitespace_tokens = text.split() + compacted_text = ' '.join(non_whitespace_tokens) + return format(compacted_text, *args, **kw) + + +def compact_empty_lines(text): + """ + Replace repeating empty lines with a single empty line (similar to ``cat -s``). + + :param text: The text in which to compact empty lines (a string). + :returns: The text with empty lines compacted (a string). + """ + i = 0 + lines = text.splitlines(True) + while i < len(lines): + if i > 0 and is_empty_line(lines[i - 1]) and is_empty_line(lines[i]): + lines.pop(i) + else: + i += 1 + return ''.join(lines) + + +def concatenate(items, conjunction='and', serial_comma=False): + """ + Concatenate a list of items in a human friendly way. + + :param items: + + A sequence of strings. + + :param conjunction: + + The word to use before the last item (a string, defaults to "and"). + + :param serial_comma: + + :data:`True` to use a `serial comma`_, :data:`False` otherwise + (defaults to :data:`False`). + + :returns: + + A single string. + + >>> from humanfriendly.text import concatenate + >>> concatenate(["eggs", "milk", "bread"]) + 'eggs, milk and bread' + + .. _serial comma: https://en.wikipedia.org/wiki/Serial_comma + """ + items = list(items) + if len(items) > 1: + final_item = items.pop() + formatted = ', '.join(items) + if serial_comma: + formatted += ',' + return ' '.join([formatted, conjunction, final_item]) + elif items: + return items[0] + else: + return '' + + +def dedent(text, *args, **kw): + """ + Dedent a string (remove common leading whitespace from all lines). + + Removes common leading whitespace from all lines in the string using + :func:`textwrap.dedent()`, removes leading and trailing empty lines using + :func:`trim_empty_lines()` and interpolates any arguments using + :func:`format()`. + + :param text: The text to dedent (a string). + :param args: Any positional arguments are interpolated using :func:`format()`. + :param kw: Any keyword arguments are interpolated using :func:`format()`. + :returns: The dedented text (a string). + + The :func:`compact()` function's documentation contains an example of how I + like to use the :func:`compact()` and :func:`dedent()` functions. The main + difference is that I use :func:`compact()` for text that will be presented + to the user (where whitespace is not so significant) and :func:`dedent()` + for data file and code generation tasks (where newlines and indentation are + very significant). + """ + dedented_text = textwrap.dedent(text) + trimmed_text = trim_empty_lines(dedented_text) + return format(trimmed_text, *args, **kw) + + +def format(text, *args, **kw): + """ + Format a string using the string formatting operator and/or :meth:`str.format()`. + + :param text: The text to format (a string). + :param args: Any positional arguments are interpolated into the text using + the string formatting operator (``%``). If no positional + arguments are given no interpolation is done. + :param kw: Any keyword arguments are interpolated into the text using the + :meth:`str.format()` function. If no keyword arguments are given + no interpolation is done. + :returns: The text with any positional and/or keyword arguments + interpolated (a string). + + The implementation of this function is so trivial that it seems silly to + even bother writing and documenting it. Justifying this requires some + context :-). + + **Why format() instead of the string formatting operator?** + + For really simple string interpolation Python's string formatting operator + is ideal, but it does have some strange quirks: + + - When you switch from interpolating a single value to interpolating + multiple values you have to wrap them in tuple syntax. Because + :func:`format()` takes a `variable number of arguments`_ it always + receives a tuple (which saves me a context switch :-). Here's an + example: + + >>> from humanfriendly.text import format + >>> # The string formatting operator. + >>> print('the magic number is %s' % 42) + the magic number is 42 + >>> print('the magic numbers are %s and %s' % (12, 42)) + the magic numbers are 12 and 42 + >>> # The format() function. + >>> print(format('the magic number is %s', 42)) + the magic number is 42 + >>> print(format('the magic numbers are %s and %s', 12, 42)) + the magic numbers are 12 and 42 + + - When you interpolate a single value and someone accidentally passes in a + tuple your code raises a :exc:`~exceptions.TypeError`. Because + :func:`format()` takes a `variable number of arguments`_ it always + receives a tuple so this can never happen. Here's an example: + + >>> # How expecting to interpolate a single value can fail. + >>> value = (12, 42) + >>> print('the magic value is %s' % value) + Traceback (most recent call last): + File "", line 1, in + TypeError: not all arguments converted during string formatting + >>> # The following line works as intended, no surprises here! + >>> print(format('the magic value is %s', value)) + the magic value is (12, 42) + + **Why format() instead of the str.format() method?** + + When you're doing complex string interpolation the :meth:`str.format()` + function results in more readable code, however I frequently find myself + adding parentheses to force evaluation order. The :func:`format()` function + avoids this because of the relative priority between the comma and dot + operators. Here's an example: + + >>> "{adjective} example" + " " + "(can't think of anything less {adjective})".format(adjective='silly') + "{adjective} example (can't think of anything less silly)" + >>> ("{adjective} example" + " " + "(can't think of anything less {adjective})").format(adjective='silly') + "silly example (can't think of anything less silly)" + >>> format("{adjective} example" + " " + "(can't think of anything less {adjective})", adjective='silly') + "silly example (can't think of anything less silly)" + + The :func:`compact()` and :func:`dedent()` functions are wrappers that + combine :func:`format()` with whitespace manipulation to make it easy to + write nice to read Python code. + + .. _variable number of arguments: https://docs.python.org/2/tutorial/controlflow.html#arbitrary-argument-lists + """ + if args: + text %= args + if kw: + text = text.format(**kw) + return text + + +def generate_slug(text, delimiter="-"): + """ + Convert text to a normalized "slug" without whitespace. + + :param text: The original text, for example ``Some Random Text!``. + :param delimiter: The delimiter used to separate words + (defaults to the ``-`` character). + :returns: The slug text, for example ``some-random-text``. + :raises: :exc:`~exceptions.ValueError` when the provided + text is nonempty but results in an empty slug. + """ + slug = text.lower() + escaped = delimiter.replace("\\", "\\\\") + slug = re.sub("[^a-z0-9]+", escaped, slug) + slug = slug.strip(delimiter) + if text and not slug: + msg = "The provided text %r results in an empty slug!" + raise ValueError(format(msg, text)) + return slug + + +def is_empty_line(text): + """ + Check if a text is empty or contains only whitespace. + + :param text: The text to check for "emptiness" (a string). + :returns: :data:`True` if the text is empty or contains only whitespace, + :data:`False` otherwise. + """ + return len(text) == 0 or text.isspace() + + +def join_lines(text): + """ + Remove "hard wrapping" from the paragraphs in a string. + + :param text: The text to reformat (a string). + :returns: The text without hard wrapping (a string). + + This function works by removing line breaks when the last character before + a line break and the first character after the line break are both + non-whitespace characters. This means that common leading indentation will + break :func:`join_lines()` (in that case you can use :func:`dedent()` + before calling :func:`join_lines()`). + """ + return re.sub(r'(\S)\n(\S)', r'\1 \2', text) + + +def pluralize(count, singular, plural=None): + """ + Combine a count with the singular or plural form of a word. + + :param count: The count (a number). + :param singular: The singular form of the word (a string). + :param plural: The plural form of the word (a string or :data:`None`). + :returns: The count and singular or plural word concatenated (a string). + + See :func:`pluralize_raw()` for the logic underneath :func:`pluralize()`. + """ + return '%s %s' % (count, pluralize_raw(count, singular, plural)) + + +def pluralize_raw(count, singular, plural=None): + """ + Select the singular or plural form of a word based on a count. + + :param count: The count (a number). + :param singular: The singular form of the word (a string). + :param plural: The plural form of the word (a string or :data:`None`). + :returns: The singular or plural form of the word (a string). + + When the given count is exactly 1.0 the singular form of the word is + selected, in all other cases the plural form of the word is selected. + + If the plural form of the word is not provided it is obtained by + concatenating the singular form of the word with the letter "s". Of course + this will not always be correct, which is why you have the option to + specify both forms. + """ + if not plural: + plural = singular + 's' + return singular if float(count) == 1.0 else plural + + +def random_string(length=(25, 100), characters=string.ascii_letters): + """random_string(length=(25, 100), characters=string.ascii_letters) + Generate a random string. + + :param length: The length of the string to be generated (a number or a + tuple with two numbers). If this is a tuple then a random + number between the two numbers given in the tuple is used. + :param characters: The characters to be used (a string, defaults + to :data:`string.ascii_letters`). + :returns: A random string. + + The :func:`random_string()` function is very useful in test suites; by the + time I included it in :mod:`humanfriendly.text` I had already included + variants of this function in seven different test suites :-). + """ + if not isinstance(length, numbers.Number): + length = random.randint(length[0], length[1]) + return ''.join(random.choice(characters) for _ in range(length)) + + +def split(text, delimiter=','): + """ + Split a comma-separated list of strings. + + :param text: The text to split (a string). + :param delimiter: The delimiter to split on (a string). + :returns: A list of zero or more nonempty strings. + + Here's the default behavior of Python's built in :meth:`str.split()` + function: + + >>> 'foo,bar, baz,'.split(',') + ['foo', 'bar', ' baz', ''] + + In contrast here's the default behavior of the :func:`split()` function: + + >>> from humanfriendly.text import split + >>> split('foo,bar, baz,') + ['foo', 'bar', 'baz'] + + Here is an example that parses a nested data structure (a mapping of + logging level names to one or more styles per level) that's encoded in a + string so it can be set as an environment variable: + + >>> from pprint import pprint + >>> encoded_data = 'debug=green;warning=yellow;error=red;critical=red,bold' + >>> parsed_data = dict((k, split(v, ',')) for k, v in (split(kv, '=') for kv in split(encoded_data, ';'))) + >>> pprint(parsed_data) + {'debug': ['green'], + 'warning': ['yellow'], + 'error': ['red'], + 'critical': ['red', 'bold']} + """ + return [token.strip() for token in text.split(delimiter) if token and not token.isspace()] + + +def split_paragraphs(text): + """ + Split a string into paragraphs (one or more lines delimited by an empty line). + + :param text: The text to split into paragraphs (a string). + :returns: A list of strings. + """ + paragraphs = [] + for chunk in text.split('\n\n'): + chunk = trim_empty_lines(chunk) + if chunk and not chunk.isspace(): + paragraphs.append(chunk) + return paragraphs + + +def tokenize(text): + """ + Tokenize a text into numbers and strings. + + :param text: The text to tokenize (a string). + :returns: A list of strings and/or numbers. + + This function is used to implement robust tokenization of user input in + functions like :func:`.parse_size()` and :func:`.parse_timespan()`. It + automatically coerces integer and floating point numbers, ignores + whitespace and knows how to separate numbers from strings even without + whitespace. Some examples to make this more concrete: + + >>> from humanfriendly.text import tokenize + >>> tokenize('42') + [42] + >>> tokenize('42MB') + [42, 'MB'] + >>> tokenize('42.5MB') + [42.5, 'MB'] + >>> tokenize('42.5 MB') + [42.5, 'MB'] + """ + tokenized_input = [] + for token in re.split(r'(\d+(?:\.\d+)?)', text): + token = token.strip() + if re.match(r'\d+\.\d+', token): + tokenized_input.append(float(token)) + elif token.isdigit(): + tokenized_input.append(int(token)) + elif token: + tokenized_input.append(token) + return tokenized_input + + +def trim_empty_lines(text): + """ + Trim leading and trailing empty lines from the given text. + + :param text: The text to trim (a string). + :returns: The trimmed text (a string). + """ + lines = text.splitlines(True) + while lines and is_empty_line(lines[0]): + lines.pop(0) + while lines and is_empty_line(lines[-1]): + lines.pop(-1) + return ''.join(lines) diff --git a/evalkit_tf446/lib/python3.10/site-packages/parso-0.8.4.dist-info/INSTALLER b/evalkit_tf446/lib/python3.10/site-packages/parso-0.8.4.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/evalkit_tf446/lib/python3.10/site-packages/parso-0.8.4.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/evalkit_tf446/lib/python3.10/site-packages/parso-0.8.4.dist-info/LICENSE.txt b/evalkit_tf446/lib/python3.10/site-packages/parso-0.8.4.dist-info/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..08c41db014ea40b0f01e9f5c56793b3c1d138aea --- /dev/null +++ b/evalkit_tf446/lib/python3.10/site-packages/parso-0.8.4.dist-info/LICENSE.txt @@ -0,0 +1,86 @@ +All contributions towards parso are MIT licensed. + +Some Python files have been taken from the standard library and are therefore +PSF licensed. Modifications on these files are dual licensed (both MIT and +PSF). These files are: + +- parso/pgen2/* +- parso/tokenize.py +- parso/token.py +- test/test_pgen2.py + +Also some test files under test/normalizer_issue_files have been copied from +https://github.com/PyCQA/pycodestyle (Expat License == MIT License). + +------------------------------------------------------------------------------- +The MIT License (MIT) + +Copyright (c) <2013-2017> + +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. + +------------------------------------------------------------------------------- + +PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 +-------------------------------------------- + +1. This LICENSE AGREEMENT is between the Python Software Foundation +("PSF"), and the Individual or Organization ("Licensee") accessing and +otherwise using this software ("Python") in source or binary form and +its associated documentation. + +2. Subject to the terms and conditions of this License Agreement, PSF hereby +grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, +analyze, test, perform and/or display publicly, prepare derivative works, +distribute, and otherwise use Python alone or in any derivative version, +provided, however, that PSF's License Agreement and PSF's notice of copyright, +i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, +2011, 2012, 2013, 2014, 2015 Python Software Foundation; All Rights Reserved" +are retained in Python alone or in any derivative version prepared by Licensee. + +3. In the event Licensee prepares a derivative work that is based on +or incorporates Python or any part thereof, and wants to make +the derivative work available to others as provided herein, then +Licensee hereby agrees to include in any such work a brief summary of +the changes made to Python. + +4. PSF is making Python available to Licensee on an "AS IS" +basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON +FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS +A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, +OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +6. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +7. Nothing in this License Agreement shall be deemed to create any +relationship of agency, partnership, or joint venture between PSF and +Licensee. This License Agreement does not grant permission to use PSF +trademarks or trade name in a trademark sense to endorse or promote +products or services of Licensee, or any third party. + +8. By copying, installing or otherwise using Python, Licensee +agrees to be bound by the terms and conditions of this License +Agreement. diff --git a/evalkit_tf446/lib/python3.10/site-packages/parso-0.8.4.dist-info/METADATA b/evalkit_tf446/lib/python3.10/site-packages/parso-0.8.4.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..10f9cb843e8056d4cae4eb713acee3489d2d2b8c --- /dev/null +++ b/evalkit_tf446/lib/python3.10/site-packages/parso-0.8.4.dist-info/METADATA @@ -0,0 +1,287 @@ +Metadata-Version: 2.1 +Name: parso +Version: 0.8.4 +Summary: A Python Parser +Home-page: https://github.com/davidhalter/parso +Author: David Halter +Author-email: davidhalter88@gmail.com +Maintainer: David Halter +Maintainer-email: davidhalter88@gmail.com +License: MIT +Keywords: python parser parsing +Platform: any +Classifier: Development Status :: 4 - Beta +Classifier: Environment :: Plugins +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: MIT License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.6 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Topic :: Text Editors :: Integrated Development Environments (IDE) +Classifier: Topic :: Utilities +Classifier: Typing :: Typed +Requires-Python: >=3.6 +Provides-Extra: qa +Requires-Dist: flake8 (==5.0.4) ; extra == 'qa' +Requires-Dist: mypy (==0.971) ; extra == 'qa' +Requires-Dist: types-setuptools (==67.2.0.1) ; extra == 'qa' +Provides-Extra: testing +Requires-Dist: docopt ; extra == 'testing' +Requires-Dist: pytest ; extra == 'testing' + +################################################################### +parso - A Python Parser +################################################################### + + +.. image:: https://github.com/davidhalter/parso/workflows/Build/badge.svg?branch=master + :target: https://github.com/davidhalter/parso/actions + :alt: GitHub Actions build status + +.. image:: https://coveralls.io/repos/github/davidhalter/parso/badge.svg?branch=master + :target: https://coveralls.io/github/davidhalter/parso?branch=master + :alt: Coverage Status + +.. image:: https://pepy.tech/badge/parso + :target: https://pepy.tech/project/parso + :alt: PyPI Downloads + +.. image:: https://raw.githubusercontent.com/davidhalter/parso/master/docs/_static/logo_characters.png + +Parso is a Python parser that supports error recovery and round-trip parsing +for different Python versions (in multiple Python versions). Parso is also able +to list multiple syntax errors in your python file. + +Parso has been battle-tested by jedi_. It was pulled out of jedi to be useful +for other projects as well. + +Parso consists of a small API to parse Python and analyse the syntax tree. + +A simple example: + +.. code-block:: python + + >>> import parso + >>> module = parso.parse('hello + 1', version="3.9") + >>> expr = module.children[0] + >>> expr + PythonNode(arith_expr, [, , ]) + >>> print(expr.get_code()) + hello + 1 + >>> name = expr.children[0] + >>> name + + >>> name.end_pos + (1, 5) + >>> expr.end_pos + (1, 9) + +To list multiple issues: + +.. code-block:: python + + >>> grammar = parso.load_grammar() + >>> module = grammar.parse('foo +\nbar\ncontinue') + >>> error1, error2 = grammar.iter_errors(module) + >>> error1.message + 'SyntaxError: invalid syntax' + >>> error2.message + "SyntaxError: 'continue' not properly in loop" + +Resources +========= + +- `Testing `_ +- `PyPI `_ +- `Docs `_ +- Uses `semantic versioning `_ + +Installation +============ + + pip install parso + +Future +====== + +- There will be better support for refactoring and comments. Stay tuned. +- There's a WIP PEP8 validator. It's however not in a good shape, yet. + +Known Issues +============ + +- `async`/`await` are already used as keywords in Python3.6. +- `from __future__ import print_function` is not ignored. + + +Acknowledgements +================ + +- Guido van Rossum (@gvanrossum) for creating the parser generator pgen2 + (originally used in lib2to3). +- `Salome Schneider `_ + for the extremely awesome parso logo. + + +.. _jedi: https://github.com/davidhalter/jedi + + +.. :changelog: + +Changelog +--------- + +Unreleased +++++++++++ + +0.8.4 (2024-04-05) +++++++++++++++++++ + +- Add basic support for Python 3.13 + +0.8.3 (2021-11-30) +++++++++++++++++++ + +- Add basic support for Python 3.11 and 3.12 + +0.8.2 (2021-03-30) +++++++++++++++++++ + +- Various small bugfixes + +0.8.1 (2020-12-10) +++++++++++++++++++ + +- Various small bugfixes + +0.8.0 (2020-08-05) +++++++++++++++++++ + +- Dropped Support for Python 2.7, 3.4, 3.5 +- It's possible to use ``pathlib.Path`` objects now in the API +- The stubs are gone, we are now using annotations +- ``namedexpr_test`` nodes are now a proper class called ``NamedExpr`` +- A lot of smaller refactorings + +0.7.1 (2020-07-24) +++++++++++++++++++ + +- Fixed a couple of smaller bugs (mostly syntax error detection in + ``Grammar.iter_errors``) + +This is going to be the last release that supports Python 2.7, 3.4 and 3.5. + +0.7.0 (2020-04-13) +++++++++++++++++++ + +- Fix a lot of annoying bugs in the diff parser. The fuzzer did not find + issues anymore even after running it for more than 24 hours (500k tests). +- Small grammar change: suites can now contain newlines even after a newline. + This should really not matter if you don't use error recovery. It allows for + nicer error recovery. + +0.6.2 (2020-02-27) +++++++++++++++++++ + +- Bugfixes +- Add Grammar.refactor (might still be subject to change until 0.7.0) + +0.6.1 (2020-02-03) +++++++++++++++++++ + +- Add ``parso.normalizer.Issue.end_pos`` to make it possible to know where an + issue ends + +0.6.0 (2020-01-26) +++++++++++++++++++ + +- Dropped Python 2.6/Python 3.3 support +- del_stmt names are now considered as a definition + (for ``name.is_definition()``) +- Bugfixes + +0.5.2 (2019-12-15) +++++++++++++++++++ + +- Add include_setitem to get_definition/is_definition and get_defined_names (#66) +- Fix named expression error listing (#89, #90) +- Fix some f-string tokenizer issues (#93) + +0.5.1 (2019-07-13) +++++++++++++++++++ + +- Fix: Some unicode identifiers were not correctly tokenized +- Fix: Line continuations in f-strings are now working + +0.5.0 (2019-06-20) +++++++++++++++++++ + +- **Breaking Change** comp_for is now called sync_comp_for for all Python + versions to be compatible with the Python 3.8 Grammar +- Added .pyi stubs for a lot of the parso API +- Small FileIO changes + +0.4.0 (2019-04-05) +++++++++++++++++++ + +- Python 3.8 support +- FileIO support, it's now possible to use abstract file IO, support is alpha + +0.3.4 (2019-02-13) ++++++++++++++++++++ + +- Fix an f-string tokenizer error + +0.3.3 (2019-02-06) ++++++++++++++++++++ + +- Fix async errors in the diff parser +- A fix in iter_errors +- This is a very small bugfix release + +0.3.2 (2019-01-24) ++++++++++++++++++++ + +- 20+ bugfixes in the diff parser and 3 in the tokenizer +- A fuzzer for the diff parser, to give confidence that the diff parser is in a + good shape. +- Some bugfixes for f-string + +0.3.1 (2018-07-09) ++++++++++++++++++++ + +- Bugfixes in the diff parser and keyword-only arguments + +0.3.0 (2018-06-30) ++++++++++++++++++++ + +- Rewrote the pgen2 parser generator. + +0.2.1 (2018-05-21) ++++++++++++++++++++ + +- A bugfix for the diff parser. +- Grammar files can now be loaded from a specific path. + +0.2.0 (2018-04-15) ++++++++++++++++++++ + +- f-strings are now parsed as a part of the normal Python grammar. This makes + it way easier to deal with them. + +0.1.1 (2017-11-05) ++++++++++++++++++++ + +- Fixed a few bugs in the caching layer +- Added support for Python 3.7 + +0.1.0 (2017-09-04) ++++++++++++++++++++ + +- Pulling the library out of Jedi. Some APIs will definitely change. + + diff --git a/evalkit_tf446/lib/python3.10/site-packages/parso-0.8.4.dist-info/REQUESTED b/evalkit_tf446/lib/python3.10/site-packages/parso-0.8.4.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/evalkit_tf446/lib/python3.10/site-packages/parso-0.8.4.dist-info/top_level.txt b/evalkit_tf446/lib/python3.10/site-packages/parso-0.8.4.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..0e2334404713dd9c161c1d61e779798c4476a237 --- /dev/null +++ b/evalkit_tf446/lib/python3.10/site-packages/parso-0.8.4.dist-info/top_level.txt @@ -0,0 +1 @@ +parso diff --git a/evalkit_tf446/lib/python3.10/site-packages/uvicorn-0.32.0.dist-info/RECORD b/evalkit_tf446/lib/python3.10/site-packages/uvicorn-0.32.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..fca849884745c148e4066fbc9c3cbdb7746bbbdd --- /dev/null +++ b/evalkit_tf446/lib/python3.10/site-packages/uvicorn-0.32.0.dist-info/RECORD @@ -0,0 +1,87 @@ +../../../bin/uvicorn,sha256=iYbzwXo_ZbjDjrDc6eif7iIHRKhJB2a2m4lH5s8ZcYk,230 +uvicorn-0.32.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +uvicorn-0.32.0.dist-info/METADATA,sha256=uM66dN5rYhRB3gOPuEfEVITkmMNPGXNNX5V5b2mkgXw,6620 +uvicorn-0.32.0.dist-info/RECORD,, +uvicorn-0.32.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +uvicorn-0.32.0.dist-info/WHEEL,sha256=1yFddiXMmvYK7QYTqtRNtX66WJ0Mz8PYEiEUoOUUxRY,87 +uvicorn-0.32.0.dist-info/entry_points.txt,sha256=FW1w-hkc9QgwaGoovMvm0ZY73w_NcycWdGAUfDsNGxw,46 +uvicorn-0.32.0.dist-info/licenses/LICENSE.md,sha256=7-Gs8-YvuZwoiw7HPlp3O3Jo70Mg_nV-qZQhTktjw3E,1526 +uvicorn/__init__.py,sha256=WepnRLFNoKFn9CYP5C2Ya8jtfACAx_r-T_E5yIIQU6Q,147 +uvicorn/__main__.py,sha256=DQizy6nKP0ywhPpnCHgmRDYIMfcqZKVEzNIWQZjqtVQ,62 +uvicorn/__pycache__/__init__.cpython-310.pyc,, +uvicorn/__pycache__/__main__.cpython-310.pyc,, +uvicorn/__pycache__/_subprocess.cpython-310.pyc,, +uvicorn/__pycache__/_types.cpython-310.pyc,, +uvicorn/__pycache__/config.cpython-310.pyc,, +uvicorn/__pycache__/importer.cpython-310.pyc,, +uvicorn/__pycache__/logging.cpython-310.pyc,, +uvicorn/__pycache__/main.cpython-310.pyc,, +uvicorn/__pycache__/server.cpython-310.pyc,, +uvicorn/__pycache__/workers.cpython-310.pyc,, +uvicorn/_subprocess.py,sha256=HbfRnsCkXyg7xCWVAWWzXQTeWlvLKfTlIF5wevFBkR4,2766 +uvicorn/_types.py,sha256=TcUzCyKNq90ZX2Hxa6ce0juF558zLO_AyBB1XijnD2Y,7814 +uvicorn/config.py,sha256=gpsukzuJFbXBRN5_qOnLGiENmGgKM0Fi-eZJ6GwM1dQ,20849 +uvicorn/importer.py,sha256=nRt0QQ3qpi264-n_mR0l55C2ddM8nowTNzT1jsWaam8,1128 +uvicorn/lifespan/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +uvicorn/lifespan/__pycache__/__init__.cpython-310.pyc,, +uvicorn/lifespan/__pycache__/off.cpython-310.pyc,, +uvicorn/lifespan/__pycache__/on.cpython-310.pyc,, +uvicorn/lifespan/off.py,sha256=nfI6qHAUo_8-BEXMBKoHQ9wUbsXrPaXLCbDSS0vKSr8,332 +uvicorn/lifespan/on.py,sha256=1KYuFNNyQONIjtEHhKZAJp-OOokIyjj74wpGCGBv4lk,5184 +uvicorn/logging.py,sha256=sg4D9lHaW_kKQj_kmP-bolbChjKfhBuihktlWp8RjSI,4236 +uvicorn/loops/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +uvicorn/loops/__pycache__/__init__.cpython-310.pyc,, +uvicorn/loops/__pycache__/asyncio.cpython-310.pyc,, +uvicorn/loops/__pycache__/auto.cpython-310.pyc,, +uvicorn/loops/__pycache__/uvloop.cpython-310.pyc,, +uvicorn/loops/asyncio.py,sha256=qPnQLT2htZkcGG_ncnTyrSH38jEkqjg8guwP0lA146A,301 +uvicorn/loops/auto.py,sha256=BWVq18ce9SoFTo3z5zNW2IU2850u2tRrc6WyK7idsdI,400 +uvicorn/loops/uvloop.py,sha256=K4QybYVxtK9C2emDhDPUCkBXR4XMT5Ofv9BPFPoX0ok,148 +uvicorn/main.py,sha256=iv6ptgDBnko0W-VkHs0e3I4UrF7_5sEZrntQNKJGFNY,16915 +uvicorn/middleware/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +uvicorn/middleware/__pycache__/__init__.cpython-310.pyc,, +uvicorn/middleware/__pycache__/asgi2.cpython-310.pyc,, +uvicorn/middleware/__pycache__/message_logger.cpython-310.pyc,, +uvicorn/middleware/__pycache__/proxy_headers.cpython-310.pyc,, +uvicorn/middleware/__pycache__/wsgi.cpython-310.pyc,, +uvicorn/middleware/asgi2.py,sha256=YQrQNm3RehFts3mzk3k4yw8aD8Egtj0tRS3N45YkQa0,394 +uvicorn/middleware/message_logger.py,sha256=IHEZUSnFNaMFUFdwtZO3AuFATnYcSor-gVtOjbCzt8M,2859 +uvicorn/middleware/proxy_headers.py,sha256=f1VDAc-ipPHdNTuLNHwYCeDgYXoCL_VjD6hDTUXZT_U,5790 +uvicorn/middleware/wsgi.py,sha256=TBeG4W_gEmWddbGfWyxdzJ0IDaWWkJZyF8eIp-1fv0U,7111 +uvicorn/protocols/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +uvicorn/protocols/__pycache__/__init__.cpython-310.pyc,, +uvicorn/protocols/__pycache__/utils.cpython-310.pyc,, +uvicorn/protocols/http/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +uvicorn/protocols/http/__pycache__/__init__.cpython-310.pyc,, +uvicorn/protocols/http/__pycache__/auto.cpython-310.pyc,, +uvicorn/protocols/http/__pycache__/flow_control.cpython-310.pyc,, +uvicorn/protocols/http/__pycache__/h11_impl.cpython-310.pyc,, +uvicorn/protocols/http/__pycache__/httptools_impl.cpython-310.pyc,, +uvicorn/protocols/http/auto.py,sha256=YfXGyzWTaaE2p_jkTPWrJCXsxEaQnC3NK0-G7Wgmnls,403 +uvicorn/protocols/http/flow_control.py,sha256=050WVg31EvPOkHwynCoMP1zXFl_vO3U4durlc5vyp4U,1701 +uvicorn/protocols/http/h11_impl.py,sha256=MuX72-pIyZGHDtZ75-1mveeTj6_ruL-306Ug7z0yV8w,20765 +uvicorn/protocols/http/httptools_impl.py,sha256=TikbbIZRFG08KTClZER47ehM1Tu8koBfT6WGU5t5ACg,21491 +uvicorn/protocols/utils.py,sha256=rCjYLd4_uwPeZkbRXQ6beCfxyI_oYpvJCwz3jEGNOiE,1849 +uvicorn/protocols/websockets/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +uvicorn/protocols/websockets/__pycache__/__init__.cpython-310.pyc,, +uvicorn/protocols/websockets/__pycache__/auto.cpython-310.pyc,, +uvicorn/protocols/websockets/__pycache__/websockets_impl.cpython-310.pyc,, +uvicorn/protocols/websockets/__pycache__/wsproto_impl.cpython-310.pyc,, +uvicorn/protocols/websockets/auto.py,sha256=kNP-h07ZzjA9dKRUd7MNO0J7xhRJ5xVBfit7wCbdB0A,574 +uvicorn/protocols/websockets/websockets_impl.py,sha256=LV58OW3whQAd4iwbJl4R3iIod8myVYK3IhAn6F5VeZ4,15490 +uvicorn/protocols/websockets/wsproto_impl.py,sha256=haJEXK82Ldu8_hz4NDxQ0KpPXa9vOi6pG6iDLoBDKjs,15341 +uvicorn/py.typed,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1 +uvicorn/server.py,sha256=McDmVn0sBIVOzaCoKrp10oxaScD3tosoWhtsL1YldNo,13010 +uvicorn/supervisors/__init__.py,sha256=UVJYW3RVHMDSgUytToyAgGyd9NUQVqbNpVrQrvm4Tpc,700 +uvicorn/supervisors/__pycache__/__init__.cpython-310.pyc,, +uvicorn/supervisors/__pycache__/basereload.cpython-310.pyc,, +uvicorn/supervisors/__pycache__/multiprocess.cpython-310.pyc,, +uvicorn/supervisors/__pycache__/statreload.cpython-310.pyc,, +uvicorn/supervisors/__pycache__/watchfilesreload.cpython-310.pyc,, +uvicorn/supervisors/__pycache__/watchgodreload.cpython-310.pyc,, +uvicorn/supervisors/basereload.py,sha256=Hxezjgt_HXkOPVj-hJGH7uj0bZ3EhmwsmaOBc63ySoM,3831 +uvicorn/supervisors/multiprocess.py,sha256=Opt0XvOUj1DIMXYwb4OlkJZxeh_RjweFnTmDPYItONw,7507 +uvicorn/supervisors/statreload.py,sha256=gc-HUB44f811PvxD_ZIEQYenM7mWmhQQjYg7KKQ1c5o,1542 +uvicorn/supervisors/watchfilesreload.py,sha256=41FGNMXPKrKvPr-5O8yRWg43l6OCBtapt39M-gpdk0E,3010 +uvicorn/supervisors/watchgodreload.py,sha256=kd-gOvp14ArTNIc206Nt5CEjZZ4NP2UmMVYE7571yRQ,5486 +uvicorn/workers.py,sha256=DukTKlrCyyvWVHbJWBJflIV2yUe-q6KaGdrEwLrNmyc,3893 diff --git a/evalkit_tf446/lib/python3.10/site-packages/uvicorn-0.32.0.dist-info/REQUESTED b/evalkit_tf446/lib/python3.10/site-packages/uvicorn-0.32.0.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/evalkit_tf446/lib/python3.10/site-packages/uvicorn-0.32.0.dist-info/entry_points.txt b/evalkit_tf446/lib/python3.10/site-packages/uvicorn-0.32.0.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..4b00fcb60173c5497fb24839da1837e8bdbfd98c --- /dev/null +++ b/evalkit_tf446/lib/python3.10/site-packages/uvicorn-0.32.0.dist-info/entry_points.txt @@ -0,0 +1,2 @@ +[console_scripts] +uvicorn = uvicorn.main:main diff --git a/evalkit_tf446/lib/python3.10/site-packages/uvicorn-0.32.0.dist-info/licenses/LICENSE.md b/evalkit_tf446/lib/python3.10/site-packages/uvicorn-0.32.0.dist-info/licenses/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..a6bba14552c7673a7db57a5750ddb06508264273 --- /dev/null +++ b/evalkit_tf446/lib/python3.10/site-packages/uvicorn-0.32.0.dist-info/licenses/LICENSE.md @@ -0,0 +1,27 @@ +Copyright © 2017-present, [Encode OSS Ltd](https://www.encode.io/). +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/evalkit_tf446/lib/python3.10/site-packages/uvicorn/__pycache__/__init__.cpython-310.pyc b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3417839042ad6aedd90379bd747c63eb0add5254 Binary files /dev/null and b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/__pycache__/__init__.cpython-310.pyc differ diff --git a/evalkit_tf446/lib/python3.10/site-packages/uvicorn/__pycache__/__main__.cpython-310.pyc b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/__pycache__/__main__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..45997ec4099a42b755d4c75b4d8a64bb05d91a98 Binary files /dev/null and b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/__pycache__/__main__.cpython-310.pyc differ diff --git a/evalkit_tf446/lib/python3.10/site-packages/uvicorn/__pycache__/_subprocess.cpython-310.pyc b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/__pycache__/_subprocess.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f01022c56124e583d063ebf35b2979eaeac3f0c0 Binary files /dev/null and b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/__pycache__/_subprocess.cpython-310.pyc differ diff --git a/evalkit_tf446/lib/python3.10/site-packages/uvicorn/__pycache__/_types.cpython-310.pyc b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/__pycache__/_types.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e7e2f04acd002cc8e6fec0ae052cf07a6ff7044d Binary files /dev/null and b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/__pycache__/_types.cpython-310.pyc differ diff --git a/evalkit_tf446/lib/python3.10/site-packages/uvicorn/__pycache__/config.cpython-310.pyc b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/__pycache__/config.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dcd3e0b7c557a6b2c5f348368fe30a6a1efee0d1 Binary files /dev/null and b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/__pycache__/config.cpython-310.pyc differ diff --git a/evalkit_tf446/lib/python3.10/site-packages/uvicorn/__pycache__/importer.cpython-310.pyc b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/__pycache__/importer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4043c37d29a3bcee1276cf91a1dad4455c5636ab Binary files /dev/null and b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/__pycache__/importer.cpython-310.pyc differ diff --git a/evalkit_tf446/lib/python3.10/site-packages/uvicorn/__pycache__/logging.cpython-310.pyc b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/__pycache__/logging.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..61dd37c0d970d7c6419a45a5f7442bf8bc15018c Binary files /dev/null and b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/__pycache__/logging.cpython-310.pyc differ diff --git a/evalkit_tf446/lib/python3.10/site-packages/uvicorn/__pycache__/main.cpython-310.pyc b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/__pycache__/main.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b743c0cdd1a97fdc7d5bc6d780b8ddf94ab4618d Binary files /dev/null and b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/__pycache__/main.cpython-310.pyc differ diff --git a/evalkit_tf446/lib/python3.10/site-packages/uvicorn/__pycache__/server.cpython-310.pyc b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/__pycache__/server.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b87dfaf0be6e55e788e6432814bfee7ee7ca4684 Binary files /dev/null and b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/__pycache__/server.cpython-310.pyc differ diff --git a/evalkit_tf446/lib/python3.10/site-packages/uvicorn/__pycache__/workers.cpython-310.pyc b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/__pycache__/workers.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d62110892e952fc129e699b05bcfcf94baf595b2 Binary files /dev/null and b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/__pycache__/workers.cpython-310.pyc differ diff --git a/evalkit_tf446/lib/python3.10/site-packages/uvicorn/lifespan/__init__.py b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/lifespan/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/evalkit_tf446/lib/python3.10/site-packages/uvicorn/lifespan/__pycache__/__init__.cpython-310.pyc b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/lifespan/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bcf693877c222c2273e4f5c54b63af282dacfb97 Binary files /dev/null and b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/lifespan/__pycache__/__init__.cpython-310.pyc differ diff --git a/evalkit_tf446/lib/python3.10/site-packages/uvicorn/lifespan/__pycache__/off.cpython-310.pyc b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/lifespan/__pycache__/off.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5852b299c5fbb28280c18a8219d5bd76d06f8a54 Binary files /dev/null and b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/lifespan/__pycache__/off.cpython-310.pyc differ diff --git a/evalkit_tf446/lib/python3.10/site-packages/uvicorn/lifespan/__pycache__/on.cpython-310.pyc b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/lifespan/__pycache__/on.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c2f05f05b2adc9f12873efeee793cac16c69e263 Binary files /dev/null and b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/lifespan/__pycache__/on.cpython-310.pyc differ diff --git a/evalkit_tf446/lib/python3.10/site-packages/uvicorn/lifespan/on.py b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/lifespan/on.py new file mode 100644 index 0000000000000000000000000000000000000000..09df984ea1b184c0af9666c98d0709364de024c5 --- /dev/null +++ b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/lifespan/on.py @@ -0,0 +1,137 @@ +from __future__ import annotations + +import asyncio +import logging +from asyncio import Queue +from typing import Any, Union + +from uvicorn import Config +from uvicorn._types import ( + LifespanScope, + LifespanShutdownCompleteEvent, + LifespanShutdownEvent, + LifespanShutdownFailedEvent, + LifespanStartupCompleteEvent, + LifespanStartupEvent, + LifespanStartupFailedEvent, +) + +LifespanReceiveMessage = Union[LifespanStartupEvent, LifespanShutdownEvent] +LifespanSendMessage = Union[ + LifespanStartupFailedEvent, + LifespanShutdownFailedEvent, + LifespanStartupCompleteEvent, + LifespanShutdownCompleteEvent, +] + + +STATE_TRANSITION_ERROR = "Got invalid state transition on lifespan protocol." + + +class LifespanOn: + def __init__(self, config: Config) -> None: + if not config.loaded: + config.load() + + self.config = config + self.logger = logging.getLogger("uvicorn.error") + self.startup_event = asyncio.Event() + self.shutdown_event = asyncio.Event() + self.receive_queue: Queue[LifespanReceiveMessage] = asyncio.Queue() + self.error_occured = False + self.startup_failed = False + self.shutdown_failed = False + self.should_exit = False + self.state: dict[str, Any] = {} + + async def startup(self) -> None: + self.logger.info("Waiting for application startup.") + + loop = asyncio.get_event_loop() + main_lifespan_task = loop.create_task(self.main()) # noqa: F841 + # Keep a hard reference to prevent garbage collection + # See https://github.com/encode/uvicorn/pull/972 + startup_event: LifespanStartupEvent = {"type": "lifespan.startup"} + await self.receive_queue.put(startup_event) + await self.startup_event.wait() + + if self.startup_failed or (self.error_occured and self.config.lifespan == "on"): + self.logger.error("Application startup failed. Exiting.") + self.should_exit = True + else: + self.logger.info("Application startup complete.") + + async def shutdown(self) -> None: + if self.error_occured: + return + self.logger.info("Waiting for application shutdown.") + shutdown_event: LifespanShutdownEvent = {"type": "lifespan.shutdown"} + await self.receive_queue.put(shutdown_event) + await self.shutdown_event.wait() + + if self.shutdown_failed or (self.error_occured and self.config.lifespan == "on"): + self.logger.error("Application shutdown failed. Exiting.") + self.should_exit = True + else: + self.logger.info("Application shutdown complete.") + + async def main(self) -> None: + try: + app = self.config.loaded_app + scope: LifespanScope = { + "type": "lifespan", + "asgi": {"version": self.config.asgi_version, "spec_version": "2.0"}, + "state": self.state, + } + await app(scope, self.receive, self.send) + except BaseException as exc: + self.asgi = None + self.error_occured = True + if self.startup_failed or self.shutdown_failed: + return + if self.config.lifespan == "auto": + msg = "ASGI 'lifespan' protocol appears unsupported." + self.logger.info(msg) + else: + msg = "Exception in 'lifespan' protocol\n" + self.logger.error(msg, exc_info=exc) + finally: + self.startup_event.set() + self.shutdown_event.set() + + async def send(self, message: LifespanSendMessage) -> None: + assert message["type"] in ( + "lifespan.startup.complete", + "lifespan.startup.failed", + "lifespan.shutdown.complete", + "lifespan.shutdown.failed", + ) + + if message["type"] == "lifespan.startup.complete": + assert not self.startup_event.is_set(), STATE_TRANSITION_ERROR + assert not self.shutdown_event.is_set(), STATE_TRANSITION_ERROR + self.startup_event.set() + + elif message["type"] == "lifespan.startup.failed": + assert not self.startup_event.is_set(), STATE_TRANSITION_ERROR + assert not self.shutdown_event.is_set(), STATE_TRANSITION_ERROR + self.startup_event.set() + self.startup_failed = True + if message.get("message"): + self.logger.error(message["message"]) + + elif message["type"] == "lifespan.shutdown.complete": + assert self.startup_event.is_set(), STATE_TRANSITION_ERROR + assert not self.shutdown_event.is_set(), STATE_TRANSITION_ERROR + self.shutdown_event.set() + + elif message["type"] == "lifespan.shutdown.failed": + assert self.startup_event.is_set(), STATE_TRANSITION_ERROR + assert not self.shutdown_event.is_set(), STATE_TRANSITION_ERROR + self.shutdown_event.set() + self.shutdown_failed = True + if message.get("message"): + self.logger.error(message["message"]) + + async def receive(self) -> LifespanReceiveMessage: + return await self.receive_queue.get() diff --git a/evalkit_tf446/lib/python3.10/site-packages/uvicorn/middleware/__pycache__/__init__.cpython-310.pyc b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/middleware/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e4d1aab93b1990820687424da14a17a2338fbd12 Binary files /dev/null and b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/middleware/__pycache__/__init__.cpython-310.pyc differ diff --git a/evalkit_tf446/lib/python3.10/site-packages/uvicorn/middleware/__pycache__/asgi2.cpython-310.pyc b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/middleware/__pycache__/asgi2.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e310ab648aa006dffb94d58fa38cf478e2b9466 Binary files /dev/null and b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/middleware/__pycache__/asgi2.cpython-310.pyc differ diff --git a/evalkit_tf446/lib/python3.10/site-packages/uvicorn/middleware/__pycache__/message_logger.cpython-310.pyc b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/middleware/__pycache__/message_logger.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..49d7e4e914592cae313024558021babcbb0ab33e Binary files /dev/null and b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/middleware/__pycache__/message_logger.cpython-310.pyc differ diff --git a/evalkit_tf446/lib/python3.10/site-packages/uvicorn/middleware/__pycache__/proxy_headers.cpython-310.pyc b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/middleware/__pycache__/proxy_headers.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..69d2c86a11457b643bf923bfd5f4f1e11b1574d5 Binary files /dev/null and b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/middleware/__pycache__/proxy_headers.cpython-310.pyc differ diff --git a/evalkit_tf446/lib/python3.10/site-packages/uvicorn/middleware/__pycache__/wsgi.cpython-310.pyc b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/middleware/__pycache__/wsgi.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e81da24c18afd4241932c918176d49b3c07fab0a Binary files /dev/null and b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/middleware/__pycache__/wsgi.cpython-310.pyc differ diff --git a/evalkit_tf446/lib/python3.10/site-packages/uvicorn/middleware/asgi2.py b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/middleware/asgi2.py new file mode 100644 index 0000000000000000000000000000000000000000..4e15d1599bab04ac38f56cf271d2ff9b1b9984c8 --- /dev/null +++ b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/middleware/asgi2.py @@ -0,0 +1,15 @@ +from uvicorn._types import ( + ASGI2Application, + ASGIReceiveCallable, + ASGISendCallable, + Scope, +) + + +class ASGI2Middleware: + def __init__(self, app: "ASGI2Application"): + self.app = app + + async def __call__(self, scope: "Scope", receive: "ASGIReceiveCallable", send: "ASGISendCallable") -> None: + instance = self.app(scope) + await instance(receive, send) diff --git a/evalkit_tf446/lib/python3.10/site-packages/uvicorn/middleware/message_logger.py b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/middleware/message_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..0174bcce6d48de946214d59bcae5543d38d89c3a --- /dev/null +++ b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/middleware/message_logger.py @@ -0,0 +1,87 @@ +import logging +from typing import Any + +from uvicorn._types import ( + ASGI3Application, + ASGIReceiveCallable, + ASGIReceiveEvent, + ASGISendCallable, + ASGISendEvent, + WWWScope, +) +from uvicorn.logging import TRACE_LOG_LEVEL + +PLACEHOLDER_FORMAT = { + "body": "<{length} bytes>", + "bytes": "<{length} bytes>", + "text": "<{length} chars>", + "headers": "<...>", +} + + +def message_with_placeholders(message: Any) -> Any: + """ + Return an ASGI message, with any body-type content omitted and replaced + with a placeholder. + """ + new_message = message.copy() + for attr in PLACEHOLDER_FORMAT.keys(): + if message.get(attr) is not None: + content = message[attr] + placeholder = PLACEHOLDER_FORMAT[attr].format(length=len(content)) + new_message[attr] = placeholder + return new_message + + +class MessageLoggerMiddleware: + def __init__(self, app: "ASGI3Application"): + self.task_counter = 0 + self.app = app + self.logger = logging.getLogger("uvicorn.asgi") + + def trace(message: Any, *args: Any, **kwargs: Any) -> None: + self.logger.log(TRACE_LOG_LEVEL, message, *args, **kwargs) + + self.logger.trace = trace # type: ignore + + async def __call__( + self, + scope: "WWWScope", + receive: "ASGIReceiveCallable", + send: "ASGISendCallable", + ) -> None: + self.task_counter += 1 + + task_counter = self.task_counter + client = scope.get("client") + prefix = "%s:%d - ASGI" % (client[0], client[1]) if client else "ASGI" + + async def inner_receive() -> "ASGIReceiveEvent": + message = await receive() + logged_message = message_with_placeholders(message) + log_text = "%s [%d] Receive %s" + self.logger.trace( # type: ignore + log_text, prefix, task_counter, logged_message + ) + return message + + async def inner_send(message: "ASGISendEvent") -> None: + logged_message = message_with_placeholders(message) + log_text = "%s [%d] Send %s" + self.logger.trace( # type: ignore + log_text, prefix, task_counter, logged_message + ) + await send(message) + + logged_scope = message_with_placeholders(scope) + log_text = "%s [%d] Started scope=%s" + self.logger.trace(log_text, prefix, task_counter, logged_scope) # type: ignore + try: + await self.app(scope, inner_receive, inner_send) + except BaseException as exc: + log_text = "%s [%d] Raised exception" + self.logger.trace(log_text, prefix, task_counter) # type: ignore + raise exc from None + else: + log_text = "%s [%d] Completed" + self.logger.trace(log_text, prefix, task_counter) # type: ignore diff --git a/evalkit_tf446/lib/python3.10/site-packages/uvicorn/middleware/wsgi.py b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/middleware/wsgi.py new file mode 100644 index 0000000000000000000000000000000000000000..078de1af01579e2020303ad1ee65481f84db0c84 --- /dev/null +++ b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/middleware/wsgi.py @@ -0,0 +1,200 @@ +from __future__ import annotations + +import asyncio +import concurrent.futures +import io +import sys +import warnings +from collections import deque +from typing import Iterable + +from uvicorn._types import ( + ASGIReceiveCallable, + ASGIReceiveEvent, + ASGISendCallable, + ASGISendEvent, + Environ, + ExcInfo, + HTTPRequestEvent, + HTTPResponseBodyEvent, + HTTPResponseStartEvent, + HTTPScope, + StartResponse, + WSGIApp, +) + + +def build_environ(scope: HTTPScope, message: ASGIReceiveEvent, body: io.BytesIO) -> Environ: + """ + Builds a scope and request message into a WSGI environ object. + """ + script_name = scope.get("root_path", "").encode("utf8").decode("latin1") + path_info = scope["path"].encode("utf8").decode("latin1") + if path_info.startswith(script_name): + path_info = path_info[len(script_name) :] + environ = { + "REQUEST_METHOD": scope["method"], + "SCRIPT_NAME": script_name, + "PATH_INFO": path_info, + "QUERY_STRING": scope["query_string"].decode("ascii"), + "SERVER_PROTOCOL": "HTTP/%s" % scope["http_version"], + "wsgi.version": (1, 0), + "wsgi.url_scheme": scope.get("scheme", "http"), + "wsgi.input": body, + "wsgi.errors": sys.stdout, + "wsgi.multithread": True, + "wsgi.multiprocess": True, + "wsgi.run_once": False, + } + + # Get server name and port - required in WSGI, not in ASGI + server = scope.get("server") + if server is None: + server = ("localhost", 80) + environ["SERVER_NAME"] = server[0] + environ["SERVER_PORT"] = server[1] + + # Get client IP address + client = scope.get("client") + if client is not None: + environ["REMOTE_ADDR"] = client[0] + + # Go through headers and make them into environ entries + for name, value in scope.get("headers", []): + name_str: str = name.decode("latin1") + if name_str == "content-length": + corrected_name = "CONTENT_LENGTH" + elif name_str == "content-type": + corrected_name = "CONTENT_TYPE" + else: + corrected_name = "HTTP_%s" % name_str.upper().replace("-", "_") + # HTTPbis say only ASCII chars are allowed in headers, but we latin1 + # just in case + value_str: str = value.decode("latin1") + if corrected_name in environ: + corrected_name_environ = environ[corrected_name] + assert isinstance(corrected_name_environ, str) + value_str = corrected_name_environ + "," + value_str + environ[corrected_name] = value_str + return environ + + +class _WSGIMiddleware: + def __init__(self, app: WSGIApp, workers: int = 10): + warnings.warn( + "Uvicorn's native WSGI implementation is deprecated, you " + "should switch to a2wsgi (`pip install a2wsgi`).", + DeprecationWarning, + ) + self.app = app + self.executor = concurrent.futures.ThreadPoolExecutor(max_workers=workers) + + async def __call__( + self, + scope: HTTPScope, + receive: ASGIReceiveCallable, + send: ASGISendCallable, + ) -> None: + assert scope["type"] == "http" + instance = WSGIResponder(self.app, self.executor, scope) + await instance(receive, send) + + +class WSGIResponder: + def __init__( + self, + app: WSGIApp, + executor: concurrent.futures.ThreadPoolExecutor, + scope: HTTPScope, + ): + self.app = app + self.executor = executor + self.scope = scope + self.status = None + self.response_headers = None + self.send_event = asyncio.Event() + self.send_queue: deque[ASGISendEvent | None] = deque() + self.loop: asyncio.AbstractEventLoop = asyncio.get_event_loop() + self.response_started = False + self.exc_info: ExcInfo | None = None + + async def __call__(self, receive: ASGIReceiveCallable, send: ASGISendCallable) -> None: + message: HTTPRequestEvent = await receive() # type: ignore[assignment] + body = io.BytesIO(message.get("body", b"")) + more_body = message.get("more_body", False) + if more_body: + body.seek(0, io.SEEK_END) + while more_body: + body_message: HTTPRequestEvent = ( + await receive() # type: ignore[assignment] + ) + body.write(body_message.get("body", b"")) + more_body = body_message.get("more_body", False) + body.seek(0) + environ = build_environ(self.scope, message, body) + self.loop = asyncio.get_event_loop() + wsgi = self.loop.run_in_executor(self.executor, self.wsgi, environ, self.start_response) + sender = self.loop.create_task(self.sender(send)) + try: + await asyncio.wait_for(wsgi, None) + finally: + self.send_queue.append(None) + self.send_event.set() + await asyncio.wait_for(sender, None) + if self.exc_info is not None: + raise self.exc_info[0].with_traceback(self.exc_info[1], self.exc_info[2]) + + async def sender(self, send: ASGISendCallable) -> None: + while True: + if self.send_queue: + message = self.send_queue.popleft() + if message is None: + return + await send(message) + else: + await self.send_event.wait() + self.send_event.clear() + + def start_response( + self, + status: str, + response_headers: Iterable[tuple[str, str]], + exc_info: ExcInfo | None = None, + ) -> None: + self.exc_info = exc_info + if not self.response_started: + self.response_started = True + status_code_str, _ = status.split(" ", 1) + status_code = int(status_code_str) + headers = [(name.encode("ascii"), value.encode("ascii")) for name, value in response_headers] + http_response_start_event: HTTPResponseStartEvent = { + "type": "http.response.start", + "status": status_code, + "headers": headers, + } + self.send_queue.append(http_response_start_event) + self.loop.call_soon_threadsafe(self.send_event.set) + + def wsgi(self, environ: Environ, start_response: StartResponse) -> None: + for chunk in self.app(environ, start_response): # type: ignore + response_body: HTTPResponseBodyEvent = { + "type": "http.response.body", + "body": chunk, + "more_body": True, + } + self.send_queue.append(response_body) + self.loop.call_soon_threadsafe(self.send_event.set) + + empty_body: HTTPResponseBodyEvent = { + "type": "http.response.body", + "body": b"", + "more_body": False, + } + self.send_queue.append(empty_body) + self.loop.call_soon_threadsafe(self.send_event.set) + + +try: + from a2wsgi import WSGIMiddleware +except ModuleNotFoundError: # pragma: no cover + WSGIMiddleware = _WSGIMiddleware # type: ignore[misc, assignment] diff --git a/evalkit_tf446/lib/python3.10/site-packages/uvicorn/protocols/http/__pycache__/__init__.cpython-310.pyc b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/protocols/http/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fda867a6661b813001fdc6a8df7cf11dd60802b2 Binary files /dev/null and b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/protocols/http/__pycache__/__init__.cpython-310.pyc differ diff --git a/evalkit_tf446/lib/python3.10/site-packages/uvicorn/protocols/http/__pycache__/flow_control.cpython-310.pyc b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/protocols/http/__pycache__/flow_control.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6154683ce76ed935969e2d8928211279f47f9bd6 Binary files /dev/null and b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/protocols/http/__pycache__/flow_control.cpython-310.pyc differ diff --git a/evalkit_tf446/lib/python3.10/site-packages/uvicorn/protocols/http/__pycache__/h11_impl.cpython-310.pyc b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/protocols/http/__pycache__/h11_impl.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c5145bc3b4072fd596e9644a55f65b90fda35335 Binary files /dev/null and b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/protocols/http/__pycache__/h11_impl.cpython-310.pyc differ diff --git a/evalkit_tf446/lib/python3.10/site-packages/uvicorn/protocols/websockets/__pycache__/__init__.cpython-310.pyc b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/protocols/websockets/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b130d663c2f8617ed1ea59d92c699b1bc3ee3fc9 Binary files /dev/null and b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/protocols/websockets/__pycache__/__init__.cpython-310.pyc differ diff --git a/evalkit_tf446/lib/python3.10/site-packages/uvicorn/protocols/websockets/__pycache__/wsproto_impl.cpython-310.pyc b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/protocols/websockets/__pycache__/wsproto_impl.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..24dbdbf5ec90a073a45ffdffd25377cedbafbb6a Binary files /dev/null and b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/protocols/websockets/__pycache__/wsproto_impl.cpython-310.pyc differ diff --git a/evalkit_tf446/lib/python3.10/site-packages/uvicorn/protocols/websockets/auto.py b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/protocols/websockets/auto.py new file mode 100644 index 0000000000000000000000000000000000000000..08fd13678a1c4dffe3e126acf0167c17d62c2ed8 --- /dev/null +++ b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/protocols/websockets/auto.py @@ -0,0 +1,21 @@ +from __future__ import annotations + +import asyncio +import typing + +AutoWebSocketsProtocol: typing.Callable[..., asyncio.Protocol] | None +try: + import websockets # noqa +except ImportError: # pragma: no cover + try: + import wsproto # noqa + except ImportError: + AutoWebSocketsProtocol = None + else: + from uvicorn.protocols.websockets.wsproto_impl import WSProtocol + + AutoWebSocketsProtocol = WSProtocol +else: + from uvicorn.protocols.websockets.websockets_impl import WebSocketProtocol + + AutoWebSocketsProtocol = WebSocketProtocol diff --git a/evalkit_tf446/lib/python3.10/site-packages/uvicorn/supervisors/__init__.py b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/supervisors/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c90f24e4acbf48142b34ae0fe6f137d967cad7e6 --- /dev/null +++ b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/supervisors/__init__.py @@ -0,0 +1,23 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +from uvicorn.supervisors.basereload import BaseReload +from uvicorn.supervisors.multiprocess import Multiprocess + +if TYPE_CHECKING: + ChangeReload: type[BaseReload] +else: + try: + from uvicorn.supervisors.watchfilesreload import ( + WatchFilesReload as ChangeReload, + ) + except ImportError: # pragma: no cover + try: + from uvicorn.supervisors.watchgodreload import ( + WatchGodReload as ChangeReload, + ) + except ImportError: + from uvicorn.supervisors.statreload import StatReload as ChangeReload + +__all__ = ["Multiprocess", "ChangeReload"] diff --git a/evalkit_tf446/lib/python3.10/site-packages/uvicorn/supervisors/__pycache__/__init__.cpython-310.pyc b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/supervisors/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cf2ae67783205df0fb98c93a9fd221c8430b1acc Binary files /dev/null and b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/supervisors/__pycache__/__init__.cpython-310.pyc differ diff --git a/evalkit_tf446/lib/python3.10/site-packages/uvicorn/supervisors/__pycache__/multiprocess.cpython-310.pyc b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/supervisors/__pycache__/multiprocess.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..402b484239b40e737c783b20b8cfdfd85657d90e Binary files /dev/null and b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/supervisors/__pycache__/multiprocess.cpython-310.pyc differ diff --git a/evalkit_tf446/lib/python3.10/site-packages/uvicorn/supervisors/__pycache__/watchfilesreload.cpython-310.pyc b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/supervisors/__pycache__/watchfilesreload.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c358cfddb79824fd9582f8ecfce8d97268b95db6 Binary files /dev/null and b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/supervisors/__pycache__/watchfilesreload.cpython-310.pyc differ diff --git a/evalkit_tf446/lib/python3.10/site-packages/uvicorn/supervisors/multiprocess.py b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/supervisors/multiprocess.py new file mode 100644 index 0000000000000000000000000000000000000000..e198fe780bf5d24f7eba828a28a279d98133361c --- /dev/null +++ b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/supervisors/multiprocess.py @@ -0,0 +1,222 @@ +from __future__ import annotations + +import logging +import os +import signal +import threading +from multiprocessing import Pipe +from socket import socket +from typing import Any, Callable + +import click + +from uvicorn._subprocess import get_subprocess +from uvicorn.config import Config + +SIGNALS = { + getattr(signal, f"SIG{x}"): x + for x in "INT TERM BREAK HUP QUIT TTIN TTOU USR1 USR2 WINCH".split() + if hasattr(signal, f"SIG{x}") +} + +logger = logging.getLogger("uvicorn.error") + + +class Process: + def __init__( + self, + config: Config, + target: Callable[[list[socket] | None], None], + sockets: list[socket], + ) -> None: + self.real_target = target + + self.parent_conn, self.child_conn = Pipe() + self.process = get_subprocess(config, self.target, sockets) + + def ping(self, timeout: float = 5) -> bool: + self.parent_conn.send(b"ping") + if self.parent_conn.poll(timeout): + self.parent_conn.recv() + return True + return False + + def pong(self) -> None: + self.child_conn.recv() + self.child_conn.send(b"pong") + + def always_pong(self) -> None: + while True: + self.pong() + + def target(self, sockets: list[socket] | None = None) -> Any: # pragma: no cover + if os.name == "nt": # pragma: py-not-win32 + # Windows doesn't support SIGTERM, so we use SIGBREAK instead. + # And then we raise SIGTERM when SIGBREAK is received. + # https://learn.microsoft.com/zh-cn/cpp/c-runtime-library/reference/signal?view=msvc-170 + signal.signal( + signal.SIGBREAK, # type: ignore[attr-defined] + lambda sig, frame: signal.raise_signal(signal.SIGTERM), + ) + + threading.Thread(target=self.always_pong, daemon=True).start() + return self.real_target(sockets) + + def is_alive(self, timeout: float = 5) -> bool: + if not self.process.is_alive(): + return False # pragma: full coverage + + return self.ping(timeout) + + def start(self) -> None: + self.process.start() + + def terminate(self) -> None: + if self.process.exitcode is None: # Process is still running + assert self.process.pid is not None + if os.name == "nt": # pragma: py-not-win32 + # Windows doesn't support SIGTERM. + # So send SIGBREAK, and then in process raise SIGTERM. + os.kill(self.process.pid, signal.CTRL_BREAK_EVENT) # type: ignore[attr-defined] + else: + os.kill(self.process.pid, signal.SIGTERM) + logger.info(f"Terminated child process [{self.process.pid}]") + + self.parent_conn.close() + self.child_conn.close() + + def kill(self) -> None: + # In Windows, the method will call `TerminateProcess` to kill the process. + # In Unix, the method will send SIGKILL to the process. + self.process.kill() + + def join(self) -> None: + logger.info(f"Waiting for child process [{self.process.pid}]") + self.process.join() + + @property + def pid(self) -> int | None: + return self.process.pid + + +class Multiprocess: + def __init__( + self, + config: Config, + target: Callable[[list[socket] | None], None], + sockets: list[socket], + ) -> None: + self.config = config + self.target = target + self.sockets = sockets + + self.processes_num = config.workers + self.processes: list[Process] = [] + + self.should_exit = threading.Event() + + self.signal_queue: list[int] = [] + for sig in SIGNALS: + signal.signal(sig, lambda sig, frame: self.signal_queue.append(sig)) + + def init_processes(self) -> None: + for _ in range(self.processes_num): + process = Process(self.config, self.target, self.sockets) + process.start() + self.processes.append(process) + + def terminate_all(self) -> None: + for process in self.processes: + process.terminate() + + def join_all(self) -> None: + for process in self.processes: + process.join() + + def restart_all(self) -> None: + for idx, process in enumerate(self.processes): + process.terminate() + process.join() + new_process = Process(self.config, self.target, self.sockets) + new_process.start() + self.processes[idx] = new_process + + def run(self) -> None: + message = f"Started parent process [{os.getpid()}]" + color_message = "Started parent process [{}]".format(click.style(str(os.getpid()), fg="cyan", bold=True)) + logger.info(message, extra={"color_message": color_message}) + + self.init_processes() + + while not self.should_exit.wait(0.5): + self.handle_signals() + self.keep_subprocess_alive() + + self.terminate_all() + self.join_all() + + message = f"Stopping parent process [{os.getpid()}]" + color_message = "Stopping parent process [{}]".format(click.style(str(os.getpid()), fg="cyan", bold=True)) + logger.info(message, extra={"color_message": color_message}) + + def keep_subprocess_alive(self) -> None: + if self.should_exit.is_set(): + return # parent process is exiting, no need to keep subprocess alive + + for idx, process in enumerate(self.processes): + if process.is_alive(): + continue + + process.kill() # process is hung, kill it + process.join() + + if self.should_exit.is_set(): + return # pragma: full coverage + + logger.info(f"Child process [{process.pid}] died") + process = Process(self.config, self.target, self.sockets) + process.start() + self.processes[idx] = process + + def handle_signals(self) -> None: + for sig in tuple(self.signal_queue): + self.signal_queue.remove(sig) + sig_name = SIGNALS[sig] + sig_handler = getattr(self, f"handle_{sig_name.lower()}", None) + if sig_handler is not None: + sig_handler() + else: # pragma: no cover + logger.debug(f"Received signal {sig_name}, but no handler is defined for it.") + + def handle_int(self) -> None: + logger.info("Received SIGINT, exiting.") + self.should_exit.set() + + def handle_term(self) -> None: + logger.info("Received SIGTERM, exiting.") + self.should_exit.set() + + def handle_break(self) -> None: # pragma: py-not-win32 + logger.info("Received SIGBREAK, exiting.") + self.should_exit.set() + + def handle_hup(self) -> None: # pragma: py-win32 + logger.info("Received SIGHUP, restarting processes.") + self.restart_all() + + def handle_ttin(self) -> None: # pragma: py-win32 + logger.info("Received SIGTTIN, increasing the number of processes.") + self.processes_num += 1 + process = Process(self.config, self.target, self.sockets) + process.start() + self.processes.append(process) + + def handle_ttou(self) -> None: # pragma: py-win32 + logger.info("Received SIGTTOU, decreasing number of processes.") + if self.processes_num <= 1: + logger.info("Already reached one process, cannot decrease the number of processes anymore.") + return + self.processes_num -= 1 + process = self.processes.pop() + process.terminate() + process.join() diff --git a/evalkit_tf446/lib/python3.10/site-packages/uvicorn/supervisors/watchgodreload.py b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/supervisors/watchgodreload.py new file mode 100644 index 0000000000000000000000000000000000000000..6f248faa7e194e571740b27b1ee56b99e9189cbf --- /dev/null +++ b/evalkit_tf446/lib/python3.10/site-packages/uvicorn/supervisors/watchgodreload.py @@ -0,0 +1,152 @@ +from __future__ import annotations + +import logging +import warnings +from pathlib import Path +from socket import socket +from typing import TYPE_CHECKING, Callable + +from watchgod import DefaultWatcher + +from uvicorn.config import Config +from uvicorn.supervisors.basereload import BaseReload + +if TYPE_CHECKING: + import os + + DirEntry = os.DirEntry[str] + +logger = logging.getLogger("uvicorn.error") + + +class CustomWatcher(DefaultWatcher): + def __init__(self, root_path: Path, config: Config): + default_includes = ["*.py"] + self.includes = [default for default in default_includes if default not in config.reload_excludes] + self.includes.extend(config.reload_includes) + self.includes = list(set(self.includes)) + + default_excludes = [".*", ".py[cod]", ".sw.*", "~*"] + self.excludes = [default for default in default_excludes if default not in config.reload_includes] + self.excludes.extend(config.reload_excludes) + self.excludes = list(set(self.excludes)) + + self.watched_dirs: dict[str, bool] = {} + self.watched_files: dict[str, bool] = {} + self.dirs_includes = set(config.reload_dirs) + self.dirs_excludes = set(config.reload_dirs_excludes) + self.resolved_root = root_path + super().__init__(str(root_path)) + + def should_watch_file(self, entry: DirEntry) -> bool: + cached_result = self.watched_files.get(entry.path) + if cached_result is not None: + return cached_result + + entry_path = Path(entry) + + # cwd is not verified through should_watch_dir, so we need to verify here + if entry_path.parent == Path.cwd() and Path.cwd() not in self.dirs_includes: + self.watched_files[entry.path] = False + return False + for include_pattern in self.includes: + if str(entry_path).endswith(include_pattern): + self.watched_files[entry.path] = True + return True + if entry_path.match(include_pattern): + for exclude_pattern in self.excludes: + if entry_path.match(exclude_pattern): + self.watched_files[entry.path] = False + return False + self.watched_files[entry.path] = True + return True + self.watched_files[entry.path] = False + return False + + def should_watch_dir(self, entry: DirEntry) -> bool: + cached_result = self.watched_dirs.get(entry.path) + if cached_result is not None: + return cached_result + + entry_path = Path(entry) + + if entry_path in self.dirs_excludes: + self.watched_dirs[entry.path] = False + return False + + for exclude_pattern in self.excludes: + if entry_path.match(exclude_pattern): + is_watched = False + if entry_path in self.dirs_includes: + is_watched = True + + for directory in self.dirs_includes: + if directory in entry_path.parents: + is_watched = True + + if is_watched: + logger.debug( + "WatchGodReload detected a new excluded dir '%s' in '%s'; " "Adding to exclude list.", + entry_path.relative_to(self.resolved_root), + str(self.resolved_root), + ) + self.watched_dirs[entry.path] = False + self.dirs_excludes.add(entry_path) + return False + + if entry_path in self.dirs_includes: + self.watched_dirs[entry.path] = True + return True + + for directory in self.dirs_includes: + if directory in entry_path.parents: + self.watched_dirs[entry.path] = True + return True + + for include_pattern in self.includes: + if entry_path.match(include_pattern): + logger.info( + "WatchGodReload detected a new reload dir '%s' in '%s'; " "Adding to watch list.", + str(entry_path.relative_to(self.resolved_root)), + str(self.resolved_root), + ) + self.dirs_includes.add(entry_path) + self.watched_dirs[entry.path] = True + return True + + self.watched_dirs[entry.path] = False + return False + + +class WatchGodReload(BaseReload): + def __init__( + self, + config: Config, + target: Callable[[list[socket] | None], None], + sockets: list[socket], + ) -> None: + warnings.warn( + '"watchgod" is deprecated, you should switch ' "to watchfiles (`pip install watchfiles`).", + DeprecationWarning, + ) + super().__init__(config, target, sockets) + self.reloader_name = "WatchGod" + self.watchers = [] + reload_dirs = [] + for directory in config.reload_dirs: + if Path.cwd() not in directory.parents: + reload_dirs.append(directory) + if Path.cwd() not in reload_dirs: + reload_dirs.append(Path.cwd()) + for w in reload_dirs: + self.watchers.append(CustomWatcher(w.resolve(), self.config)) + + def should_restart(self) -> list[Path] | None: + self.pause() + + for watcher in self.watchers: + change = watcher.check() + if change != set(): + return list({Path(c[1]) for c in change}) + + return None