diff --git a/.gitattributes b/.gitattributes index a6344aac8c09253b3b630fb776ae94478aa0275b..4c0faf4d254244acba928944755d2ce9d0fe367e 100644 --- a/.gitattributes +++ b/.gitattributes @@ -33,3 +33,7 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text *.zip filter=lfs diff=lfs merge=lfs -text *.zst filter=lfs diff=lfs merge=lfs -text *tfevents* filter=lfs diff=lfs merge=lfs -text +python_embeded/python.exe filter=lfs diff=lfs merge=lfs -text +python_embeded/vcruntime140.dll filter=lfs diff=lfs merge=lfs -text +python_embeded/libssl-3.dll filter=lfs diff=lfs merge=lfs -text +python_embeded/sqlite3.dll filter=lfs diff=lfs merge=lfs -text diff --git a/python_embeded/Lib/site-packages/Deprecated-1.2.18.dist-info/RECORD b/python_embeded/Lib/site-packages/Deprecated-1.2.18.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..78905cb69866df3513721812739c516170eaa16a --- /dev/null +++ b/python_embeded/Lib/site-packages/Deprecated-1.2.18.dist-info/RECORD @@ -0,0 +1,12 @@ +Deprecated-1.2.18.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +Deprecated-1.2.18.dist-info/LICENSE.rst,sha256=HoPt0VvkGbXVveNy4yXlJ_9PmRX1SOfHUxS0H2aZ6Dw,1081 +Deprecated-1.2.18.dist-info/METADATA,sha256=4CrUw5Bl8_NsBuZYe0Nw-mIwQnVpT1CnmBYU9BqOuq8,5725 +Deprecated-1.2.18.dist-info/RECORD,, +Deprecated-1.2.18.dist-info/WHEEL,sha256=9Hm2OB-j1QcCUq9Jguht7ayGIIZBRTdOXD1qg9cCgPM,109 +Deprecated-1.2.18.dist-info/top_level.txt,sha256=nHbOYawKPQQE5lQl-toUB1JBRJjUyn_m_Mb8RVJ0RjA,11 +deprecated/__init__.py,sha256=yZNbmDKXF4PLtp_Ikdb_9ObJLkHuFSUHvqidFTKKGFM,351 +deprecated/__pycache__/__init__.cpython-312.pyc,, +deprecated/__pycache__/classic.cpython-312.pyc,, +deprecated/__pycache__/sphinx.cpython-312.pyc,, +deprecated/classic.py,sha256=7WXOt4Vf1NhrUznm8ypjS50CMyAdZwrGT58Lhb8fW14,10609 +deprecated/sphinx.py,sha256=cOKnXbDyFAwDr5O7HBEpgQrx-J-qfp57sfdK_LabDxs,11109 diff --git a/python_embeded/Lib/site-packages/Deprecated-1.2.18.dist-info/WHEEL b/python_embeded/Lib/site-packages/Deprecated-1.2.18.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..eaea6f3b57e8165ab7d2673900a9939348ee5e42 --- /dev/null +++ b/python_embeded/Lib/site-packages/Deprecated-1.2.18.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: setuptools (75.8.0) +Root-Is-Purelib: true +Tag: py2-none-any +Tag: py3-none-any + diff --git a/python_embeded/Lib/site-packages/click-8.2.1.dist-info/INSTALLER b/python_embeded/Lib/site-packages/click-8.2.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/python_embeded/Lib/site-packages/click-8.2.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/python_embeded/Lib/site-packages/click-8.2.1.dist-info/METADATA b/python_embeded/Lib/site-packages/click-8.2.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..e6c05af4a78cabdf5689f3f6f7fd57304d8a0eb1 --- /dev/null +++ b/python_embeded/Lib/site-packages/click-8.2.1.dist-info/METADATA @@ -0,0 +1,82 @@ +Metadata-Version: 2.4 +Name: click +Version: 8.2.1 +Summary: Composable command line interface toolkit +Maintainer-email: Pallets +Requires-Python: >=3.10 +Description-Content-Type: text/markdown +License-Expression: BSD-3-Clause +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Typing :: Typed +License-File: LICENSE.txt +Requires-Dist: colorama; platform_system == 'Windows' +Project-URL: Changes, https://click.palletsprojects.com/page/changes/ +Project-URL: Chat, https://discord.gg/pallets +Project-URL: Documentation, https://click.palletsprojects.com/ +Project-URL: Donate, https://palletsprojects.com/donate +Project-URL: Source, https://github.com/pallets/click/ + +# $ click_ + +Click is a Python package for creating beautiful command line interfaces +in a composable way with as little code as necessary. It's the "Command +Line Interface Creation Kit". It's highly configurable but comes with +sensible defaults out of the box. + +It aims to make the process of writing command line tools quick and fun +while also preventing any frustration caused by the inability to +implement an intended CLI API. + +Click in three points: + +- Arbitrary nesting of commands +- Automatic help page generation +- Supports lazy loading of subcommands at runtime + + +## A Simple Example + +```python +import click + +@click.command() +@click.option("--count", default=1, help="Number of greetings.") +@click.option("--name", prompt="Your name", help="The person to greet.") +def hello(count, name): + """Simple program that greets NAME for a total of COUNT times.""" + for _ in range(count): + click.echo(f"Hello, {name}!") + +if __name__ == '__main__': + hello() +``` + +``` +$ python hello.py --count=3 +Your name: Click +Hello, Click! +Hello, Click! +Hello, Click! +``` + + +## Donate + +The Pallets organization develops and supports Click and other popular +packages. In order to grow the community of contributors and users, and +allow the maintainers to devote more time to the projects, [please +donate today][]. + +[please donate today]: https://palletsprojects.com/donate + +## Contributing + +See our [detailed contributing documentation][contrib] for many ways to +contribute, including reporting issues, requesting features, asking or answering +questions, and making PRs. + +[contrib]: https://palletsprojects.com/contributing/ + diff --git a/python_embeded/Lib/site-packages/click-8.2.1.dist-info/RECORD b/python_embeded/Lib/site-packages/click-8.2.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..61f4cd2b07ca70728ec4af378c37dd7e62cccddd --- /dev/null +++ b/python_embeded/Lib/site-packages/click-8.2.1.dist-info/RECORD @@ -0,0 +1,38 @@ +click-8.2.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +click-8.2.1.dist-info/METADATA,sha256=dI1MbhHTLoKD2tNCCGnx9rK2gok23HDNylFeLKdLSik,2471 +click-8.2.1.dist-info/RECORD,, +click-8.2.1.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82 +click-8.2.1.dist-info/licenses/LICENSE.txt,sha256=morRBqOU6FO_4h9C9OctWSgZoigF2ZG18ydQKSkrZY0,1475 +click/__init__.py,sha256=6YyS1aeyknZ0LYweWozNZy0A9nZ_11wmYIhv3cbQrYo,4473 +click/__pycache__/__init__.cpython-312.pyc,, +click/__pycache__/_compat.cpython-312.pyc,, +click/__pycache__/_termui_impl.cpython-312.pyc,, +click/__pycache__/_textwrap.cpython-312.pyc,, +click/__pycache__/_winconsole.cpython-312.pyc,, +click/__pycache__/core.cpython-312.pyc,, +click/__pycache__/decorators.cpython-312.pyc,, +click/__pycache__/exceptions.cpython-312.pyc,, +click/__pycache__/formatting.cpython-312.pyc,, +click/__pycache__/globals.cpython-312.pyc,, +click/__pycache__/parser.cpython-312.pyc,, +click/__pycache__/shell_completion.cpython-312.pyc,, +click/__pycache__/termui.cpython-312.pyc,, +click/__pycache__/testing.cpython-312.pyc,, +click/__pycache__/types.cpython-312.pyc,, +click/__pycache__/utils.cpython-312.pyc,, +click/_compat.py,sha256=v3xBZkFbvA1BXPRkFfBJc6-pIwPI7345m-kQEnpVAs4,18693 +click/_termui_impl.py,sha256=ASXhLi9IQIc0Js9KQSS-3-SLZcPet3VqysBf9WgbbpI,26712 +click/_textwrap.py,sha256=BOae0RQ6vg3FkNgSJyOoGzG1meGMxJ_ukWVZKx_v-0o,1400 +click/_winconsole.py,sha256=_vxUuUaxwBhoR0vUWCNuHY8VUefiMdCIyU2SXPqoF-A,8465 +click/core.py,sha256=gUhpNS9cFBGdEXXdisGVG-eRvGf49RTyFagxulqwdFw,117343 +click/decorators.py,sha256=5P7abhJtAQYp_KHgjUvhMv464ERwOzrv2enNknlwHyQ,18461 +click/exceptions.py,sha256=1rdtXgHJ1b3OjGkN-UpXB9t_HCBihJvh_DtpmLmwn9s,9891 +click/formatting.py,sha256=Bhqx4QXdKQ9W4WKknIwj5KPKFmtduGOuGq1yw_THLZ8,9726 +click/globals.py,sha256=gM-Nh6A4M0HB_SgkaF5M4ncGGMDHc_flHXu9_oh4GEU,1923 +click/parser.py,sha256=nU1Ah2p11q29ul1vNdU9swPo_PUuKrxU6YXToi71q1c,18979 +click/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +click/shell_completion.py,sha256=CQSGdjgun4ORbOZrXP0CVhEtPx4knsufOkRsDiK64cM,19857 +click/termui.py,sha256=vAYrKC2a7f_NfEIhAThEVYfa__ib5XQbTSCGtJlABRA,30847 +click/testing.py,sha256=2eLdAaCJCGToP5Tw-XN8JjrDb3wbJIfARxg3d0crW5M,18702 +click/types.py,sha256=KBTRxN28cR1VZ5mb9iJX98MQSw_p9SGzljqfEI8z5Tw,38389 +click/utils.py,sha256=b1Mm-usEDBHtEwcPltPIn3zSK4nw2KTp5GC7_oSTlLo,20245 diff --git a/python_embeded/Lib/site-packages/click/__init__.py b/python_embeded/Lib/site-packages/click/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1aa547c57af68954b3bcd6012873881030e53d91 --- /dev/null +++ b/python_embeded/Lib/site-packages/click/__init__.py @@ -0,0 +1,123 @@ +""" +Click is a simple Python module inspired by the stdlib optparse to make +writing command line scripts fun. Unlike other modules, it's based +around a simple API that does not come with too much magic and is +composable. +""" + +from __future__ import annotations + +from .core import Argument as Argument +from .core import Command as Command +from .core import CommandCollection as CommandCollection +from .core import Context as Context +from .core import Group as Group +from .core import Option as Option +from .core import Parameter as Parameter +from .decorators import argument as argument +from .decorators import command as command +from .decorators import confirmation_option as confirmation_option +from .decorators import group as group +from .decorators import help_option as help_option +from .decorators import make_pass_decorator as make_pass_decorator +from .decorators import option as option +from .decorators import pass_context as pass_context +from .decorators import pass_obj as pass_obj +from .decorators import password_option as password_option +from .decorators import version_option as version_option +from .exceptions import Abort as Abort +from .exceptions import BadArgumentUsage as BadArgumentUsage +from .exceptions import BadOptionUsage as BadOptionUsage +from .exceptions import BadParameter as BadParameter +from .exceptions import ClickException as ClickException +from .exceptions import FileError as FileError +from .exceptions import MissingParameter as MissingParameter +from .exceptions import NoSuchOption as NoSuchOption +from .exceptions import UsageError as UsageError +from .formatting import HelpFormatter as HelpFormatter +from .formatting import wrap_text as wrap_text +from .globals import get_current_context as get_current_context +from .termui import clear as clear +from .termui import confirm as confirm +from .termui import echo_via_pager as echo_via_pager +from .termui import edit as edit +from .termui import getchar as getchar +from .termui import launch as launch +from .termui import pause as pause +from .termui import progressbar as progressbar +from .termui import prompt as prompt +from .termui import secho as secho +from .termui import style as style +from .termui import unstyle as unstyle +from .types import BOOL as BOOL +from .types import Choice as Choice +from .types import DateTime as DateTime +from .types import File as File +from .types import FLOAT as FLOAT +from .types import FloatRange as FloatRange +from .types import INT as INT +from .types import IntRange as IntRange +from .types import ParamType as ParamType +from .types import Path as Path +from .types import STRING as STRING +from .types import Tuple as Tuple +from .types import UNPROCESSED as UNPROCESSED +from .types import UUID as UUID +from .utils import echo as echo +from .utils import format_filename as format_filename +from .utils import get_app_dir as get_app_dir +from .utils import get_binary_stream as get_binary_stream +from .utils import get_text_stream as get_text_stream +from .utils import open_file as open_file + + +def __getattr__(name: str) -> object: + import warnings + + if name == "BaseCommand": + from .core import _BaseCommand + + warnings.warn( + "'BaseCommand' is deprecated and will be removed in Click 9.0. Use" + " 'Command' instead.", + DeprecationWarning, + stacklevel=2, + ) + return _BaseCommand + + if name == "MultiCommand": + from .core import _MultiCommand + + warnings.warn( + "'MultiCommand' is deprecated and will be removed in Click 9.0. Use" + " 'Group' instead.", + DeprecationWarning, + stacklevel=2, + ) + return _MultiCommand + + if name == "OptionParser": + from .parser import _OptionParser + + warnings.warn( + "'OptionParser' is deprecated and will be removed in Click 9.0. The" + " old parser is available in 'optparse'.", + DeprecationWarning, + stacklevel=2, + ) + return _OptionParser + + if name == "__version__": + import importlib.metadata + import warnings + + warnings.warn( + "The '__version__' attribute is deprecated and will be removed in" + " Click 9.1. Use feature detection or" + " 'importlib.metadata.version(\"click\")' instead.", + DeprecationWarning, + stacklevel=2, + ) + return importlib.metadata.version("click") + + raise AttributeError(name) diff --git a/python_embeded/Lib/site-packages/click/_compat.py b/python_embeded/Lib/site-packages/click/_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..f2726b93afe2ed69ba20d8e709c9cbd22b9d2339 --- /dev/null +++ b/python_embeded/Lib/site-packages/click/_compat.py @@ -0,0 +1,622 @@ +from __future__ import annotations + +import codecs +import collections.abc as cabc +import io +import os +import re +import sys +import typing as t +from types import TracebackType +from weakref import WeakKeyDictionary + +CYGWIN = sys.platform.startswith("cygwin") +WIN = sys.platform.startswith("win") +auto_wrap_for_ansi: t.Callable[[t.TextIO], t.TextIO] | None = None +_ansi_re = re.compile(r"\033\[[;?0-9]*[a-zA-Z]") + + +def _make_text_stream( + stream: t.BinaryIO, + encoding: str | None, + errors: str | None, + force_readable: bool = False, + force_writable: bool = False, +) -> t.TextIO: + if encoding is None: + encoding = get_best_encoding(stream) + if errors is None: + errors = "replace" + return _NonClosingTextIOWrapper( + stream, + encoding, + errors, + line_buffering=True, + force_readable=force_readable, + force_writable=force_writable, + ) + + +def is_ascii_encoding(encoding: str) -> bool: + """Checks if a given encoding is ascii.""" + try: + return codecs.lookup(encoding).name == "ascii" + except LookupError: + return False + + +def get_best_encoding(stream: t.IO[t.Any]) -> str: + """Returns the default stream encoding if not found.""" + rv = getattr(stream, "encoding", None) or sys.getdefaultencoding() + if is_ascii_encoding(rv): + return "utf-8" + return rv + + +class _NonClosingTextIOWrapper(io.TextIOWrapper): + def __init__( + self, + stream: t.BinaryIO, + encoding: str | None, + errors: str | None, + force_readable: bool = False, + force_writable: bool = False, + **extra: t.Any, + ) -> None: + self._stream = stream = t.cast( + t.BinaryIO, _FixupStream(stream, force_readable, force_writable) + ) + super().__init__(stream, encoding, errors, **extra) + + def __del__(self) -> None: + try: + self.detach() + except Exception: + pass + + def isatty(self) -> bool: + # https://bitbucket.org/pypy/pypy/issue/1803 + return self._stream.isatty() + + +class _FixupStream: + """The new io interface needs more from streams than streams + traditionally implement. As such, this fix-up code is necessary in + some circumstances. + + The forcing of readable and writable flags are there because some tools + put badly patched objects on sys (one such offender are certain version + of jupyter notebook). + """ + + def __init__( + self, + stream: t.BinaryIO, + force_readable: bool = False, + force_writable: bool = False, + ): + self._stream = stream + self._force_readable = force_readable + self._force_writable = force_writable + + def __getattr__(self, name: str) -> t.Any: + return getattr(self._stream, name) + + def read1(self, size: int) -> bytes: + f = getattr(self._stream, "read1", None) + + if f is not None: + return t.cast(bytes, f(size)) + + return self._stream.read(size) + + def readable(self) -> bool: + if self._force_readable: + return True + x = getattr(self._stream, "readable", None) + if x is not None: + return t.cast(bool, x()) + try: + self._stream.read(0) + except Exception: + return False + return True + + def writable(self) -> bool: + if self._force_writable: + return True + x = getattr(self._stream, "writable", None) + if x is not None: + return t.cast(bool, x()) + try: + self._stream.write(b"") + except Exception: + try: + self._stream.write(b"") + except Exception: + return False + return True + + def seekable(self) -> bool: + x = getattr(self._stream, "seekable", None) + if x is not None: + return t.cast(bool, x()) + try: + self._stream.seek(self._stream.tell()) + except Exception: + return False + return True + + +def _is_binary_reader(stream: t.IO[t.Any], default: bool = False) -> bool: + try: + return isinstance(stream.read(0), bytes) + except Exception: + return default + # This happens in some cases where the stream was already + # closed. In this case, we assume the default. + + +def _is_binary_writer(stream: t.IO[t.Any], default: bool = False) -> bool: + try: + stream.write(b"") + except Exception: + try: + stream.write("") + return False + except Exception: + pass + return default + return True + + +def _find_binary_reader(stream: t.IO[t.Any]) -> t.BinaryIO | None: + # We need to figure out if the given stream is already binary. + # This can happen because the official docs recommend detaching + # the streams to get binary streams. Some code might do this, so + # we need to deal with this case explicitly. + if _is_binary_reader(stream, False): + return t.cast(t.BinaryIO, stream) + + buf = getattr(stream, "buffer", None) + + # Same situation here; this time we assume that the buffer is + # actually binary in case it's closed. + if buf is not None and _is_binary_reader(buf, True): + return t.cast(t.BinaryIO, buf) + + return None + + +def _find_binary_writer(stream: t.IO[t.Any]) -> t.BinaryIO | None: + # We need to figure out if the given stream is already binary. + # This can happen because the official docs recommend detaching + # the streams to get binary streams. Some code might do this, so + # we need to deal with this case explicitly. + if _is_binary_writer(stream, False): + return t.cast(t.BinaryIO, stream) + + buf = getattr(stream, "buffer", None) + + # Same situation here; this time we assume that the buffer is + # actually binary in case it's closed. + if buf is not None and _is_binary_writer(buf, True): + return t.cast(t.BinaryIO, buf) + + return None + + +def _stream_is_misconfigured(stream: t.TextIO) -> bool: + """A stream is misconfigured if its encoding is ASCII.""" + # If the stream does not have an encoding set, we assume it's set + # to ASCII. This appears to happen in certain unittest + # environments. It's not quite clear what the correct behavior is + # but this at least will force Click to recover somehow. + return is_ascii_encoding(getattr(stream, "encoding", None) or "ascii") + + +def _is_compat_stream_attr(stream: t.TextIO, attr: str, value: str | None) -> bool: + """A stream attribute is compatible if it is equal to the + desired value or the desired value is unset and the attribute + has a value. + """ + stream_value = getattr(stream, attr, None) + return stream_value == value or (value is None and stream_value is not None) + + +def _is_compatible_text_stream( + stream: t.TextIO, encoding: str | None, errors: str | None +) -> bool: + """Check if a stream's encoding and errors attributes are + compatible with the desired values. + """ + return _is_compat_stream_attr( + stream, "encoding", encoding + ) and _is_compat_stream_attr(stream, "errors", errors) + + +def _force_correct_text_stream( + text_stream: t.IO[t.Any], + encoding: str | None, + errors: str | None, + is_binary: t.Callable[[t.IO[t.Any], bool], bool], + find_binary: t.Callable[[t.IO[t.Any]], t.BinaryIO | None], + force_readable: bool = False, + force_writable: bool = False, +) -> t.TextIO: + if is_binary(text_stream, False): + binary_reader = t.cast(t.BinaryIO, text_stream) + else: + text_stream = t.cast(t.TextIO, text_stream) + # If the stream looks compatible, and won't default to a + # misconfigured ascii encoding, return it as-is. + if _is_compatible_text_stream(text_stream, encoding, errors) and not ( + encoding is None and _stream_is_misconfigured(text_stream) + ): + return text_stream + + # Otherwise, get the underlying binary reader. + possible_binary_reader = find_binary(text_stream) + + # If that's not possible, silently use the original reader + # and get mojibake instead of exceptions. + if possible_binary_reader is None: + return text_stream + + binary_reader = possible_binary_reader + + # Default errors to replace instead of strict in order to get + # something that works. + if errors is None: + errors = "replace" + + # Wrap the binary stream in a text stream with the correct + # encoding parameters. + return _make_text_stream( + binary_reader, + encoding, + errors, + force_readable=force_readable, + force_writable=force_writable, + ) + + +def _force_correct_text_reader( + text_reader: t.IO[t.Any], + encoding: str | None, + errors: str | None, + force_readable: bool = False, +) -> t.TextIO: + return _force_correct_text_stream( + text_reader, + encoding, + errors, + _is_binary_reader, + _find_binary_reader, + force_readable=force_readable, + ) + + +def _force_correct_text_writer( + text_writer: t.IO[t.Any], + encoding: str | None, + errors: str | None, + force_writable: bool = False, +) -> t.TextIO: + return _force_correct_text_stream( + text_writer, + encoding, + errors, + _is_binary_writer, + _find_binary_writer, + force_writable=force_writable, + ) + + +def get_binary_stdin() -> t.BinaryIO: + reader = _find_binary_reader(sys.stdin) + if reader is None: + raise RuntimeError("Was not able to determine binary stream for sys.stdin.") + return reader + + +def get_binary_stdout() -> t.BinaryIO: + writer = _find_binary_writer(sys.stdout) + if writer is None: + raise RuntimeError("Was not able to determine binary stream for sys.stdout.") + return writer + + +def get_binary_stderr() -> t.BinaryIO: + writer = _find_binary_writer(sys.stderr) + if writer is None: + raise RuntimeError("Was not able to determine binary stream for sys.stderr.") + return writer + + +def get_text_stdin(encoding: str | None = None, errors: str | None = None) -> t.TextIO: + rv = _get_windows_console_stream(sys.stdin, encoding, errors) + if rv is not None: + return rv + return _force_correct_text_reader(sys.stdin, encoding, errors, force_readable=True) + + +def get_text_stdout(encoding: str | None = None, errors: str | None = None) -> t.TextIO: + rv = _get_windows_console_stream(sys.stdout, encoding, errors) + if rv is not None: + return rv + return _force_correct_text_writer(sys.stdout, encoding, errors, force_writable=True) + + +def get_text_stderr(encoding: str | None = None, errors: str | None = None) -> t.TextIO: + rv = _get_windows_console_stream(sys.stderr, encoding, errors) + if rv is not None: + return rv + return _force_correct_text_writer(sys.stderr, encoding, errors, force_writable=True) + + +def _wrap_io_open( + file: str | os.PathLike[str] | int, + mode: str, + encoding: str | None, + errors: str | None, +) -> t.IO[t.Any]: + """Handles not passing ``encoding`` and ``errors`` in binary mode.""" + if "b" in mode: + return open(file, mode) + + return open(file, mode, encoding=encoding, errors=errors) + + +def open_stream( + filename: str | os.PathLike[str], + mode: str = "r", + encoding: str | None = None, + errors: str | None = "strict", + atomic: bool = False, +) -> tuple[t.IO[t.Any], bool]: + binary = "b" in mode + filename = os.fspath(filename) + + # Standard streams first. These are simple because they ignore the + # atomic flag. Use fsdecode to handle Path("-"). + if os.fsdecode(filename) == "-": + if any(m in mode for m in ["w", "a", "x"]): + if binary: + return get_binary_stdout(), False + return get_text_stdout(encoding=encoding, errors=errors), False + if binary: + return get_binary_stdin(), False + return get_text_stdin(encoding=encoding, errors=errors), False + + # Non-atomic writes directly go out through the regular open functions. + if not atomic: + return _wrap_io_open(filename, mode, encoding, errors), True + + # Some usability stuff for atomic writes + if "a" in mode: + raise ValueError( + "Appending to an existing file is not supported, because that" + " would involve an expensive `copy`-operation to a temporary" + " file. Open the file in normal `w`-mode and copy explicitly" + " if that's what you're after." + ) + if "x" in mode: + raise ValueError("Use the `overwrite`-parameter instead.") + if "w" not in mode: + raise ValueError("Atomic writes only make sense with `w`-mode.") + + # Atomic writes are more complicated. They work by opening a file + # as a proxy in the same folder and then using the fdopen + # functionality to wrap it in a Python file. Then we wrap it in an + # atomic file that moves the file over on close. + import errno + import random + + try: + perm: int | None = os.stat(filename).st_mode + except OSError: + perm = None + + flags = os.O_RDWR | os.O_CREAT | os.O_EXCL + + if binary: + flags |= getattr(os, "O_BINARY", 0) + + while True: + tmp_filename = os.path.join( + os.path.dirname(filename), + f".__atomic-write{random.randrange(1 << 32):08x}", + ) + try: + fd = os.open(tmp_filename, flags, 0o666 if perm is None else perm) + break + except OSError as e: + if e.errno == errno.EEXIST or ( + os.name == "nt" + and e.errno == errno.EACCES + and os.path.isdir(e.filename) + and os.access(e.filename, os.W_OK) + ): + continue + raise + + if perm is not None: + os.chmod(tmp_filename, perm) # in case perm includes bits in umask + + f = _wrap_io_open(fd, mode, encoding, errors) + af = _AtomicFile(f, tmp_filename, os.path.realpath(filename)) + return t.cast(t.IO[t.Any], af), True + + +class _AtomicFile: + def __init__(self, f: t.IO[t.Any], tmp_filename: str, real_filename: str) -> None: + self._f = f + self._tmp_filename = tmp_filename + self._real_filename = real_filename + self.closed = False + + @property + def name(self) -> str: + return self._real_filename + + def close(self, delete: bool = False) -> None: + if self.closed: + return + self._f.close() + os.replace(self._tmp_filename, self._real_filename) + self.closed = True + + def __getattr__(self, name: str) -> t.Any: + return getattr(self._f, name) + + def __enter__(self) -> _AtomicFile: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + tb: TracebackType | None, + ) -> None: + self.close(delete=exc_type is not None) + + def __repr__(self) -> str: + return repr(self._f) + + +def strip_ansi(value: str) -> str: + return _ansi_re.sub("", value) + + +def _is_jupyter_kernel_output(stream: t.IO[t.Any]) -> bool: + while isinstance(stream, (_FixupStream, _NonClosingTextIOWrapper)): + stream = stream._stream + + return stream.__class__.__module__.startswith("ipykernel.") + + +def should_strip_ansi( + stream: t.IO[t.Any] | None = None, color: bool | None = None +) -> bool: + if color is None: + if stream is None: + stream = sys.stdin + return not isatty(stream) and not _is_jupyter_kernel_output(stream) + return not color + + +# On Windows, wrap the output streams with colorama to support ANSI +# color codes. +# NOTE: double check is needed so mypy does not analyze this on Linux +if sys.platform.startswith("win") and WIN: + from ._winconsole import _get_windows_console_stream + + def _get_argv_encoding() -> str: + import locale + + return locale.getpreferredencoding() + + _ansi_stream_wrappers: cabc.MutableMapping[t.TextIO, t.TextIO] = WeakKeyDictionary() + + def auto_wrap_for_ansi(stream: t.TextIO, color: bool | None = None) -> t.TextIO: + """Support ANSI color and style codes on Windows by wrapping a + stream with colorama. + """ + try: + cached = _ansi_stream_wrappers.get(stream) + except Exception: + cached = None + + if cached is not None: + return cached + + import colorama + + strip = should_strip_ansi(stream, color) + ansi_wrapper = colorama.AnsiToWin32(stream, strip=strip) + rv = t.cast(t.TextIO, ansi_wrapper.stream) + _write = rv.write + + def _safe_write(s: str) -> int: + try: + return _write(s) + except BaseException: + ansi_wrapper.reset_all() + raise + + rv.write = _safe_write # type: ignore[method-assign] + + try: + _ansi_stream_wrappers[stream] = rv + except Exception: + pass + + return rv + +else: + + def _get_argv_encoding() -> str: + return getattr(sys.stdin, "encoding", None) or sys.getfilesystemencoding() + + def _get_windows_console_stream( + f: t.TextIO, encoding: str | None, errors: str | None + ) -> t.TextIO | None: + return None + + +def term_len(x: str) -> int: + return len(strip_ansi(x)) + + +def isatty(stream: t.IO[t.Any]) -> bool: + try: + return stream.isatty() + except Exception: + return False + + +def _make_cached_stream_func( + src_func: t.Callable[[], t.TextIO | None], + wrapper_func: t.Callable[[], t.TextIO], +) -> t.Callable[[], t.TextIO | None]: + cache: cabc.MutableMapping[t.TextIO, t.TextIO] = WeakKeyDictionary() + + def func() -> t.TextIO | None: + stream = src_func() + + if stream is None: + return None + + try: + rv = cache.get(stream) + except Exception: + rv = None + if rv is not None: + return rv + rv = wrapper_func() + try: + cache[stream] = rv + except Exception: + pass + return rv + + return func + + +_default_text_stdin = _make_cached_stream_func(lambda: sys.stdin, get_text_stdin) +_default_text_stdout = _make_cached_stream_func(lambda: sys.stdout, get_text_stdout) +_default_text_stderr = _make_cached_stream_func(lambda: sys.stderr, get_text_stderr) + + +binary_streams: cabc.Mapping[str, t.Callable[[], t.BinaryIO]] = { + "stdin": get_binary_stdin, + "stdout": get_binary_stdout, + "stderr": get_binary_stderr, +} + +text_streams: cabc.Mapping[str, t.Callable[[str | None, str | None], t.TextIO]] = { + "stdin": get_text_stdin, + "stdout": get_text_stdout, + "stderr": get_text_stderr, +} diff --git a/python_embeded/Lib/site-packages/color_matcher-0.6.0.dist-info/INSTALLER b/python_embeded/Lib/site-packages/color_matcher-0.6.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/python_embeded/Lib/site-packages/color_matcher-0.6.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/python_embeded/Lib/site-packages/color_matcher-0.6.0.dist-info/LICENSE b/python_embeded/Lib/site-packages/color_matcher-0.6.0.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f288702d2fa16d3cdf0035b15a9fcbc552cd88e7 --- /dev/null +++ b/python_embeded/Lib/site-packages/color_matcher-0.6.0.dist-info/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/python_embeded/Lib/site-packages/color_matcher-0.6.0.dist-info/METADATA b/python_embeded/Lib/site-packages/color_matcher-0.6.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..0f226581a5ee5f2d56054c9617402b2cf2f2cc4e --- /dev/null +++ b/python_embeded/Lib/site-packages/color_matcher-0.6.0.dist-info/METADATA @@ -0,0 +1,24 @@ +Metadata-Version: 2.1 +Name: color-matcher +Version: 0.6.0 +Summary: Package enabling color transfer across images +Home-page: http://github.com/hahnec/color-matcher +Author: Christopher Hahne +Author-email: inbox@christopherhahne.de +License: GNU GPL V3.0 +Keywords: color match histogram matching image colour transfer monge kantorovich mkl pitie reinhardrecolor re-color recolour re-colour paintings film movie sequence automatic grading color-grading colour-grading equalize equalise equalization equalisation light-field lightfield stop-motion stopmotion +Requires-Python: >=3 +Description-Content-Type: text/x-rst +License-File: LICENSE +Requires-Dist: ddt +Requires-Dist: docutils +Requires-Dist: imageio +Requires-Dist: matplotlib +Requires-Dist: numpy >=1.21 +Requires-Dist: packaging >=24.2 + +color-matcher enables color transfer across images which comes in handy for automatic color-grading +of photographs, paintings and film sequences as well as light-field and stopmotion corrections. The methods behind +the mappings are based on the approach from Reinhard et al., the Monge-Kantorovich Linearization (MKL) as proposed by +Pitie et al. and our analytical solution to a Multi-Variate Gaussian Distribution (MVGD) transfer in conjunction with +classical histogram matching. As shown below our HM-MVGD-HM compound outperforms existing methods. diff --git a/python_embeded/Lib/site-packages/color_matcher-0.6.0.dist-info/WHEEL b/python_embeded/Lib/site-packages/color_matcher-0.6.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..98c0d20b7a64f4f998d7913e1d38a05dba20916c --- /dev/null +++ b/python_embeded/Lib/site-packages/color_matcher-0.6.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.42.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/python_embeded/Lib/site-packages/color_matcher-0.6.0.dist-info/entry_points.txt b/python_embeded/Lib/site-packages/color_matcher-0.6.0.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..85eadb40790f091fb2355ff8638c97d4fc997c64 --- /dev/null +++ b/python_embeded/Lib/site-packages/color_matcher-0.6.0.dist-info/entry_points.txt @@ -0,0 +1,2 @@ +[console_scripts] +color-matcher = color_matcher.bin.cli:main diff --git a/python_embeded/Lib/site-packages/color_matcher-0.6.0.dist-info/top_level.txt b/python_embeded/Lib/site-packages/color_matcher-0.6.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..23cd4350a518f647630f0d3595d13bd52c84ad95 --- /dev/null +++ b/python_embeded/Lib/site-packages/color_matcher-0.6.0.dist-info/top_level.txt @@ -0,0 +1,2 @@ +color_matcher +tests diff --git a/python_embeded/Lib/site-packages/color_matcher/__init__.py b/python_embeded/Lib/site-packages/color_matcher/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..72ef4f779681ece2a86ec17e33654640d3e8451b --- /dev/null +++ b/python_embeded/Lib/site-packages/color_matcher/__init__.py @@ -0,0 +1,25 @@ +#!/usr/bin/env python + +__author__ = "Christopher Hahne" +__email__ = "inbox@christopherhahne.de" +__license__ = """ +Copyright (c) 2020 Christopher Hahne + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + You should have received a copy of the GNU General Public License + along with this program. If not, see . +""" + +__version__ = '0.6.0' + +from .top_level import ColorMatcher +from .hist_matcher import HistogramMatcher +from .mvgd_matcher import TransferMVGD +from .reinhard_matcher import ReinhardMatcher +from .baseclass import MatcherBaseclass diff --git a/python_embeded/Lib/site-packages/color_matcher/baseclass.py b/python_embeded/Lib/site-packages/color_matcher/baseclass.py new file mode 100644 index 0000000000000000000000000000000000000000..2273c22a6ec53f1bb9b0de27f2f0a13daa62e74b --- /dev/null +++ b/python_embeded/Lib/site-packages/color_matcher/baseclass.py @@ -0,0 +1,105 @@ +#!/usr/bin/env python + +__author__ = "Christopher Hahne" +__email__ = "inbox@christopherhahne.de" +__license__ = """ +Copyright (c) 2020 Christopher Hahne + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + You should have received a copy of the GNU General Public License + along with this program. If not, see . +""" + +import numpy as np +import warnings + + +class MatcherBaseclass(object): + + def __init__(self, *args, **kwargs): + + self._src = None + self._ref = None + self._funs = [] + + if len(args) == 2: + self._src = args[0] + self._ref = args[1] + + if bool(kwargs): + self._src = kwargs['src'] if 'src' in kwargs else self._src + self._ref = kwargs['ref'] if 'ref' in kwargs else self._ref + + def validate_img_dims(self): + """ + This function validates the image dimensions. It throws an exception if the dimension are unequal to 2 or 3. + """ + + # add third image dimension for monochromatic images + self._src = self._src[..., np.newaxis] if len(self._src.shape) == 2 else self._src + self._ref = self._ref[..., np.newaxis] if len(self._ref.shape) == 2 else self._ref + + if len(self._src.shape) not in (2, 3) or len(self._ref.shape) not in (2, 3): + raise BaseException('Each image must have 2 or 3 dimensions') + + return True + + def validate_color_chs(self): + """ + This function checks whether provided images consist of a valid number of color channels. + """ + + if len(self._src.shape) == 3 or len(self._ref.shape) == 3: + if self._src.shape[2] > 4 or self._ref.shape[2] > 4: + raise BaseException('Each image cannot have more than 4 color channels') + elif self._src.shape[2] == 3 and self._ref.shape[2] == 4: + self._ref = self._ref[..., :3] + elif self._src.shape[2] == 4 and self._ref.shape[2] == 3: + self._src = self._src[..., :3] + elif self._src.shape[2] == 1 and self._ref.shape[2] == 3: + self._ref = self.rgb2gray(self._ref) + elif self._src.shape[2] == 3 and self._ref.shape[2] == 1: + self._src = self.rgb2gray(self._src) + + if self._src.shape[2] == 1 and self._ref.shape[2] == 1: + # restrict monochromatic transfer to histogram matching + self._funs = [self.hist_match] + warnings.warn('Transfer restricted to histogram matching due to monochromatic input') + + return True + + @staticmethod + def rgb2gray(rgb: np.ndarray = None, standard: str = 'HDTV') -> np.ndarray: + """ Convert RGB color space to monochromatic color space + + :param rgb: input array in red, green and blue (RGB) space + :type rgb: :class:`~numpy:numpy.ndarray` + :param standard: option that determines whether head- and footroom are excluded ('HDTV') or considered otherwise + :type standard: :class:`string` + :return: array in monochromatic space + :rtype: ~numpy:np.ndarray + + """ + + # store shape + shape = rgb.shape + + # reshape image to channel vectors + rgb = rgb.reshape(-1, 3).T + + # choose standard + mat = np.array([0.2126, 0.7152, 0.0722]) if standard == 'HDTV' else np.array([0.299, 0.587, 0.114]) + + # convert to gray + arr = np.dot(mat, rgb) + + # reshape to 2-D image + arr = arr.reshape(shape[:2] + (1,)) + + return arr diff --git a/python_embeded/Lib/site-packages/color_matcher/hist_matcher.py b/python_embeded/Lib/site-packages/color_matcher/hist_matcher.py new file mode 100644 index 0000000000000000000000000000000000000000..0a27dd200f0763196971686eb99cf2118312b7f6 --- /dev/null +++ b/python_embeded/Lib/site-packages/color_matcher/hist_matcher.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python + +__author__ = "Christopher Hahne" +__email__ = "info@christopherhahne.de" +__license__ = """ + Copyright (c) 2020 Christopher Hahne + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +""" + +import numpy as np + +from .baseclass import MatcherBaseclass + + +class HistogramMatcher(MatcherBaseclass): + + def __init__(self, *args, **kwargs): + super(HistogramMatcher, self).__init__(*args, **kwargs) + + def hist_match(self, src: np.ndarray = None, ref: np.ndarray = None) -> np.ndarray: + """ + + This function conducts channel-wise histogram matching which is invariant of image resolutions, + but requires the same number of color channels in both images. + + :param src: Source image that requires transfer + :param ref: Palette image which serves as reference + :param res: Resulting image after the mapping + + :type src: :class:`~numpy:numpy.ndarray` + :type ref: :class:`~numpy:numpy.ndarray` + :type res: :class:`~numpy:numpy.ndarray` + + :return: **res** + :rtype: np.ndarray + + """ + + # override source and reference image with arguments (if provided) + self._src = src if src is not None else self._src + self._ref = ref if ref is not None else self._ref + + # parameter init + res = np.zeros_like(self._src) + + for ch in range(self._src.shape[2]): + + # convert to 1D arrays + src_vec = self._src[..., ch].ravel() + ref_vec = self._ref[..., ch].ravel() + + # analyze histograms + _, src_idxs, src_cnts = np.unique(src_vec, return_inverse=True, return_counts=True) + ref_vals, ref_cnts = np.unique(ref_vec, return_counts=True) + + # compute cumulative distribution functions + src_cdf = np.cumsum(src_cnts).astype(np.float64) / src_vec.size + ref_cdf = np.cumsum(ref_cnts).astype(np.float64) / ref_vec.size + + # do the histogram mapping + interp_vals = np.interp(src_cdf, ref_cdf, ref_vals) + res[..., ch] = interp_vals[src_idxs].reshape(src[..., ch].shape) + + return res diff --git a/python_embeded/Lib/site-packages/color_matcher/io_handler.py b/python_embeded/Lib/site-packages/color_matcher/io_handler.py new file mode 100644 index 0000000000000000000000000000000000000000..a95da258ee166698a805036c8e251fa847b7369e --- /dev/null +++ b/python_embeded/Lib/site-packages/color_matcher/io_handler.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python + +__author__ = "Christopher Hahne" +__email__ = "info@christopherhahne.de" +__license__ = """ + Copyright (c) 2020 Christopher Hahne + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +""" + +import os +import numpy as np + +try: + from PIL import Image +except ImportError: + raise ImportError('Please install pillow.') + +from color_matcher.normalizer import Normalizer + +FILE_EXTS = ('bmp', 'png', 'tiff', 'tif', 'jpeg', 'jpg') + + +def save_img_file(img, file_path: str = None, file_type: str = None) -> bool: + + file_path = os.getcwd() if file_path is None else file_path + ext = os.path.splitext(file_path)[-1][1:] + + if not file_type: + file_type = ext if ext == 'png' or ext == 'tiff' else 'tiff' if img.dtype == 'uint16' else 'png' + + # compose new file path string if extension type changed + file_path = os.path.splitext(file_path)[-2] if file_path.endswith(FILE_EXTS) else file_path + file_type = 'png' if file_type is None else file_type + file_path += '.' + file_type + + # normalization + img = Normalizer(img).uint16_norm() if file_type.__contains__('tif') else Normalizer(img).uint8_norm() + + try: + import imageio + suppress_user_warning(True, category=UserWarning) + imageio.imwrite(uri=file_path, im=img) + suppress_user_warning(False, category=UserWarning) + except ImportError: + if file_type == 'png' or file_type == 'bmp': + try: + Image.fromarray(img).save(file_path, file_type, optimize=True) + #imageio.imwrite(uri=file_path, im=img) + except PermissionError as e: + raise Exception(e) + + return True + + +def load_img_file(file_path: str = None) -> np.ndarray: + + # get file extension + file_type = file_path.split('.')[-1] + + if any(file_type.lower() in ext for ext in FILE_EXTS): + try: + import imageio + suppress_user_warning(True, category=UserWarning) + img = imageio.imread(uri=file_path, format=file_type) + suppress_user_warning(False, category=UserWarning) + except ImportError: + try: + img = Image.open(file_path) + except OSError or TypeError: + # support load of truncated images + from PIL import ImageFile + ImageFile.LOAD_TRUNCATED_IMAGES = True + img = Image.open(file_path) + + else: + raise TypeError('Filetype %s not recognized' % file_type) + + # normalize (convert to numpy array) + img = Normalizer(np.asarray(img)).type_norm() + + return img + + +def suppress_user_warning(switch=None, category=None): + + import warnings + switch = switch if switch is None else True + if switch: + warnings.filterwarnings("ignore", category=category) + else: + warnings.filterwarnings("default", category=category) + + +def select_file(init_dir=None, title=''): + """ get filepath from tkinter dialog """ + + # consider initial directory if provided + init_dir = os.path.expanduser('~/') if not init_dir else init_dir + + # import tkinter while considering Python version + try: + import tkinter as tk + from tkinter.filedialog import askopenfilename + except ImportError: + import Tkinter as tk + from tkFileDialog import askopenfilename + + # open window using tkinter + root = tk.Tk() + root.withdraw() + root.update() + file_path = askopenfilename(initialdir=[init_dir], title=title) + root.update() + + return file_path if file_path else None diff --git a/python_embeded/Lib/site-packages/color_matcher/mvgd_matcher.py b/python_embeded/Lib/site-packages/color_matcher/mvgd_matcher.py new file mode 100644 index 0000000000000000000000000000000000000000..2f9352d9acd25bf81d23d419574a306319b83c2f --- /dev/null +++ b/python_embeded/Lib/site-packages/color_matcher/mvgd_matcher.py @@ -0,0 +1,207 @@ +#!/usr/bin/env python + +__author__ = "Christopher Hahne" +__email__ = "info@christopherhahne.de" +__license__ = """ + Copyright (c) 2020 Christopher Hahne + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +""" + +import numpy as np + +from .baseclass import MatcherBaseclass +from types import FunctionType + + +class TransferMVGD(MatcherBaseclass): + + def __init__(self, *args, **kwargs): + super(TransferMVGD, self).__init__(*args, **kwargs) + + # extract method from kwargs (if available) + self._fun_dict = {'mvgd': self.analytical_solver, 'mkl': self.mkl_solver} + try: + self._fun_name = [kw for kw in list(self._fun_dict.keys()) if kwargs['method'].__contains__(kw)][0] + except (BaseException, IndexError): + # default function + self._fun_name = 'mkl' + self._fun_call = self._fun_dict[self._fun_name] if self._fun_name in self._fun_dict else self.mkl_solver + + # initialize variables + self.r, self.z, self.cov_r, self.cov_z, self.mu_r, self.mu_z, self.transfer_mat = [None]*7 + + def init_vars(self): + + # reshape source and reference images + self.r, self.z = self._src.reshape([-1, self._src.shape[2]]).T, self._ref.reshape([-1, self._ref.shape[2]]).T + + # compute covariance matrices + self.cov_r, self.cov_z = np.cov(self.r), np.cov(self.z) + + # compute color channel means + self.mu_r, self.mu_z = self.r.mean(axis=1)[..., np.newaxis], self.z.mean(axis=1)[..., np.newaxis] + + # validate dimensionality + self.check_dims() + + def multivar_transfer(self, src: np.ndarray = None, ref: np.ndarray = None, fun: FunctionType = None) -> np.ndarray: + """ + + Transfer function to map colors based on for Multi-Variate Gaussian Distributions (MVGDs). + + :param src: Source image that requires transfer + :param ref: Palette image which serves as reference + :param fun: Optional argument to pass a transfer function to solve for covariance matrices + :param res: Resulting image after the mapping + + :type src: :class:`~numpy:numpy.ndarray` + :type ref: :class:`~numpy:numpy.ndarray` + :type res: :class:`~numpy:numpy.ndarray` + + :return: **res** + :rtype: np.ndarray + + """ + + # override source and reference image with arguments (if provided) + self._src = src if src is not None else self._src + self._ref = ref if ref is not None else self._ref + + # check if three color channels are provided + self.validate_color_chs() + + # re-initialize variables to account for change in src and ref when passed to self.transfer() + self.init_vars() + + # set solver function for transfer matrix + self._fun_call = fun if fun is FunctionType else self._fun_call + + # compute transfer matrix + self.transfer_mat = self._fun_call() + + # transfer the intensity distributions + res = np.dot(self.transfer_mat, self.r - self.mu_r) + self.mu_z + + # reshape pixel array + res = res.T.reshape(self._src.shape) + + return res + + def mkl_solver(self): + """ + This function computes the transfer matrix based on the Monge-Kantorovich Linearization (MKL). + + :return: **transfer_mat**: Transfer matrix + :type transfer_mat: :class:`~numpy:numpy.ndarray` + :rtype: np.ndarray + + """ + + # validate dimensionality + self.check_dims() + + eig_val_r, eig_vec_r = np.linalg.eig(self.cov_r) + eig_val_r[eig_val_r < 0] = 0 + val_r = np.diag(np.sqrt(eig_val_r[::-1])) + vec_r = np.array(eig_vec_r[:, ::-1]) + inv_r = np.diag(1. / (np.diag(val_r + np.spacing(1)))) + + mat_c = val_r @ vec_r.T @ self.cov_z @ vec_r @ val_r + eig_val_c, eig_vec_c = np.linalg.eig(mat_c) + eig_val_c[eig_val_c < 0] = 0 + val_c = np.diag(np.sqrt(eig_val_c)) + + self.transfer_mat = vec_r @ inv_r @ eig_vec_c @ val_c @ eig_vec_c.T @ inv_r @ vec_r.T + + return self.transfer_mat + + def analytical_solver(self) -> np.ndarray: + """ + An analytical solution to the linear equation system of Multi-Variate Gaussian Distributions (MVGDs). + + :return: **transfer_mat**: Transfer matrix + :type transfer_mat: :class:`~numpy:numpy.ndarray` + :rtype: np.ndarray + + """ + + # validate dimensionality + self.check_dims() + if self.r.shape[-1] != self.z.shape[-1]: + raise Exception('Analytical MVGD solution requires spatial dimensions of both images to be equal') + + cov_r_inv = np.linalg.pinv(self.cov_r) + cov_z_inv = np.linalg.pinv(self.cov_z) + + # compute transfer matrix using analytical method + self.transfer_mat = np.linalg.pinv((self.z-self.mu_z).T @ cov_z_inv) @ (self.r-self.mu_r).T @ cov_r_inv + + return self.transfer_mat + + @staticmethod + def w2_dist(mu_a: np.ndarray, mu_b: np.ndarray, cov_a: np.ndarray, cov_b: np.ndarray) -> float: + """ + Wasserstein-2 distance metric is a similarity measure for Gaussian distributions + + :param mu_a: Gaussian mean of distribution *a* + :param mu_b: Gaussian mean of distribution *b* + :param cov_a: Covariance matrix of distribution *a* + :param cov_b: Covariance matrix of distribution *b* + + :type mu_a: :class:`~numpy:numpy.ndarray` + :type mu_b: :class:`~numpy:numpy.ndarray` + :type cov_a: :class:`~numpy:numpy.ndarray` + :type cov_b: :class:`~numpy:numpy.ndarray` + + :return: **scalar**: Wasserstein-2 metric as a scalar + :rtype: float + """ + + mean_dist = np.sum((mu_a-mu_b)**2) + vars_dist = np.trace(cov_a+cov_b - 2*(np.dot(np.abs(cov_b)**.5, np.dot(np.abs(cov_a), np.abs(cov_b)**.5))**.5)) + + return float(mean_dist + vars_dist) + + def w2_img_dist(self, img_a: np.ndarray, img_b:np.ndarray): + + """ + Wasserstein-2 image distance metric is a similarity measure for Gaussian distributions + + :param img_a: Image array *a* + :param img_b: Image array *b* + + :type img_a: :class:`~numpy:numpy.ndarray` + :type img_b: :class:`~numpy:numpy.ndarray` + + :return: **scalar**: Wasserstein-2 image metric as a scalar + :rtype: float + """ + + mu_a, mu_b = np.mean(img_a, axis=(0, 1)), np.mean(img_b, axis=(0, 1)) + cov_a, cov_b = np.cov(img_a.reshape(-1, 3).T), np.cov(img_b.reshape(-1, 3).T) + w2_img_dist = self.w2_dist(mu_a, mu_b, cov_a, cov_b) + + return w2_img_dist + + def check_dims(self): + """ + Catch error for wrong color channel number (e.g., gray scale image) + + :return: None + """ + + if np.ndim(self.cov_r) == 0 or np.ndim(self.cov_z) == 0: + raise Exception('Wrong color channel dimensionality for %s method' % self._fun_name) diff --git a/python_embeded/Lib/site-packages/color_matcher/normalizer.py b/python_embeded/Lib/site-packages/color_matcher/normalizer.py new file mode 100644 index 0000000000000000000000000000000000000000..144e238e4cace474d8b140f82923b946cdb35ed4 --- /dev/null +++ b/python_embeded/Lib/site-packages/color_matcher/normalizer.py @@ -0,0 +1,78 @@ +#!/usr/bin/env python + +__author__ = "Christopher Hahne" +__email__ = "info@christopherhahne.de" +__license__ = """ + Copyright (c) 2019 Christopher Hahne + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +""" + +import numpy as np + + +class Normalizer(object): + + def __init__(self, data=None, min=None, max=None): + + self._data, self._min, self._max = None, None, None + self._var_init(data, min, max) + + def _var_init(self, data=None, min=None, max=None): + + self._data = self._data if data is None else np.asarray(data, dtype='float64') + self._dtype = str(self._data.dtype) if isinstance(self._data, np.ndarray) else 'float64' + + self._min = self._min if min is None else min + self._max = self._max if max is None else max + self._min = self._data.min() if not any([self._min, min]) and isinstance(self._data, np.ndarray) else self._min + self._max = self._data.max() if not any([self._max, max]) and isinstance(self._data, np.ndarray) else self._max + + def uint16_norm(self): + """ normalize image array to 16-bit unsigned integer """ + + return np.asarray(np.round(self.norm_fun()*(2**16-1)), dtype=np.uint16) + + def uint8_norm(self): + """ normalize image array to 8-bit unsigned integer """ + + return np.asarray(np.round(self.norm_fun()*(2**8-1)), dtype=np.uint8) + + def type_norm(self, data=None, min=None, max=None, new_min=None, new_max=None): + """ normalize numpy image array for provided data type """ + + self._var_init(data, min, max) + + if self._dtype.startswith(('int', 'uint')): + new_max = np.iinfo(np.dtype(self._dtype)).max if new_max is None else new_max + new_min = np.iinfo(np.dtype(self._dtype)).min if new_min is None else new_min + img_norm = np.round(self.norm_fun() * (new_max - new_min) + new_min) + else: + new_max = 1.0 if new_max is None else new_max + new_min = 0.0 if new_min is None else new_min + img_norm = self.norm_fun() * (new_max - new_min) + new_min + + return np.asarray(img_norm, dtype=self._dtype) + + def norm_fun(self): + """ normalize image to values between 1 and 0 """ + + norm = (self._data - self._min) / (self._max - self._min) if self._max != (self._min and 0) else self._data + + # prevent wrap-around + norm[norm < 0] = 0 + norm[norm > 1] = 1 + + return norm diff --git a/python_embeded/Lib/site-packages/color_matcher/reinhard_matcher.py b/python_embeded/Lib/site-packages/color_matcher/reinhard_matcher.py new file mode 100644 index 0000000000000000000000000000000000000000..7d6e4a852431fc21f202c6ff7eb1183b54e65426 --- /dev/null +++ b/python_embeded/Lib/site-packages/color_matcher/reinhard_matcher.py @@ -0,0 +1,84 @@ +import numpy as np + +from .baseclass import MatcherBaseclass + +LMS_MAT = np.array([[0.3811, 0.5783, 0.0402], [0.1967, 0.7244, 0.0782], [0.0241, 0.1288, 0.8444]]) +LMS_MAT_INV = np.array([[4.4679, -3.5873, 0.1193], [-1.2186, 2.3809, -0.1624], [0.0497, -0.2439, 1.2045]]) + + +class ReinhardMatcher(MatcherBaseclass): + + def __init__(self, *args, **kwargs): + super(ReinhardMatcher, self).__init__(*args, **kwargs) + + def reinhard(self, src: np.ndarray = None, ref: np.ndarray = None) -> np.ndarray: + """ + + This function conducts color matching based on the principles proposed by Reinhard et al. + The paper of the original work can be found at https://www.cs.tau.ac.il/~turkel/imagepapers/ColorTransfer.pdf + + :param src: Source image that requires transfer + :param ref: Palette image which serves as reference + :param res: Resulting image after the mapping + + :type src: :class:`~numpy:numpy.ndarray` + :type ref: :class:`~numpy:numpy.ndarray` + :type res: :class:`~numpy:numpy.ndarray` + + :return: **res** + :rtype: np.ndarray + + """ + + # override source and reference image with arguments (if provided) + self._src = src if src is not None else self._src + self._ref = ref if ref is not None else self._ref + + # get image dimensions after validating that 3 color channels are present + m, n, p = self._src.shape if self.validate_color_chs() else self._src.shape + (1,) + + # flatten images along spatial dimensions + src = self._src.reshape((-1, p)).transpose() + ref = self._ref.reshape((-1, p)).transpose() + + # replace zeros with small value for numerical stability + src[src == 0] = 1/(2**8-1) + ref[ref == 0] = 1/(2**8-1) + + # convert to LMS color space + lms_src = np.dot(LMS_MAT, src) + lms_ref = np.dot(LMS_MAT, ref) + + # convert data to logarithmic LMS color space to eliminate skew + lms_src = np.log10(lms_src) + lms_ref = np.log10(lms_ref) + + # PCA transform matrices according to Rudermann et al. + b = np.array([[1/np.sqrt(3), 0, 0], [0, 1/np.sqrt(6), 0], [0, 0, 1/np.sqrt(2)]]) + c = np.array([[1, 1, 1], [1, 1, -2], [1, -1, 0]]) + + # convert to Lab space + lab_src = np.dot(np.dot(b, c), lms_src) + lab_ref = np.dot(np.dot(b, c), lms_ref) + + # compute statistical measures + mean_src, std_src = np.mean(lab_src, axis=1), np.std(lab_src, axis=1) + mean_ref, std_ref = np.mean(lab_ref, axis=1), np.std(lab_ref, axis=1) + + # compute ratios of standard deviations channel-wise + std_ratios = std_ref / std_src + + # apply statistical alignment channel-wise + res_lab = ((lab_src.T - mean_src) * std_ratios + mean_ref).T + + # convert back to LMS + lms_res = np.dot(np.dot(c.T, b), res_lab) + lms_res = 10**lms_res + + # convert back to RGB + res = np.dot(LMS_MAT_INV, lms_res).transpose() + + # reshape to 2-D image + res = res.reshape((m, n, p)) + + return res diff --git a/python_embeded/Lib/site-packages/color_matcher/top_level.py b/python_embeded/Lib/site-packages/color_matcher/top_level.py new file mode 100644 index 0000000000000000000000000000000000000000..5447c77941d83b40f9afa4f28dc0fe42aadb2183 --- /dev/null +++ b/python_embeded/Lib/site-packages/color_matcher/top_level.py @@ -0,0 +1,98 @@ +#!/usr/bin/env python + +__author__ = "Christopher Hahne" +__email__ = "info@christopherhahne.de" +__license__ = """ + Copyright (c) 2020 Christopher Hahne + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +""" + +from color_matcher.hist_matcher import HistogramMatcher +from color_matcher.mvgd_matcher import TransferMVGD +from color_matcher.reinhard_matcher import ReinhardMatcher +import numpy as np + +METHODS = ('default', 'hm', 'reinhard', 'mvgd', 'mkl', 'hm-mvgd-hm', 'hm-mkl-hm') + + +class ColorMatcher(HistogramMatcher, ReinhardMatcher, TransferMVGD): + + def __init__(self, *args, **kwargs): + super(ColorMatcher, self).__init__(*args, **kwargs) + + self._method = kwargs['method'] if 'method' in kwargs else 'default' + self._funs = [] + + def main(self) -> np.ndarray: + """ + The main function is the high-level entry point performing the mapping based on instantiation arguments. + + :return: Resulting image after color mapping + :rtype: np.ndarray + """ + + self.transfer() + + return self._src + + def transfer(self, src: np.ndarray = None, ref: np.ndarray = None, method: str = None) -> np.ndarray: + """ + + Transfer function to map colors based on provided transfer method. + + :param src: Source image that requires transfer + :param ref: Palette image which serves as reference + :param method: ('default', 'hm', 'reinhard', 'mvgd', 'mkl', 'hm-mvgd-hm', 'hm-mkl-hm') determining color mapping + + :type src: :class:`~numpy:numpy.ndarray` + :type ref: :class:`~numpy:numpy.ndarray` + :type method: :class:`str` + + :return: Resulting image after color mapping + :rtype: np.ndarray + + """ + + # assign input arguments to variables (if provided) + self._method = self._method.lower() if method is None else method.lower() + self._src = src if src is not None else self._src + self._ref = ref if ref is not None else self._ref + + # color transfer methods (to be iterated through) + if self._method == METHODS[0]: + self._funs = [self.multivar_transfer] + elif self._method == METHODS[1]: + self._funs = [self.hist_match] + elif self._method == METHODS[2]: + self._funs = [self.reinhard] + elif self._method in METHODS[3:5]: + self._funs = [self.multivar_transfer] + elif self._method in METHODS[5:]: + self._funs = [self.hist_match, self.multivar_transfer, self.hist_match] + else: + raise BaseException('Method type \'%s\' not recognized' % method) + + # check if three color channels are provided + self.validate_img_dims() + + # check provided color channels + self.validate_color_chs() + + # proceed with the color match + for fun in self._funs: + self._src = fun(self._src, self._ref) + + return self._src diff --git a/python_embeded/Lib/site-packages/colorama-0.4.6.dist-info/METADATA b/python_embeded/Lib/site-packages/colorama-0.4.6.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..a1b5c57543005b310ac2efb02243a6b6ab6d8932 --- /dev/null +++ b/python_embeded/Lib/site-packages/colorama-0.4.6.dist-info/METADATA @@ -0,0 +1,441 @@ +Metadata-Version: 2.1 +Name: colorama +Version: 0.4.6 +Summary: Cross-platform colored terminal text. +Project-URL: Homepage, https://github.com/tartley/colorama +Author-email: Jonathan Hartley +License-File: LICENSE.txt +Keywords: ansi,color,colour,crossplatform,terminal,text,windows,xplatform +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: Console +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: BSD License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 2 +Classifier: Programming Language :: Python :: 2.7 +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 :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: Terminals +Requires-Python: !=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*,>=2.7 +Description-Content-Type: text/x-rst + +.. image:: https://img.shields.io/pypi/v/colorama.svg + :target: https://pypi.org/project/colorama/ + :alt: Latest Version + +.. image:: https://img.shields.io/pypi/pyversions/colorama.svg + :target: https://pypi.org/project/colorama/ + :alt: Supported Python versions + +.. image:: https://github.com/tartley/colorama/actions/workflows/test.yml/badge.svg + :target: https://github.com/tartley/colorama/actions/workflows/test.yml + :alt: Build Status + +Colorama +======== + +Makes ANSI escape character sequences (for producing colored terminal text and +cursor positioning) work under MS Windows. + +.. |donate| image:: https://www.paypalobjects.com/en_US/i/btn/btn_donate_SM.gif + :target: https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=2MZ9D2GMLYCUJ&item_name=Colorama¤cy_code=USD + :alt: Donate with Paypal + +`PyPI for releases `_ | +`Github for source `_ | +`Colorama for enterprise on Tidelift `_ + +If you find Colorama useful, please |donate| to the authors. Thank you! + +Installation +------------ + +Tested on CPython 2.7, 3.7, 3.8, 3.9 and 3.10 and Pypy 2.7 and 3.8. + +No requirements other than the standard library. + +.. code-block:: bash + + pip install colorama + # or + conda install -c anaconda colorama + +Description +----------- + +ANSI escape character sequences have long been used to produce colored terminal +text and cursor positioning on Unix and Macs. Colorama makes this work on +Windows, too, by wrapping ``stdout``, stripping ANSI sequences it finds (which +would appear as gobbledygook in the output), and converting them into the +appropriate win32 calls to modify the state of the terminal. On other platforms, +Colorama does nothing. + +This has the upshot of providing a simple cross-platform API for printing +colored terminal text from Python, and has the happy side-effect that existing +applications or libraries which use ANSI sequences to produce colored output on +Linux or Macs can now also work on Windows, simply by calling +``colorama.just_fix_windows_console()`` (since v0.4.6) or ``colorama.init()`` +(all versions, but may have other side-effects – see below). + +An alternative approach is to install ``ansi.sys`` on Windows machines, which +provides the same behaviour for all applications running in terminals. Colorama +is intended for situations where that isn't easy (e.g., maybe your app doesn't +have an installer.) + +Demo scripts in the source code repository print some colored text using +ANSI sequences. Compare their output under Gnome-terminal's built in ANSI +handling, versus on Windows Command-Prompt using Colorama: + +.. image:: https://github.com/tartley/colorama/raw/master/screenshots/ubuntu-demo.png + :width: 661 + :height: 357 + :alt: ANSI sequences on Ubuntu under gnome-terminal. + +.. image:: https://github.com/tartley/colorama/raw/master/screenshots/windows-demo.png + :width: 668 + :height: 325 + :alt: Same ANSI sequences on Windows, using Colorama. + +These screenshots show that, on Windows, Colorama does not support ANSI 'dim +text'; it looks the same as 'normal text'. + +Usage +----- + +Initialisation +.............. + +If the only thing you want from Colorama is to get ANSI escapes to work on +Windows, then run: + +.. code-block:: python + + from colorama import just_fix_windows_console + just_fix_windows_console() + +If you're on a recent version of Windows 10 or better, and your stdout/stderr +are pointing to a Windows console, then this will flip the magic configuration +switch to enable Windows' built-in ANSI support. + +If you're on an older version of Windows, and your stdout/stderr are pointing to +a Windows console, then this will wrap ``sys.stdout`` and/or ``sys.stderr`` in a +magic file object that intercepts ANSI escape sequences and issues the +appropriate Win32 calls to emulate them. + +In all other circumstances, it does nothing whatsoever. Basically the idea is +that this makes Windows act like Unix with respect to ANSI escape handling. + +It's safe to call this function multiple times. It's safe to call this function +on non-Windows platforms, but it won't do anything. It's safe to call this +function when one or both of your stdout/stderr are redirected to a file – it +won't do anything to those streams. + +Alternatively, you can use the older interface with more features (but also more +potential footguns): + +.. code-block:: python + + from colorama import init + init() + +This does the same thing as ``just_fix_windows_console``, except for the +following differences: + +- It's not safe to call ``init`` multiple times; you can end up with multiple + layers of wrapping and broken ANSI support. + +- Colorama will apply a heuristic to guess whether stdout/stderr support ANSI, + and if it thinks they don't, then it will wrap ``sys.stdout`` and + ``sys.stderr`` in a magic file object that strips out ANSI escape sequences + before printing them. This happens on all platforms, and can be convenient if + you want to write your code to emit ANSI escape sequences unconditionally, and + let Colorama decide whether they should actually be output. But note that + Colorama's heuristic is not particularly clever. + +- ``init`` also accepts explicit keyword args to enable/disable various + functionality – see below. + +To stop using Colorama before your program exits, simply call ``deinit()``. +This will restore ``stdout`` and ``stderr`` to their original values, so that +Colorama is disabled. To resume using Colorama again, call ``reinit()``; it is +cheaper than calling ``init()`` again (but does the same thing). + +Most users should depend on ``colorama >= 0.4.6``, and use +``just_fix_windows_console``. The old ``init`` interface will be supported +indefinitely for backwards compatibility, but we don't plan to fix any issues +with it, also for backwards compatibility. + +Colored Output +.............. + +Cross-platform printing of colored text can then be done using Colorama's +constant shorthand for ANSI escape sequences. These are deliberately +rudimentary, see below. + +.. code-block:: python + + from colorama import Fore, Back, Style + print(Fore.RED + 'some red text') + print(Back.GREEN + 'and with a green background') + print(Style.DIM + 'and in dim text') + print(Style.RESET_ALL) + print('back to normal now') + +...or simply by manually printing ANSI sequences from your own code: + +.. code-block:: python + + print('\033[31m' + 'some red text') + print('\033[39m') # and reset to default color + +...or, Colorama can be used in conjunction with existing ANSI libraries +such as the venerable `Termcolor `_ +the fabulous `Blessings `_, +or the incredible `_Rich `_. + +If you wish Colorama's Fore, Back and Style constants were more capable, +then consider using one of the above highly capable libraries to generate +colors, etc, and use Colorama just for its primary purpose: to convert +those ANSI sequences to also work on Windows: + +SIMILARLY, do not send PRs adding the generation of new ANSI types to Colorama. +We are only interested in converting ANSI codes to win32 API calls, not +shortcuts like the above to generate ANSI characters. + +.. code-block:: python + + from colorama import just_fix_windows_console + from termcolor import colored + + # use Colorama to make Termcolor work on Windows too + just_fix_windows_console() + + # then use Termcolor for all colored text output + print(colored('Hello, World!', 'green', 'on_red')) + +Available formatting constants are:: + + Fore: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET. + Back: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET. + Style: DIM, NORMAL, BRIGHT, RESET_ALL + +``Style.RESET_ALL`` resets foreground, background, and brightness. Colorama will +perform this reset automatically on program exit. + +These are fairly well supported, but not part of the standard:: + + Fore: LIGHTBLACK_EX, LIGHTRED_EX, LIGHTGREEN_EX, LIGHTYELLOW_EX, LIGHTBLUE_EX, LIGHTMAGENTA_EX, LIGHTCYAN_EX, LIGHTWHITE_EX + Back: LIGHTBLACK_EX, LIGHTRED_EX, LIGHTGREEN_EX, LIGHTYELLOW_EX, LIGHTBLUE_EX, LIGHTMAGENTA_EX, LIGHTCYAN_EX, LIGHTWHITE_EX + +Cursor Positioning +.................. + +ANSI codes to reposition the cursor are supported. See ``demos/demo06.py`` for +an example of how to generate them. + +Init Keyword Args +................. + +``init()`` accepts some ``**kwargs`` to override default behaviour. + +init(autoreset=False): + If you find yourself repeatedly sending reset sequences to turn off color + changes at the end of every print, then ``init(autoreset=True)`` will + automate that: + + .. code-block:: python + + from colorama import init + init(autoreset=True) + print(Fore.RED + 'some red text') + print('automatically back to default color again') + +init(strip=None): + Pass ``True`` or ``False`` to override whether ANSI codes should be + stripped from the output. The default behaviour is to strip if on Windows + or if output is redirected (not a tty). + +init(convert=None): + Pass ``True`` or ``False`` to override whether to convert ANSI codes in the + output into win32 calls. The default behaviour is to convert if on Windows + and output is to a tty (terminal). + +init(wrap=True): + On Windows, Colorama works by replacing ``sys.stdout`` and ``sys.stderr`` + with proxy objects, which override the ``.write()`` method to do their work. + If this wrapping causes you problems, then this can be disabled by passing + ``init(wrap=False)``. The default behaviour is to wrap if ``autoreset`` or + ``strip`` or ``convert`` are True. + + When wrapping is disabled, colored printing on non-Windows platforms will + continue to work as normal. To do cross-platform colored output, you can + use Colorama's ``AnsiToWin32`` proxy directly: + + .. code-block:: python + + import sys + from colorama import init, AnsiToWin32 + init(wrap=False) + stream = AnsiToWin32(sys.stderr).stream + + # Python 2 + print >>stream, Fore.BLUE + 'blue text on stderr' + + # Python 3 + print(Fore.BLUE + 'blue text on stderr', file=stream) + +Recognised ANSI Sequences +......................... + +ANSI sequences generally take the form:: + + ESC [ ; ... + +Where ```` is an integer, and ```` is a single letter. Zero or +more params are passed to a ````. If no params are passed, it is +generally synonymous with passing a single zero. No spaces exist in the +sequence; they have been inserted here simply to read more easily. + +The only ANSI sequences that Colorama converts into win32 calls are:: + + ESC [ 0 m # reset all (colors and brightness) + ESC [ 1 m # bright + ESC [ 2 m # dim (looks same as normal brightness) + ESC [ 22 m # normal brightness + + # FOREGROUND: + ESC [ 30 m # black + ESC [ 31 m # red + ESC [ 32 m # green + ESC [ 33 m # yellow + ESC [ 34 m # blue + ESC [ 35 m # magenta + ESC [ 36 m # cyan + ESC [ 37 m # white + ESC [ 39 m # reset + + # BACKGROUND + ESC [ 40 m # black + ESC [ 41 m # red + ESC [ 42 m # green + ESC [ 43 m # yellow + ESC [ 44 m # blue + ESC [ 45 m # magenta + ESC [ 46 m # cyan + ESC [ 47 m # white + ESC [ 49 m # reset + + # cursor positioning + ESC [ y;x H # position cursor at x across, y down + ESC [ y;x f # position cursor at x across, y down + ESC [ n A # move cursor n lines up + ESC [ n B # move cursor n lines down + ESC [ n C # move cursor n characters forward + ESC [ n D # move cursor n characters backward + + # clear the screen + ESC [ mode J # clear the screen + + # clear the line + ESC [ mode K # clear the line + +Multiple numeric params to the ``'m'`` command can be combined into a single +sequence:: + + ESC [ 36 ; 45 ; 1 m # bright cyan text on magenta background + +All other ANSI sequences of the form ``ESC [ ; ... `` +are silently stripped from the output on Windows. + +Any other form of ANSI sequence, such as single-character codes or alternative +initial characters, are not recognised or stripped. It would be cool to add +them though. Let me know if it would be useful for you, via the Issues on +GitHub. + +Status & Known Problems +----------------------- + +I've personally only tested it on Windows XP (CMD, Console2), Ubuntu +(gnome-terminal, xterm), and OS X. + +Some valid ANSI sequences aren't recognised. + +If you're hacking on the code, see `README-hacking.md`_. ESPECIALLY, see the +explanation there of why we do not want PRs that allow Colorama to generate new +types of ANSI codes. + +See outstanding issues and wish-list: +https://github.com/tartley/colorama/issues + +If anything doesn't work for you, or doesn't do what you expected or hoped for, +I'd love to hear about it on that issues list, would be delighted by patches, +and would be happy to grant commit access to anyone who submits a working patch +or two. + +.. _README-hacking.md: README-hacking.md + +License +------- + +Copyright Jonathan Hartley & Arnon Yaari, 2013-2020. BSD 3-Clause license; see +LICENSE file. + +Professional support +-------------------- + +.. |tideliftlogo| image:: https://cdn2.hubspot.net/hubfs/4008838/website/logos/logos_for_download/Tidelift_primary-shorthand-logo.png + :alt: Tidelift + :target: https://tidelift.com/subscription/pkg/pypi-colorama?utm_source=pypi-colorama&utm_medium=referral&utm_campaign=readme + +.. list-table:: + :widths: 10 100 + + * - |tideliftlogo| + - Professional support for colorama is available as part of the + `Tidelift Subscription`_. + Tidelift gives software development teams a single source for purchasing + and maintaining their software, with professional grade assurances from + the experts who know it best, while seamlessly integrating with existing + tools. + +.. _Tidelift Subscription: https://tidelift.com/subscription/pkg/pypi-colorama?utm_source=pypi-colorama&utm_medium=referral&utm_campaign=readme + +Thanks +------ + +See the CHANGELOG for more thanks! + +* Marc Schlaich (schlamar) for a ``setup.py`` fix for Python2.5. +* Marc Abramowitz, reported & fixed a crash on exit with closed ``stdout``, + providing a solution to issue #7's setuptools/distutils debate, + and other fixes. +* User 'eryksun', for guidance on correctly instantiating ``ctypes.windll``. +* Matthew McCormick for politely pointing out a longstanding crash on non-Win. +* Ben Hoyt, for a magnificent fix under 64-bit Windows. +* Jesse at Empty Square for submitting a fix for examples in the README. +* User 'jamessp', an observant documentation fix for cursor positioning. +* User 'vaal1239', Dave Mckee & Lackner Kristof for a tiny but much-needed Win7 + fix. +* Julien Stuyck, for wisely suggesting Python3 compatible updates to README. +* Daniel Griffith for multiple fabulous patches. +* Oscar Lesta for a valuable fix to stop ANSI chars being sent to non-tty + output. +* Roger Binns, for many suggestions, valuable feedback, & bug reports. +* Tim Golden for thought and much appreciated feedback on the initial idea. +* User 'Zearin' for updates to the README file. +* John Szakmeister for adding support for light colors +* Charles Merriam for adding documentation to demos +* Jurko for a fix on 64-bit Windows CPython2.5 w/o ctypes +* Florian Bruhin for a fix when stdout or stderr are None +* Thomas Weininger for fixing ValueError on Windows +* Remi Rampin for better Github integration and fixes to the README file +* Simeon Visser for closing a file handle using 'with' and updating classifiers + to include Python 3.3 and 3.4 +* Andy Neff for fixing RESET of LIGHT_EX colors. +* Jonathan Hartley for the initial idea and implementation. diff --git a/python_embeded/Lib/site-packages/colorama-0.4.6.dist-info/RECORD b/python_embeded/Lib/site-packages/colorama-0.4.6.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..f9b6fd25da3b51415f8bf6affb75087331319bee --- /dev/null +++ b/python_embeded/Lib/site-packages/colorama-0.4.6.dist-info/RECORD @@ -0,0 +1,33 @@ +colorama-0.4.6.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +colorama-0.4.6.dist-info/METADATA,sha256=e67SnrUMOym9sz_4TjF3vxvAV4T3aF7NyqRHHH3YEMw,17158 +colorama-0.4.6.dist-info/RECORD,, +colorama-0.4.6.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +colorama-0.4.6.dist-info/WHEEL,sha256=cdcF4Fbd0FPtw2EMIOwH-3rSOTUdTCeOSXRMD1iLUb8,105 +colorama-0.4.6.dist-info/direct_url.json,sha256=VZjQx-E-Db2UzSXVfM9xE7dRsKQmFiU6JaiCGOsB3kU,276 +colorama-0.4.6.dist-info/licenses/LICENSE.txt,sha256=ysNcAmhuXQSlpxQL-zs25zrtSWZW6JEQLkKIhteTAxg,1491 +colorama/__init__.py,sha256=wePQA4U20tKgYARySLEC047ucNX-g8pRLpYBuiHlLb8,266 +colorama/__pycache__/__init__.cpython-312.pyc,, +colorama/__pycache__/ansi.cpython-312.pyc,, +colorama/__pycache__/ansitowin32.cpython-312.pyc,, +colorama/__pycache__/initialise.cpython-312.pyc,, +colorama/__pycache__/win32.cpython-312.pyc,, +colorama/__pycache__/winterm.cpython-312.pyc,, +colorama/ansi.py,sha256=Top4EeEuaQdBWdteKMEcGOTeKeF19Q-Wo_6_Cj5kOzQ,2522 +colorama/ansitowin32.py,sha256=vPNYa3OZbxjbuFyaVo0Tmhmy1FZ1lKMWCnT7odXpItk,11128 +colorama/initialise.py,sha256=-hIny86ClXo39ixh5iSCfUIa2f_h_bgKRDW7gqs-KLU,3325 +colorama/tests/__init__.py,sha256=MkgPAEzGQd-Rq0w0PZXSX2LadRWhUECcisJY8lSrm4Q,75 +colorama/tests/__pycache__/__init__.cpython-312.pyc,, +colorama/tests/__pycache__/ansi_test.cpython-312.pyc,, +colorama/tests/__pycache__/ansitowin32_test.cpython-312.pyc,, +colorama/tests/__pycache__/initialise_test.cpython-312.pyc,, +colorama/tests/__pycache__/isatty_test.cpython-312.pyc,, +colorama/tests/__pycache__/utils.cpython-312.pyc,, +colorama/tests/__pycache__/winterm_test.cpython-312.pyc,, +colorama/tests/ansi_test.py,sha256=FeViDrUINIZcr505PAxvU4AjXz1asEiALs9GXMhwRaE,2839 +colorama/tests/ansitowin32_test.py,sha256=RN7AIhMJ5EqDsYaCjVo-o4u8JzDD4ukJbmevWKS70rY,10678 +colorama/tests/initialise_test.py,sha256=BbPy-XfyHwJ6zKozuQOvNvQZzsx9vdb_0bYXn7hsBTc,6741 +colorama/tests/isatty_test.py,sha256=Pg26LRpv0yQDB5Ac-sxgVXG7hsA1NYvapFgApZfYzZg,1866 +colorama/tests/utils.py,sha256=1IIRylG39z5-dzq09R_ngufxyPZxgldNbrxKxUGwGKE,1079 +colorama/tests/winterm_test.py,sha256=qoWFPEjym5gm2RuMwpf3pOis3a5r_PJZFCzK254JL8A,3709 +colorama/win32.py,sha256=YQOKwMTwtGBbsY4dL5HYTvwTeP9wIQra5MvPNddpxZs,6181 +colorama/winterm.py,sha256=XCQFDHjPi6AHYNdZwy0tA02H-Jh48Jp-HvCjeLeLp3U,7134 diff --git a/python_embeded/Lib/site-packages/colorama-0.4.6.dist-info/REQUESTED b/python_embeded/Lib/site-packages/colorama-0.4.6.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python_embeded/Lib/site-packages/colorama-0.4.6.dist-info/WHEEL b/python_embeded/Lib/site-packages/colorama-0.4.6.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..d79189fda3251187de18c3998f23ae6fec11b20f --- /dev/null +++ b/python_embeded/Lib/site-packages/colorama-0.4.6.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.11.1 +Root-Is-Purelib: true +Tag: py2-none-any +Tag: py3-none-any diff --git a/python_embeded/Lib/site-packages/colorama/ansi.py b/python_embeded/Lib/site-packages/colorama/ansi.py new file mode 100644 index 0000000000000000000000000000000000000000..11ec695ff79627463a0282d25079527562de9e42 --- /dev/null +++ b/python_embeded/Lib/site-packages/colorama/ansi.py @@ -0,0 +1,102 @@ +# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. +''' +This module generates ANSI character codes to printing colors to terminals. +See: http://en.wikipedia.org/wiki/ANSI_escape_code +''' + +CSI = '\033[' +OSC = '\033]' +BEL = '\a' + + +def code_to_chars(code): + return CSI + str(code) + 'm' + +def set_title(title): + return OSC + '2;' + title + BEL + +def clear_screen(mode=2): + return CSI + str(mode) + 'J' + +def clear_line(mode=2): + return CSI + str(mode) + 'K' + + +class AnsiCodes(object): + def __init__(self): + # the subclasses declare class attributes which are numbers. + # Upon instantiation we define instance attributes, which are the same + # as the class attributes but wrapped with the ANSI escape sequence + for name in dir(self): + if not name.startswith('_'): + value = getattr(self, name) + setattr(self, name, code_to_chars(value)) + + +class AnsiCursor(object): + def UP(self, n=1): + return CSI + str(n) + 'A' + def DOWN(self, n=1): + return CSI + str(n) + 'B' + def FORWARD(self, n=1): + return CSI + str(n) + 'C' + def BACK(self, n=1): + return CSI + str(n) + 'D' + def POS(self, x=1, y=1): + return CSI + str(y) + ';' + str(x) + 'H' + + +class AnsiFore(AnsiCodes): + BLACK = 30 + RED = 31 + GREEN = 32 + YELLOW = 33 + BLUE = 34 + MAGENTA = 35 + CYAN = 36 + WHITE = 37 + RESET = 39 + + # These are fairly well supported, but not part of the standard. + LIGHTBLACK_EX = 90 + LIGHTRED_EX = 91 + LIGHTGREEN_EX = 92 + LIGHTYELLOW_EX = 93 + LIGHTBLUE_EX = 94 + LIGHTMAGENTA_EX = 95 + LIGHTCYAN_EX = 96 + LIGHTWHITE_EX = 97 + + +class AnsiBack(AnsiCodes): + BLACK = 40 + RED = 41 + GREEN = 42 + YELLOW = 43 + BLUE = 44 + MAGENTA = 45 + CYAN = 46 + WHITE = 47 + RESET = 49 + + # These are fairly well supported, but not part of the standard. + LIGHTBLACK_EX = 100 + LIGHTRED_EX = 101 + LIGHTGREEN_EX = 102 + LIGHTYELLOW_EX = 103 + LIGHTBLUE_EX = 104 + LIGHTMAGENTA_EX = 105 + LIGHTCYAN_EX = 106 + LIGHTWHITE_EX = 107 + + +class AnsiStyle(AnsiCodes): + BRIGHT = 1 + DIM = 2 + NORMAL = 22 + RESET_ALL = 0 + +Fore = AnsiFore() +Back = AnsiBack() +Style = AnsiStyle() +Cursor = AnsiCursor() diff --git a/python_embeded/Lib/site-packages/colorama/ansitowin32.py b/python_embeded/Lib/site-packages/colorama/ansitowin32.py new file mode 100644 index 0000000000000000000000000000000000000000..abf209e60c7c4a9b1ae57452e36b383969848c2e --- /dev/null +++ b/python_embeded/Lib/site-packages/colorama/ansitowin32.py @@ -0,0 +1,277 @@ +# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. +import re +import sys +import os + +from .ansi import AnsiFore, AnsiBack, AnsiStyle, Style, BEL +from .winterm import enable_vt_processing, WinTerm, WinColor, WinStyle +from .win32 import windll, winapi_test + + +winterm = None +if windll is not None: + winterm = WinTerm() + + +class StreamWrapper(object): + ''' + Wraps a stream (such as stdout), acting as a transparent proxy for all + attribute access apart from method 'write()', which is delegated to our + Converter instance. + ''' + def __init__(self, wrapped, converter): + # double-underscore everything to prevent clashes with names of + # attributes on the wrapped stream object. + self.__wrapped = wrapped + self.__convertor = converter + + def __getattr__(self, name): + return getattr(self.__wrapped, name) + + def __enter__(self, *args, **kwargs): + # special method lookup bypasses __getattr__/__getattribute__, see + # https://stackoverflow.com/questions/12632894/why-doesnt-getattr-work-with-exit + # thus, contextlib magic methods are not proxied via __getattr__ + return self.__wrapped.__enter__(*args, **kwargs) + + def __exit__(self, *args, **kwargs): + return self.__wrapped.__exit__(*args, **kwargs) + + def __setstate__(self, state): + self.__dict__ = state + + def __getstate__(self): + return self.__dict__ + + def write(self, text): + self.__convertor.write(text) + + def isatty(self): + stream = self.__wrapped + if 'PYCHARM_HOSTED' in os.environ: + if stream is not None and (stream is sys.__stdout__ or stream is sys.__stderr__): + return True + try: + stream_isatty = stream.isatty + except AttributeError: + return False + else: + return stream_isatty() + + @property + def closed(self): + stream = self.__wrapped + try: + return stream.closed + # AttributeError in the case that the stream doesn't support being closed + # ValueError for the case that the stream has already been detached when atexit runs + except (AttributeError, ValueError): + return True + + +class AnsiToWin32(object): + ''' + Implements a 'write()' method which, on Windows, will strip ANSI character + sequences from the text, and if outputting to a tty, will convert them into + win32 function calls. + ''' + ANSI_CSI_RE = re.compile('\001?\033\\[((?:\\d|;)*)([a-zA-Z])\002?') # Control Sequence Introducer + ANSI_OSC_RE = re.compile('\001?\033\\]([^\a]*)(\a)\002?') # Operating System Command + + def __init__(self, wrapped, convert=None, strip=None, autoreset=False): + # The wrapped stream (normally sys.stdout or sys.stderr) + self.wrapped = wrapped + + # should we reset colors to defaults after every .write() + self.autoreset = autoreset + + # create the proxy wrapping our output stream + self.stream = StreamWrapper(wrapped, self) + + on_windows = os.name == 'nt' + # We test if the WinAPI works, because even if we are on Windows + # we may be using a terminal that doesn't support the WinAPI + # (e.g. Cygwin Terminal). In this case it's up to the terminal + # to support the ANSI codes. + conversion_supported = on_windows and winapi_test() + try: + fd = wrapped.fileno() + except Exception: + fd = -1 + system_has_native_ansi = not on_windows or enable_vt_processing(fd) + have_tty = not self.stream.closed and self.stream.isatty() + need_conversion = conversion_supported and not system_has_native_ansi + + # should we strip ANSI sequences from our output? + if strip is None: + strip = need_conversion or not have_tty + self.strip = strip + + # should we should convert ANSI sequences into win32 calls? + if convert is None: + convert = need_conversion and have_tty + self.convert = convert + + # dict of ansi codes to win32 functions and parameters + self.win32_calls = self.get_win32_calls() + + # are we wrapping stderr? + self.on_stderr = self.wrapped is sys.stderr + + def should_wrap(self): + ''' + True if this class is actually needed. If false, then the output + stream will not be affected, nor will win32 calls be issued, so + wrapping stdout is not actually required. This will generally be + False on non-Windows platforms, unless optional functionality like + autoreset has been requested using kwargs to init() + ''' + return self.convert or self.strip or self.autoreset + + def get_win32_calls(self): + if self.convert and winterm: + return { + AnsiStyle.RESET_ALL: (winterm.reset_all, ), + AnsiStyle.BRIGHT: (winterm.style, WinStyle.BRIGHT), + AnsiStyle.DIM: (winterm.style, WinStyle.NORMAL), + AnsiStyle.NORMAL: (winterm.style, WinStyle.NORMAL), + AnsiFore.BLACK: (winterm.fore, WinColor.BLACK), + AnsiFore.RED: (winterm.fore, WinColor.RED), + AnsiFore.GREEN: (winterm.fore, WinColor.GREEN), + AnsiFore.YELLOW: (winterm.fore, WinColor.YELLOW), + AnsiFore.BLUE: (winterm.fore, WinColor.BLUE), + AnsiFore.MAGENTA: (winterm.fore, WinColor.MAGENTA), + AnsiFore.CYAN: (winterm.fore, WinColor.CYAN), + AnsiFore.WHITE: (winterm.fore, WinColor.GREY), + AnsiFore.RESET: (winterm.fore, ), + AnsiFore.LIGHTBLACK_EX: (winterm.fore, WinColor.BLACK, True), + AnsiFore.LIGHTRED_EX: (winterm.fore, WinColor.RED, True), + AnsiFore.LIGHTGREEN_EX: (winterm.fore, WinColor.GREEN, True), + AnsiFore.LIGHTYELLOW_EX: (winterm.fore, WinColor.YELLOW, True), + AnsiFore.LIGHTBLUE_EX: (winterm.fore, WinColor.BLUE, True), + AnsiFore.LIGHTMAGENTA_EX: (winterm.fore, WinColor.MAGENTA, True), + AnsiFore.LIGHTCYAN_EX: (winterm.fore, WinColor.CYAN, True), + AnsiFore.LIGHTWHITE_EX: (winterm.fore, WinColor.GREY, True), + AnsiBack.BLACK: (winterm.back, WinColor.BLACK), + AnsiBack.RED: (winterm.back, WinColor.RED), + AnsiBack.GREEN: (winterm.back, WinColor.GREEN), + AnsiBack.YELLOW: (winterm.back, WinColor.YELLOW), + AnsiBack.BLUE: (winterm.back, WinColor.BLUE), + AnsiBack.MAGENTA: (winterm.back, WinColor.MAGENTA), + AnsiBack.CYAN: (winterm.back, WinColor.CYAN), + AnsiBack.WHITE: (winterm.back, WinColor.GREY), + AnsiBack.RESET: (winterm.back, ), + AnsiBack.LIGHTBLACK_EX: (winterm.back, WinColor.BLACK, True), + AnsiBack.LIGHTRED_EX: (winterm.back, WinColor.RED, True), + AnsiBack.LIGHTGREEN_EX: (winterm.back, WinColor.GREEN, True), + AnsiBack.LIGHTYELLOW_EX: (winterm.back, WinColor.YELLOW, True), + AnsiBack.LIGHTBLUE_EX: (winterm.back, WinColor.BLUE, True), + AnsiBack.LIGHTMAGENTA_EX: (winterm.back, WinColor.MAGENTA, True), + AnsiBack.LIGHTCYAN_EX: (winterm.back, WinColor.CYAN, True), + AnsiBack.LIGHTWHITE_EX: (winterm.back, WinColor.GREY, True), + } + return dict() + + def write(self, text): + if self.strip or self.convert: + self.write_and_convert(text) + else: + self.wrapped.write(text) + self.wrapped.flush() + if self.autoreset: + self.reset_all() + + + def reset_all(self): + if self.convert: + self.call_win32('m', (0,)) + elif not self.strip and not self.stream.closed: + self.wrapped.write(Style.RESET_ALL) + + + def write_and_convert(self, text): + ''' + Write the given text to our wrapped stream, stripping any ANSI + sequences from the text, and optionally converting them into win32 + calls. + ''' + cursor = 0 + text = self.convert_osc(text) + for match in self.ANSI_CSI_RE.finditer(text): + start, end = match.span() + self.write_plain_text(text, cursor, start) + self.convert_ansi(*match.groups()) + cursor = end + self.write_plain_text(text, cursor, len(text)) + + + def write_plain_text(self, text, start, end): + if start < end: + self.wrapped.write(text[start:end]) + self.wrapped.flush() + + + def convert_ansi(self, paramstring, command): + if self.convert: + params = self.extract_params(command, paramstring) + self.call_win32(command, params) + + + def extract_params(self, command, paramstring): + if command in 'Hf': + params = tuple(int(p) if len(p) != 0 else 1 for p in paramstring.split(';')) + while len(params) < 2: + # defaults: + params = params + (1,) + else: + params = tuple(int(p) for p in paramstring.split(';') if len(p) != 0) + if len(params) == 0: + # defaults: + if command in 'JKm': + params = (0,) + elif command in 'ABCD': + params = (1,) + + return params + + + def call_win32(self, command, params): + if command == 'm': + for param in params: + if param in self.win32_calls: + func_args = self.win32_calls[param] + func = func_args[0] + args = func_args[1:] + kwargs = dict(on_stderr=self.on_stderr) + func(*args, **kwargs) + elif command in 'J': + winterm.erase_screen(params[0], on_stderr=self.on_stderr) + elif command in 'K': + winterm.erase_line(params[0], on_stderr=self.on_stderr) + elif command in 'Hf': # cursor position - absolute + winterm.set_cursor_position(params, on_stderr=self.on_stderr) + elif command in 'ABCD': # cursor position - relative + n = params[0] + # A - up, B - down, C - forward, D - back + x, y = {'A': (0, -n), 'B': (0, n), 'C': (n, 0), 'D': (-n, 0)}[command] + winterm.cursor_adjust(x, y, on_stderr=self.on_stderr) + + + def convert_osc(self, text): + for match in self.ANSI_OSC_RE.finditer(text): + start, end = match.span() + text = text[:start] + text[end:] + paramstring, command = match.groups() + if command == BEL: + if paramstring.count(";") == 1: + params = paramstring.split(";") + # 0 - change title and icon (we will only change title) + # 1 - change icon (we don't support this) + # 2 - change title + if params[0] in '02': + winterm.set_title(params[1]) + return text + + + def flush(self): + self.wrapped.flush() diff --git a/python_embeded/Lib/site-packages/colorama/initialise.py b/python_embeded/Lib/site-packages/colorama/initialise.py new file mode 100644 index 0000000000000000000000000000000000000000..d5fd4b71fed1bb4871717f978f0c470280f099c1 --- /dev/null +++ b/python_embeded/Lib/site-packages/colorama/initialise.py @@ -0,0 +1,121 @@ +# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. +import atexit +import contextlib +import sys + +from .ansitowin32 import AnsiToWin32 + + +def _wipe_internal_state_for_tests(): + global orig_stdout, orig_stderr + orig_stdout = None + orig_stderr = None + + global wrapped_stdout, wrapped_stderr + wrapped_stdout = None + wrapped_stderr = None + + global atexit_done + atexit_done = False + + global fixed_windows_console + fixed_windows_console = False + + try: + # no-op if it wasn't registered + atexit.unregister(reset_all) + except AttributeError: + # python 2: no atexit.unregister. Oh well, we did our best. + pass + + +def reset_all(): + if AnsiToWin32 is not None: # Issue #74: objects might become None at exit + AnsiToWin32(orig_stdout).reset_all() + + +def init(autoreset=False, convert=None, strip=None, wrap=True): + + if not wrap and any([autoreset, convert, strip]): + raise ValueError('wrap=False conflicts with any other arg=True') + + global wrapped_stdout, wrapped_stderr + global orig_stdout, orig_stderr + + orig_stdout = sys.stdout + orig_stderr = sys.stderr + + if sys.stdout is None: + wrapped_stdout = None + else: + sys.stdout = wrapped_stdout = \ + wrap_stream(orig_stdout, convert, strip, autoreset, wrap) + if sys.stderr is None: + wrapped_stderr = None + else: + sys.stderr = wrapped_stderr = \ + wrap_stream(orig_stderr, convert, strip, autoreset, wrap) + + global atexit_done + if not atexit_done: + atexit.register(reset_all) + atexit_done = True + + +def deinit(): + if orig_stdout is not None: + sys.stdout = orig_stdout + if orig_stderr is not None: + sys.stderr = orig_stderr + + +def just_fix_windows_console(): + global fixed_windows_console + + if sys.platform != "win32": + return + if fixed_windows_console: + return + if wrapped_stdout is not None or wrapped_stderr is not None: + # Someone already ran init() and it did stuff, so we won't second-guess them + return + + # On newer versions of Windows, AnsiToWin32.__init__ will implicitly enable the + # native ANSI support in the console as a side-effect. We only need to actually + # replace sys.stdout/stderr if we're in the old-style conversion mode. + new_stdout = AnsiToWin32(sys.stdout, convert=None, strip=None, autoreset=False) + if new_stdout.convert: + sys.stdout = new_stdout + new_stderr = AnsiToWin32(sys.stderr, convert=None, strip=None, autoreset=False) + if new_stderr.convert: + sys.stderr = new_stderr + + fixed_windows_console = True + +@contextlib.contextmanager +def colorama_text(*args, **kwargs): + init(*args, **kwargs) + try: + yield + finally: + deinit() + + +def reinit(): + if wrapped_stdout is not None: + sys.stdout = wrapped_stdout + if wrapped_stderr is not None: + sys.stderr = wrapped_stderr + + +def wrap_stream(stream, convert, strip, autoreset, wrap): + if wrap: + wrapper = AnsiToWin32(stream, + convert=convert, strip=strip, autoreset=autoreset) + if wrapper.should_wrap(): + stream = wrapper.stream + return stream + + +# Use this for initial setup as well, to reduce code duplication +_wipe_internal_state_for_tests() diff --git a/python_embeded/Lib/site-packages/colorama/winterm.py b/python_embeded/Lib/site-packages/colorama/winterm.py new file mode 100644 index 0000000000000000000000000000000000000000..aad867e8c80b826bf6a060116f17fa08a8eb0765 --- /dev/null +++ b/python_embeded/Lib/site-packages/colorama/winterm.py @@ -0,0 +1,195 @@ +# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. +try: + from msvcrt import get_osfhandle +except ImportError: + def get_osfhandle(_): + raise OSError("This isn't windows!") + + +from . import win32 + +# from wincon.h +class WinColor(object): + BLACK = 0 + BLUE = 1 + GREEN = 2 + CYAN = 3 + RED = 4 + MAGENTA = 5 + YELLOW = 6 + GREY = 7 + +# from wincon.h +class WinStyle(object): + NORMAL = 0x00 # dim text, dim background + BRIGHT = 0x08 # bright text, dim background + BRIGHT_BACKGROUND = 0x80 # dim text, bright background + +class WinTerm(object): + + def __init__(self): + self._default = win32.GetConsoleScreenBufferInfo(win32.STDOUT).wAttributes + self.set_attrs(self._default) + self._default_fore = self._fore + self._default_back = self._back + self._default_style = self._style + # In order to emulate LIGHT_EX in windows, we borrow the BRIGHT style. + # So that LIGHT_EX colors and BRIGHT style do not clobber each other, + # we track them separately, since LIGHT_EX is overwritten by Fore/Back + # and BRIGHT is overwritten by Style codes. + self._light = 0 + + def get_attrs(self): + return self._fore + self._back * 16 + (self._style | self._light) + + def set_attrs(self, value): + self._fore = value & 7 + self._back = (value >> 4) & 7 + self._style = value & (WinStyle.BRIGHT | WinStyle.BRIGHT_BACKGROUND) + + def reset_all(self, on_stderr=None): + self.set_attrs(self._default) + self.set_console(attrs=self._default) + self._light = 0 + + def fore(self, fore=None, light=False, on_stderr=False): + if fore is None: + fore = self._default_fore + self._fore = fore + # Emulate LIGHT_EX with BRIGHT Style + if light: + self._light |= WinStyle.BRIGHT + else: + self._light &= ~WinStyle.BRIGHT + self.set_console(on_stderr=on_stderr) + + def back(self, back=None, light=False, on_stderr=False): + if back is None: + back = self._default_back + self._back = back + # Emulate LIGHT_EX with BRIGHT_BACKGROUND Style + if light: + self._light |= WinStyle.BRIGHT_BACKGROUND + else: + self._light &= ~WinStyle.BRIGHT_BACKGROUND + self.set_console(on_stderr=on_stderr) + + def style(self, style=None, on_stderr=False): + if style is None: + style = self._default_style + self._style = style + self.set_console(on_stderr=on_stderr) + + def set_console(self, attrs=None, on_stderr=False): + if attrs is None: + attrs = self.get_attrs() + handle = win32.STDOUT + if on_stderr: + handle = win32.STDERR + win32.SetConsoleTextAttribute(handle, attrs) + + def get_position(self, handle): + position = win32.GetConsoleScreenBufferInfo(handle).dwCursorPosition + # Because Windows coordinates are 0-based, + # and win32.SetConsoleCursorPosition expects 1-based. + position.X += 1 + position.Y += 1 + return position + + def set_cursor_position(self, position=None, on_stderr=False): + if position is None: + # I'm not currently tracking the position, so there is no default. + # position = self.get_position() + return + handle = win32.STDOUT + if on_stderr: + handle = win32.STDERR + win32.SetConsoleCursorPosition(handle, position) + + def cursor_adjust(self, x, y, on_stderr=False): + handle = win32.STDOUT + if on_stderr: + handle = win32.STDERR + position = self.get_position(handle) + adjusted_position = (position.Y + y, position.X + x) + win32.SetConsoleCursorPosition(handle, adjusted_position, adjust=False) + + def erase_screen(self, mode=0, on_stderr=False): + # 0 should clear from the cursor to the end of the screen. + # 1 should clear from the cursor to the beginning of the screen. + # 2 should clear the entire screen, and move cursor to (1,1) + handle = win32.STDOUT + if on_stderr: + handle = win32.STDERR + csbi = win32.GetConsoleScreenBufferInfo(handle) + # get the number of character cells in the current buffer + cells_in_screen = csbi.dwSize.X * csbi.dwSize.Y + # get number of character cells before current cursor position + cells_before_cursor = csbi.dwSize.X * csbi.dwCursorPosition.Y + csbi.dwCursorPosition.X + if mode == 0: + from_coord = csbi.dwCursorPosition + cells_to_erase = cells_in_screen - cells_before_cursor + elif mode == 1: + from_coord = win32.COORD(0, 0) + cells_to_erase = cells_before_cursor + elif mode == 2: + from_coord = win32.COORD(0, 0) + cells_to_erase = cells_in_screen + else: + # invalid mode + return + # fill the entire screen with blanks + win32.FillConsoleOutputCharacter(handle, ' ', cells_to_erase, from_coord) + # now set the buffer's attributes accordingly + win32.FillConsoleOutputAttribute(handle, self.get_attrs(), cells_to_erase, from_coord) + if mode == 2: + # put the cursor where needed + win32.SetConsoleCursorPosition(handle, (1, 1)) + + def erase_line(self, mode=0, on_stderr=False): + # 0 should clear from the cursor to the end of the line. + # 1 should clear from the cursor to the beginning of the line. + # 2 should clear the entire line. + handle = win32.STDOUT + if on_stderr: + handle = win32.STDERR + csbi = win32.GetConsoleScreenBufferInfo(handle) + if mode == 0: + from_coord = csbi.dwCursorPosition + cells_to_erase = csbi.dwSize.X - csbi.dwCursorPosition.X + elif mode == 1: + from_coord = win32.COORD(0, csbi.dwCursorPosition.Y) + cells_to_erase = csbi.dwCursorPosition.X + elif mode == 2: + from_coord = win32.COORD(0, csbi.dwCursorPosition.Y) + cells_to_erase = csbi.dwSize.X + else: + # invalid mode + return + # fill the entire screen with blanks + win32.FillConsoleOutputCharacter(handle, ' ', cells_to_erase, from_coord) + # now set the buffer's attributes accordingly + win32.FillConsoleOutputAttribute(handle, self.get_attrs(), cells_to_erase, from_coord) + + def set_title(self, title): + win32.SetConsoleTitle(title) + + +def enable_vt_processing(fd): + if win32.windll is None or not win32.winapi_test(): + return False + + try: + handle = get_osfhandle(fd) + mode = win32.GetConsoleMode(handle) + win32.SetConsoleMode( + handle, + mode | win32.ENABLE_VIRTUAL_TERMINAL_PROCESSING, + ) + + mode = win32.GetConsoleMode(handle) + if mode & win32.ENABLE_VIRTUAL_TERMINAL_PROCESSING: + return True + # Can get TypeError in testsuite where 'fd' is a Mock() + except (OSError, TypeError): + return False diff --git a/python_embeded/Lib/site-packages/coloredlogs-15.0.1.dist-info/INSTALLER b/python_embeded/Lib/site-packages/coloredlogs-15.0.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/python_embeded/Lib/site-packages/coloredlogs-15.0.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/python_embeded/Lib/site-packages/coloredlogs-15.0.1.dist-info/LICENSE.txt b/python_embeded/Lib/site-packages/coloredlogs-15.0.1.dist-info/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..c152168b297a9bc75a2fbbfaa5182f4da2a697eb --- /dev/null +++ b/python_embeded/Lib/site-packages/coloredlogs-15.0.1.dist-info/LICENSE.txt @@ -0,0 +1,20 @@ +Copyright (c) 2020 Peter Odding + +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. diff --git a/python_embeded/Lib/site-packages/coloredlogs-15.0.1.dist-info/METADATA b/python_embeded/Lib/site-packages/coloredlogs-15.0.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..93337008aae17923dfad6ddd3dea9201358b868d --- /dev/null +++ b/python_embeded/Lib/site-packages/coloredlogs-15.0.1.dist-info/METADATA @@ -0,0 +1,291 @@ +Metadata-Version: 2.1 +Name: coloredlogs +Version: 15.0.1 +Summary: Colored terminal output for Python's logging module +Home-page: https://coloredlogs.readthedocs.io +Author: Peter Odding +Author-email: peter@peterodding.com +License: MIT +Platform: UNKNOWN +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: Console +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Information Technology +Classifier: Intended Audience :: System Administrators +Classifier: License :: OSI Approved :: MIT License +Classifier: Operating System :: MacOS +Classifier: Operating System :: Microsoft :: Windows +Classifier: Operating System :: POSIX +Classifier: Operating System :: Unix +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 2 +Classifier: Programming Language :: Python :: 2.7 +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.5 +Classifier: Programming Language :: Python :: 3.6 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: Communications +Classifier: Topic :: Scientific/Engineering :: Human Machine Interfaces +Classifier: Topic :: Software Development +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Topic :: Software Development :: User Interfaces +Classifier: Topic :: System +Classifier: Topic :: System :: Shells +Classifier: Topic :: System :: System Shells +Classifier: Topic :: System :: Console Fonts +Classifier: Topic :: System :: Logging +Classifier: Topic :: System :: Systems Administration +Classifier: Topic :: Terminals +Classifier: Topic :: Utilities +Requires-Python: >=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.* +Requires-Dist: humanfriendly (>=9.1) +Provides-Extra: cron +Requires-Dist: capturer (>=2.4) ; extra == 'cron' + +coloredlogs: Colored terminal output for Python's logging module +================================================================ + +.. image:: https://travis-ci.org/xolox/python-coloredlogs.svg?branch=master + :target: https://travis-ci.org/xolox/python-coloredlogs + +.. image:: https://coveralls.io/repos/github/xolox/python-coloredlogs/badge.svg?branch=master + :target: https://coveralls.io/github/xolox/python-coloredlogs?branch=master + +The `coloredlogs` package enables colored terminal output for Python's logging_ +module. The ColoredFormatter_ class inherits from `logging.Formatter`_ and uses +`ANSI escape sequences`_ to render your logging messages in color. It uses only +standard colors so it should work on any UNIX terminal. It's currently tested +on Python 2.7, 3.5+ and PyPy (2 and 3). On Windows `coloredlogs` automatically +tries to enable native ANSI support (on up-to-date Windows 10 installations) +and falls back on using colorama_ (if installed). Here is a screen shot of the +demo that is printed when the command ``coloredlogs --demo`` is executed: + +.. image:: https://coloredlogs.readthedocs.io/en/latest/_images/defaults.png + +Note that the screenshot above includes custom logging levels defined by my +verboselogs_ package: if you install both `coloredlogs` and `verboselogs` it +will Just Work (`verboselogs` is of course not required to use +`coloredlogs`). + +.. contents:: + :local: + +Installation +------------ + +The `coloredlogs` package is available on PyPI_ which means installation should +be as simple as: + +.. code-block:: console + + $ pip install coloredlogs + +There's actually a multitude of ways to install Python packages (e.g. the `per +user site-packages directory`_, `virtual environments`_ or just installing +system wide) and I have no intention of getting into that discussion here, so +if this intimidates you then read up on your options before returning to these +instructions 😉. + +Optional dependencies +~~~~~~~~~~~~~~~~~~~~~ + +Native ANSI support on Windows requires an up-to-date Windows 10 installation. +If this is not working for you then consider installing the colorama_ package: + +.. code-block:: console + + $ pip install colorama + +Once colorama_ is installed it will be used automatically. + +Usage +----- + +Here's an example of how easy it is to get started: + +.. code-block:: python + + import coloredlogs, logging + + # Create a logger object. + logger = logging.getLogger(__name__) + + # By default the install() function installs a handler on the root logger, + # this means that log messages from your code and log messages from the + # libraries that you use will all show up on the terminal. + coloredlogs.install(level='DEBUG') + + # If you don't want to see log messages from libraries, you can pass a + # specific logger object to the install() function. In this case only log + # messages originating from that logger will show up on the terminal. + coloredlogs.install(level='DEBUG', logger=logger) + + # Some examples. + logger.debug("this is a debugging message") + logger.info("this is an informational message") + logger.warning("this is a warning message") + logger.error("this is an error message") + logger.critical("this is a critical message") + +Format of log messages +---------------------- + +The ColoredFormatter_ class supports user defined log formats so you can use +any log format you like. The default log format is as follows:: + + %(asctime)s %(hostname)s %(name)s[%(process)d] %(levelname)s %(message)s + +This log format results in the following output:: + + 2015-10-23 03:32:22 peter-macbook coloredlogs.demo[30462] DEBUG message with level 'debug' + 2015-10-23 03:32:23 peter-macbook coloredlogs.demo[30462] VERBOSE message with level 'verbose' + 2015-10-23 03:32:24 peter-macbook coloredlogs.demo[30462] INFO message with level 'info' + ... + +You can customize the log format and styling using environment variables as +well as programmatically, please refer to the `online documentation`_ for +details. + +Enabling millisecond precision +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If you're switching from `logging.basicConfig()`_ to `coloredlogs.install()`_ +you may notice that timestamps no longer include milliseconds. This is because +coloredlogs doesn't output milliseconds in timestamps unless you explicitly +tell it to. There are three ways to do that: + +1. The easy way is to pass the `milliseconds` argument to `coloredlogs.install()`_:: + + coloredlogs.install(milliseconds=True) + + This became supported in `release 7.1`_ (due to `#16`_). + +2. Alternatively you can change the log format `to include 'msecs'`_:: + + %(asctime)s,%(msecs)03d %(hostname)s %(name)s[%(process)d] %(levelname)s %(message)s + + Here's what the call to `coloredlogs.install()`_ would then look like:: + + coloredlogs.install(fmt='%(asctime)s,%(msecs)03d %(hostname)s %(name)s[%(process)d] %(levelname)s %(message)s') + + Customizing the log format also enables you to change the delimiter that + separates seconds from milliseconds (the comma above). This became possible + in `release 3.0`_ which added support for user defined log formats. + +3. If the use of ``%(msecs)d`` isn't flexible enough you can instead add ``%f`` + to the date/time format, it will be replaced by the value of ``%(msecs)03d``. + Support for the ``%f`` directive was added to `release 9.3`_ (due to `#45`_). + +Custom logging fields +~~~~~~~~~~~~~~~~~~~~~ + +The following custom log format fields are supported: + +- ``%(hostname)s`` provides the hostname of the local system. +- ``%(programname)s`` provides the name of the currently running program. +- ``%(username)s`` provides the username of the currently logged in user. + +When `coloredlogs.install()`_ detects that any of these fields are used in the +format string the applicable logging.Filter_ subclasses are automatically +registered to populate the relevant log record fields. + +Changing text styles and colors +------------------------------- + +The online documentation contains `an example of customizing the text styles and +colors `_. + +Colored output from cron +------------------------ + +When `coloredlogs` is used in a cron_ job, the output that's e-mailed to you by +cron won't contain any ANSI escape sequences because `coloredlogs` realizes +that it's not attached to an interactive terminal. If you'd like to have colors +e-mailed to you by cron there are two ways to make it happen: + +.. contents:: + :local: + +Modifying your crontab +~~~~~~~~~~~~~~~~~~~~~~ + +Here's an example of a minimal crontab:: + + MAILTO="your-email-address@here" + CONTENT_TYPE="text/html" + * * * * * root coloredlogs --to-html your-command + +The ``coloredlogs`` program is installed when you install the `coloredlogs` +Python package. When you execute ``coloredlogs --to-html your-command`` it runs +``your-command`` under the external program ``script`` (you need to have this +installed). This makes ``your-command`` think that it's attached to an +interactive terminal which means it will output ANSI escape sequences which +will then be converted to HTML by the ``coloredlogs`` program. Yes, this is a +bit convoluted, but it works great :-) + +Modifying your Python code +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The ColoredCronMailer_ class provides a context manager that automatically +enables HTML output when the ``$CONTENT_TYPE`` variable has been correctly set +in the crontab. + +This requires my capturer_ package which you can install using ``pip install +'coloredlogs[cron]'``. The ``[cron]`` extra will pull in capturer_ 2.4 or newer +which is required to capture the output while silencing it - otherwise you'd +get duplicate output in the emails sent by ``cron``. + +The context manager can also be used to retroactively silence output that has +already been produced, this can be useful to avoid spammy cron jobs that have +nothing useful to do but still email their output to the system administrator +every few minutes :-). + +Contact +------- + +The latest version of `coloredlogs` is available on PyPI_ and GitHub_. The +`online documentation`_ is available on Read The Docs and includes a +changelog_. For bug reports please create an issue on GitHub_. If you have +questions, suggestions, etc. feel free to send me an e-mail at +`peter@peterodding.com`_. + +License +------- + +This software is licensed under the `MIT license`_. + +© 2020 Peter Odding. + + +.. External references: +.. _#16: https://github.com/xolox/python-coloredlogs/issues/16 +.. _#45: https://github.com/xolox/python-coloredlogs/issues/45 +.. _ANSI escape sequences: https://en.wikipedia.org/wiki/ANSI_escape_code#Colors +.. _capturer: https://pypi.org/project/capturer +.. _changelog: https://coloredlogs.readthedocs.org/en/latest/changelog.html +.. _colorama: https://pypi.org/project/colorama +.. _ColoredCronMailer: https://coloredlogs.readthedocs.io/en/latest/api.html#coloredlogs.converter.ColoredCronMailer +.. _ColoredFormatter: https://coloredlogs.readthedocs.io/en/latest/api.html#coloredlogs.ColoredFormatter +.. _coloredlogs.install(): https://coloredlogs.readthedocs.io/en/latest/api.html#coloredlogs.install +.. _cron: https://en.wikipedia.org/wiki/Cron +.. _GitHub: https://github.com/xolox/python-coloredlogs +.. _logging.basicConfig(): https://docs.python.org/2/library/logging.html#logging.basicConfig +.. _logging.Filter: https://docs.python.org/3/library/logging.html#filter-objects +.. _logging.Formatter: https://docs.python.org/2/library/logging.html#logging.Formatter +.. _logging: https://docs.python.org/2/library/logging.html +.. _MIT license: https://en.wikipedia.org/wiki/MIT_License +.. _online documentation: https://coloredlogs.readthedocs.io/ +.. _per user site-packages directory: https://www.python.org/dev/peps/pep-0370/ +.. _peter@peterodding.com: peter@peterodding.com +.. _PyPI: https://pypi.org/project/coloredlogs +.. _release 3.0: https://coloredlogs.readthedocs.io/en/latest/changelog.html#release-3-0-2015-10-23 +.. _release 7.1: https://coloredlogs.readthedocs.io/en/latest/changelog.html#release-7-1-2017-07-15 +.. _release 9.3: https://coloredlogs.readthedocs.io/en/latest/changelog.html#release-9-3-2018-04-29 +.. _to include 'msecs': https://stackoverflow.com/questions/6290739/python-logging-use-milliseconds-in-time-format +.. _verboselogs: https://pypi.org/project/verboselogs +.. _virtual environments: http://docs.python-guide.org/en/latest/dev/virtualenvs/ + + diff --git a/python_embeded/Lib/site-packages/coloredlogs-15.0.1.dist-info/RECORD b/python_embeded/Lib/site-packages/coloredlogs-15.0.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..be33ce207d5768916a735cc09f582683bd588529 --- /dev/null +++ b/python_embeded/Lib/site-packages/coloredlogs-15.0.1.dist-info/RECORD @@ -0,0 +1,23 @@ +../../Scripts/coloredlogs.exe,sha256=UpWqPnsJPyK7RTPZ6QR6loFv_v88xTUGg3TOwzTEVQo,108416 +coloredlogs-15.0.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +coloredlogs-15.0.1.dist-info/LICENSE.txt,sha256=C-9P-xhVtlVwME8gGMbUTkurl71d-HFuzXgAAU1xcmc,1056 +coloredlogs-15.0.1.dist-info/METADATA,sha256=FmO6unRvNe77JJ2UU0XYhWbMTzZDhj6zGpEljDysZ0w,12387 +coloredlogs-15.0.1.dist-info/RECORD,, +coloredlogs-15.0.1.dist-info/WHEEL,sha256=kGT74LWyRUZrL4VgLh6_g12IeVl_9u9ZVhadrgXZUEY,110 +coloredlogs-15.0.1.dist-info/entry_points.txt,sha256=uOmYMPjy7X6effmVh56i3U3N9S13DTRozJOAncBtZG0,54 +coloredlogs-15.0.1.dist-info/top_level.txt,sha256=D3LuRvusEQ8xKUhPowPUmPWNm88FSw8ts3x2ulvCSyQ,12 +coloredlogs.pth,sha256=3ag6hVmG76XNh_AkiwGZwAhusOjn_s59Z0GVnFzjlTY,147 +coloredlogs/__init__.py,sha256=FxaiI1pQ0JzRYbx2K5f_Ar9Wa1meZLg5XKGWHKgPBNo,64423 +coloredlogs/__pycache__/__init__.cpython-312.pyc,, +coloredlogs/__pycache__/cli.cpython-312.pyc,, +coloredlogs/__pycache__/demo.cpython-312.pyc,, +coloredlogs/__pycache__/syslog.cpython-312.pyc,, +coloredlogs/__pycache__/tests.cpython-312.pyc,, +coloredlogs/cli.py,sha256=iaHgUVeHPl5iIecKG1WJMslOJEKdhEusbxj7B4r1sHI,3493 +coloredlogs/converter/__init__.py,sha256=t08e9V8-Ed9y9eNSYv3x1DH0hXgaXHJmQWp54j_a2nk,18353 +coloredlogs/converter/__pycache__/__init__.cpython-312.pyc,, +coloredlogs/converter/__pycache__/colors.cpython-312.pyc,, +coloredlogs/converter/colors.py,sha256=1N2PpCa-EYMMWyC6Dw7SG2WX1gC67F9F5OteeFW52SM,5387 +coloredlogs/demo.py,sha256=CaPVGOB6rCtJDyeqk0VBLi0t05jgUEniuB__VYo5kho,1825 +coloredlogs/syslog.py,sha256=-XyRUzI20QKTTtVqhJAtfYc-ljw0crsjxqjWDjqrcqU,11849 +coloredlogs/tests.py,sha256=oe_pWnTGfNEI7spY3_VA62fX_09ZEVFVERvr9sBMqnM,30791 diff --git a/python_embeded/Lib/site-packages/coloredlogs-15.0.1.dist-info/WHEEL b/python_embeded/Lib/site-packages/coloredlogs-15.0.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..ef99c6cf3283b50a273ac4c6d009a0aa85597070 --- /dev/null +++ b/python_embeded/Lib/site-packages/coloredlogs-15.0.1.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.34.2) +Root-Is-Purelib: true +Tag: py2-none-any +Tag: py3-none-any + diff --git a/python_embeded/Lib/site-packages/coloredlogs-15.0.1.dist-info/entry_points.txt b/python_embeded/Lib/site-packages/coloredlogs-15.0.1.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..564b838819160cc551845ac8081430321204c337 --- /dev/null +++ b/python_embeded/Lib/site-packages/coloredlogs-15.0.1.dist-info/entry_points.txt @@ -0,0 +1,3 @@ +[console_scripts] +coloredlogs = coloredlogs.cli:main + diff --git a/python_embeded/Lib/site-packages/coloredlogs-15.0.1.dist-info/top_level.txt b/python_embeded/Lib/site-packages/coloredlogs-15.0.1.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..4a6c8e5f402cdf0187f21f905837324f39075fb0 --- /dev/null +++ b/python_embeded/Lib/site-packages/coloredlogs-15.0.1.dist-info/top_level.txt @@ -0,0 +1 @@ +coloredlogs diff --git a/python_embeded/Lib/site-packages/coloredlogs/__init__.py b/python_embeded/Lib/site-packages/coloredlogs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d728128217571cf4c04cfeb4ee29c776addd759e --- /dev/null +++ b/python_embeded/Lib/site-packages/coloredlogs/__init__.py @@ -0,0 +1,1524 @@ +# Colored terminal output for Python's logging module. +# +# Author: Peter Odding +# Last Change: June 11, 2021 +# URL: https://coloredlogs.readthedocs.io + +""" +Colored terminal output for Python's :mod:`logging` module. + +.. contents:: + :local: + +Getting started +=============== + +The easiest way to get started is by importing :mod:`coloredlogs` and calling +:mod:`coloredlogs.install()` (similar to :func:`logging.basicConfig()`): + + >>> import coloredlogs, logging + >>> coloredlogs.install(level='DEBUG') + >>> logger = logging.getLogger('some.module.name') + >>> logger.info("this is an informational message") + 2015-10-22 19:13:52 peter-macbook some.module.name[28036] INFO this is an informational message + +The :mod:`~coloredlogs.install()` function creates a :class:`ColoredFormatter` +that injects `ANSI escape sequences`_ into the log output. + +.. _ANSI escape sequences: https://en.wikipedia.org/wiki/ANSI_escape_code#Colors + +Environment variables +===================== + +The following environment variables can be used to configure the +:mod:`coloredlogs` module without writing any code: + +============================= ============================ ================================== +Environment variable Default value Type of value +============================= ============================ ================================== +``$COLOREDLOGS_AUTO_INSTALL`` 'false' a boolean that controls whether + :func:`auto_install()` is called +``$COLOREDLOGS_LOG_LEVEL`` 'INFO' a log level name +``$COLOREDLOGS_LOG_FORMAT`` :data:`DEFAULT_LOG_FORMAT` a log format string +``$COLOREDLOGS_DATE_FORMAT`` :data:`DEFAULT_DATE_FORMAT` a date/time format string +``$COLOREDLOGS_LEVEL_STYLES`` :data:`DEFAULT_LEVEL_STYLES` see :func:`parse_encoded_styles()` +``$COLOREDLOGS_FIELD_STYLES`` :data:`DEFAULT_FIELD_STYLES` see :func:`parse_encoded_styles()` +============================= ============================ ================================== + +If the environment variable `$NO_COLOR`_ is set (the value doesn't matter, even +an empty string will do) then :func:`coloredlogs.install()` will take this as a +hint that colors should not be used (unless the ``isatty=True`` override was +passed by the caller). + +.. _$NO_COLOR: https://no-color.org/ + +Examples of customization +========================= + +Here we'll take a look at some examples of how you can customize +:mod:`coloredlogs` using environment variables. + +.. contents:: + :local: + +About the defaults +------------------ + +Here's a screen shot of the default configuration for easy comparison with the +screen shots of the following customizations (this is the same screen shot that +is shown in the introduction): + +.. image:: images/defaults.png + :alt: Screen shot of colored logging with defaults. + +The screen shot above was taken from ``urxvt`` which doesn't support faint text +colors, otherwise the color of green used for `debug` messages would have +differed slightly from the color of green used for `spam` messages. + +Apart from the `faint` style of the `spam` level, the default configuration of +`coloredlogs` sticks to the eight color palette defined by the original ANSI +standard, in order to provide a somewhat consistent experience across terminals +and terminal emulators. + +Available text styles and colors +-------------------------------- + +Of course you are free to customize the default configuration, in this case you +can use any text style or color that you know is supported by your terminal. +You can use the ``humanfriendly --demo`` command to try out the supported text +styles and colors: + +.. image:: http://humanfriendly.readthedocs.io/en/latest/_images/ansi-demo.png + :alt: Screen shot of the 'humanfriendly --demo' command. + +Changing the log format +----------------------- + +The simplest customization is to change the log format, for example: + +.. literalinclude:: examples/custom-log-format.txt + :language: console + +Here's what that looks like in a terminal (I always work in terminals with a +black background and white text): + +.. image:: images/custom-log-format.png + :alt: Screen shot of colored logging with custom log format. + +Changing the date/time format +----------------------------- + +You can also change the date/time format, for example you can remove the date +part and leave only the time: + +.. literalinclude:: examples/custom-datetime-format.txt + :language: console + +Here's what it looks like in a terminal: + +.. image:: images/custom-datetime-format.png + :alt: Screen shot of colored logging with custom date/time format. + +Changing the colors/styles +-------------------------- + +Finally you can customize the colors and text styles that are used: + +.. literalinclude:: examples/custom-colors.txt + :language: console + +Here's an explanation of the features used here: + +- The numbers used in ``$COLOREDLOGS_LEVEL_STYLES`` demonstrate the use of 256 + color mode (the numbers refer to the 256 color mode palette which is fixed). + +- The `success` level demonstrates the use of a text style (bold). + +- The `critical` level demonstrates the use of a background color (red). + +Of course none of this can be seen in the shell transcript quoted above, but +take a look at the following screen shot: + +.. image:: images/custom-colors.png + :alt: Screen shot of colored logging with custom colors. + +.. _notes about log levels: + +Some notes about log levels +=========================== + +With regards to the handling of log levels, the :mod:`coloredlogs` package +differs from Python's :mod:`logging` module in two aspects: + +1. While the :mod:`logging` module uses the default logging level + :data:`logging.WARNING`, the :mod:`coloredlogs` package has always used + :data:`logging.INFO` as its default log level. + +2. When logging to the terminal or system log is initialized by + :func:`install()` or :func:`.enable_system_logging()` the effective + level [#]_ of the selected logger [#]_ is compared against the requested + level [#]_ and if the effective level is more restrictive than the requested + level, the logger's level will be set to the requested level (this happens + in :func:`adjust_level()`). The reason for this is to work around a + combination of design choices in Python's :mod:`logging` module that can + easily confuse people who aren't already intimately familiar with it: + + - All loggers are initialized with the level :data:`logging.NOTSET`. + + - When a logger's level is set to :data:`logging.NOTSET` the + :func:`~logging.Logger.getEffectiveLevel()` method will + fall back to the level of the parent logger. + + - The parent of all loggers is the root logger and the root logger has its + level set to :data:`logging.WARNING` by default (after importing the + :mod:`logging` module). + + Effectively all user defined loggers inherit the default log level + :data:`logging.WARNING` from the root logger, which isn't very intuitive for + those who aren't already familiar with the hierarchical nature of the + :mod:`logging` module. + + By avoiding this potentially confusing behavior (see `#14`_, `#18`_, `#21`_, + `#23`_ and `#24`_), while at the same time allowing the caller to specify a + logger object, my goal and hope is to provide sane defaults that can easily + be changed when the need arises. + + .. [#] Refer to :func:`logging.Logger.getEffectiveLevel()` for details. + .. [#] The logger that is passed as an argument by the caller or the root + logger which is selected as a default when no logger is provided. + .. [#] The log level that is passed as an argument by the caller or the + default log level :data:`logging.INFO` when no level is provided. + + .. _#14: https://github.com/xolox/python-coloredlogs/issues/14 + .. _#18: https://github.com/xolox/python-coloredlogs/issues/18 + .. _#21: https://github.com/xolox/python-coloredlogs/pull/21 + .. _#23: https://github.com/xolox/python-coloredlogs/pull/23 + .. _#24: https://github.com/xolox/python-coloredlogs/issues/24 + +Classes and functions +===================== +""" + +# Standard library modules. +import collections +import logging +import os +import re +import socket +import sys + +# External dependencies. +from humanfriendly import coerce_boolean +from humanfriendly.compat import coerce_string, is_string, on_windows +from humanfriendly.terminal import ANSI_COLOR_CODES, ansi_wrap, enable_ansi_support, terminal_supports_colors +from humanfriendly.text import format, split + +# Semi-standard module versioning. +__version__ = '15.0.1' + +DEFAULT_LOG_LEVEL = logging.INFO +"""The default log level for :mod:`coloredlogs` (:data:`logging.INFO`).""" + +DEFAULT_LOG_FORMAT = '%(asctime)s %(hostname)s %(name)s[%(process)d] %(levelname)s %(message)s' +"""The default log format for :class:`ColoredFormatter` objects (a string).""" + +DEFAULT_DATE_FORMAT = '%Y-%m-%d %H:%M:%S' +"""The default date/time format for :class:`ColoredFormatter` objects (a string).""" + +CHROOT_FILES = ['/etc/debian_chroot'] +"""A list of filenames that indicate a chroot and contain the name of the chroot.""" + +DEFAULT_FIELD_STYLES = dict( + asctime=dict(color='green'), + hostname=dict(color='magenta'), + levelname=dict(color='black', bold=True), + name=dict(color='blue'), + programname=dict(color='cyan'), + username=dict(color='yellow'), +) +"""Mapping of log format names to default font styles.""" + +DEFAULT_LEVEL_STYLES = dict( + spam=dict(color='green', faint=True), + debug=dict(color='green'), + verbose=dict(color='blue'), + info=dict(), + notice=dict(color='magenta'), + warning=dict(color='yellow'), + success=dict(color='green', bold=True), + error=dict(color='red'), + critical=dict(color='red', bold=True), +) +"""Mapping of log level names to default font styles.""" + +DEFAULT_FORMAT_STYLE = '%' +"""The default logging format style (a single character).""" + +FORMAT_STYLE_PATTERNS = { + '%': r'%\((\w+)\)[#0 +-]*\d*(?:\.\d+)?[hlL]?[diouxXeEfFgGcrs%]', + '{': r'{(\w+)[^}]*}', + '$': r'\$(\w+)|\${(\w+)}', +} +""" +A dictionary that maps the `style` characters ``%``, ``{`` and ``$`` (see the +documentation of the :class:`python3:logging.Formatter` class in Python 3.2+) +to strings containing regular expression patterns that can be used to parse +format strings in the corresponding style: + +``%`` + A string containing a regular expression that matches a "percent conversion + specifier" as defined in the `String Formatting Operations`_ section of the + Python documentation. Here's an example of a logging format string in this + format: ``%(levelname)s:%(name)s:%(message)s``. + +``{`` + A string containing a regular expression that matches a "replacement field" as + defined in the `Format String Syntax`_ section of the Python documentation. + Here's an example of a logging format string in this format: + ``{levelname}:{name}:{message}``. + +``$`` + A string containing a regular expression that matches a "substitution + placeholder" as defined in the `Template Strings`_ section of the Python + documentation. Here's an example of a logging format string in this format: + ``$levelname:$name:$message``. + +These regular expressions are used by :class:`FormatStringParser` to introspect +and manipulate logging format strings. + +.. _String Formatting Operations: https://docs.python.org/2/library/stdtypes.html#string-formatting +.. _Format String Syntax: https://docs.python.org/2/library/string.html#formatstrings +.. _Template Strings: https://docs.python.org/3/library/string.html#template-strings +""" + + +def auto_install(): + """ + Automatically call :func:`install()` when ``$COLOREDLOGS_AUTO_INSTALL`` is set. + + The `coloredlogs` package includes a `path configuration file`_ that + automatically imports the :mod:`coloredlogs` module and calls + :func:`auto_install()` when the environment variable + ``$COLOREDLOGS_AUTO_INSTALL`` is set. + + This function uses :func:`~humanfriendly.coerce_boolean()` to check whether + the value of ``$COLOREDLOGS_AUTO_INSTALL`` should be considered :data:`True`. + + .. _path configuration file: https://docs.python.org/2/library/site.html#module-site + """ + if coerce_boolean(os.environ.get('COLOREDLOGS_AUTO_INSTALL', 'false')): + install() + + +def install(level=None, **kw): + """ + Enable colored terminal output for Python's :mod:`logging` module. + + :param level: The default logging level (an integer or a string with a + level name, defaults to :data:`DEFAULT_LOG_LEVEL`). + :param logger: The logger to which the stream handler should be attached (a + :class:`~logging.Logger` object, defaults to the root logger). + :param fmt: Set the logging format (a string like those accepted by + :class:`~logging.Formatter`, defaults to + :data:`DEFAULT_LOG_FORMAT`). + :param datefmt: Set the date/time format (a string, defaults to + :data:`DEFAULT_DATE_FORMAT`). + :param style: One of the characters ``%``, ``{`` or ``$`` (defaults to + :data:`DEFAULT_FORMAT_STYLE`). See the documentation of the + :class:`python3:logging.Formatter` class in Python 3.2+. On + older Python versions only ``%`` is supported. + :param milliseconds: :data:`True` to show milliseconds like :mod:`logging` + does by default, :data:`False` to hide milliseconds + (the default is :data:`False`, see `#16`_). + :param level_styles: A dictionary with custom level styles (defaults to + :data:`DEFAULT_LEVEL_STYLES`). + :param field_styles: A dictionary with custom field styles (defaults to + :data:`DEFAULT_FIELD_STYLES`). + :param stream: The stream where log messages should be written to (a + file-like object). This defaults to :data:`None` which + means :class:`StandardErrorHandler` is used. + :param isatty: :data:`True` to use a :class:`ColoredFormatter`, + :data:`False` to use a normal :class:`~logging.Formatter` + (defaults to auto-detection using + :func:`~humanfriendly.terminal.terminal_supports_colors()`). + :param reconfigure: If :data:`True` (the default) multiple calls to + :func:`coloredlogs.install()` will each override + the previous configuration. + :param use_chroot: Refer to :class:`HostNameFilter`. + :param programname: Refer to :class:`ProgramNameFilter`. + :param username: Refer to :class:`UserNameFilter`. + :param syslog: If :data:`True` then :func:`.enable_system_logging()` will + be called without arguments (defaults to :data:`False`). The + `syslog` argument may also be a number or string, in this + case it is assumed to be a logging level which is passed on + to :func:`.enable_system_logging()`. + + The :func:`coloredlogs.install()` function is similar to + :func:`logging.basicConfig()`, both functions take a lot of optional + keyword arguments but try to do the right thing by default: + + 1. If `reconfigure` is :data:`True` (it is by default) and an existing + :class:`~logging.StreamHandler` is found that is connected to either + :data:`~sys.stdout` or :data:`~sys.stderr` the handler will be removed. + This means that first calling :func:`logging.basicConfig()` and then + calling :func:`coloredlogs.install()` will replace the stream handler + instead of adding a duplicate stream handler. If `reconfigure` is + :data:`False` and an existing handler is found no further steps are + taken (to avoid installing a duplicate stream handler). + + 2. A :class:`~logging.StreamHandler` is created and connected to the stream + given by the `stream` keyword argument (:data:`sys.stderr` by + default). The stream handler's level is set to the value of the `level` + keyword argument. + + 3. A :class:`ColoredFormatter` is created if the `isatty` keyword argument + allows it (or auto-detection allows it), otherwise a normal + :class:`~logging.Formatter` is created. The formatter is initialized + with the `fmt` and `datefmt` keyword arguments (or their computed + defaults). + + The environment variable ``$NO_COLOR`` is taken as a hint by + auto-detection that colors should not be used. + + 4. :func:`HostNameFilter.install()`, :func:`ProgramNameFilter.install()` + and :func:`UserNameFilter.install()` are called to enable the use of + additional fields in the log format. + + 5. If the logger's level is too restrictive it is relaxed (refer to `notes + about log levels`_ for details). + + 6. The formatter is added to the handler and the handler is added to the + logger. + + .. _#16: https://github.com/xolox/python-coloredlogs/issues/16 + """ + logger = kw.get('logger') or logging.getLogger() + reconfigure = kw.get('reconfigure', True) + stream = kw.get('stream') or sys.stderr + style = check_style(kw.get('style') or DEFAULT_FORMAT_STYLE) + # Get the log level from an argument, environment variable or default and + # convert the names of log levels to numbers to enable numeric comparison. + if level is None: + level = os.environ.get('COLOREDLOGS_LOG_LEVEL', DEFAULT_LOG_LEVEL) + level = level_to_number(level) + # Remove any existing stream handler that writes to stdout or stderr, even + # if the stream handler wasn't created by coloredlogs because multiple + # stream handlers (in the same hierarchy) writing to stdout or stderr would + # create duplicate output. `None' is a synonym for the possibly dynamic + # value of the stderr attribute of the sys module. + match_streams = ([sys.stdout, sys.stderr] + if stream in [sys.stdout, sys.stderr, None] + else [stream]) + match_handler = lambda handler: match_stream_handler(handler, match_streams) + handler, logger = replace_handler(logger, match_handler, reconfigure) + # Make sure reconfiguration is allowed or not relevant. + if not (handler and not reconfigure): + # Make it easy to enable system logging. + syslog_enabled = kw.get('syslog') + # We ignore the value `None' because it means the caller didn't opt in + # to system logging and `False' because it means the caller explicitly + # opted out of system logging. + if syslog_enabled not in (None, False): + from coloredlogs.syslog import enable_system_logging + if syslog_enabled is True: + # If the caller passed syslog=True then we leave the choice of + # default log level up to the coloredlogs.syslog module. + enable_system_logging() + else: + # Values other than (None, True, False) are assumed to + # represent a logging level for system logging. + enable_system_logging(level=syslog_enabled) + # Figure out whether we can use ANSI escape sequences. + use_colors = kw.get('isatty', None) + # In the following indented block the expression (use_colors is None) + # can be read as "auto detect is enabled and no reason has yet been + # found to automatically disable color support". + if use_colors or (use_colors is None): + # Respect the user's choice not to have colors. + if use_colors is None and 'NO_COLOR' in os.environ: + # For details on this see https://no-color.org/. + use_colors = False + # Try to enable Windows native ANSI support or Colorama? + if (use_colors or use_colors is None) and on_windows(): + # This can fail, in which case ANSI escape sequences would end + # up being printed to the terminal in raw form. This is very + # user hostile, so to avoid this happening we disable color + # support on failure. + use_colors = enable_ansi_support() + # When auto detection is enabled, and so far we encountered no + # reason to disable color support, then we will enable color + # support if 'stream' is connected to a terminal. + if use_colors is None: + use_colors = terminal_supports_colors(stream) + # Create a stream handler and make sure to preserve any filters + # the current handler may have (if an existing handler is found). + filters = handler.filters if handler else None + if stream is sys.stderr: + handler = StandardErrorHandler() + else: + handler = logging.StreamHandler(stream) + handler.setLevel(level) + if filters: + handler.filters = filters + # Prepare the arguments to the formatter, allowing the caller to + # customize the values of `fmt', `datefmt' and `style' as desired. + formatter_options = dict(fmt=kw.get('fmt'), datefmt=kw.get('datefmt')) + # Only pass the `style' argument to the formatter when the caller + # provided an alternative logging format style. This prevents + # TypeError exceptions on Python versions before 3.2. + if style != DEFAULT_FORMAT_STYLE: + formatter_options['style'] = style + # Come up with a default log format? + if not formatter_options['fmt']: + # Use the log format defined by the environment variable + # $COLOREDLOGS_LOG_FORMAT or fall back to the default. + formatter_options['fmt'] = os.environ.get('COLOREDLOGS_LOG_FORMAT') or DEFAULT_LOG_FORMAT + # If the caller didn't specify a date/time format we'll use the format + # defined by the environment variable $COLOREDLOGS_DATE_FORMAT (or fall + # back to the default). + if not formatter_options['datefmt']: + formatter_options['datefmt'] = os.environ.get('COLOREDLOGS_DATE_FORMAT') or DEFAULT_DATE_FORMAT + # Python's logging module shows milliseconds by default through special + # handling in the logging.Formatter.formatTime() method [1]. Because + # coloredlogs always defines a `datefmt' it bypasses this special + # handling, which is fine because ever since publishing coloredlogs + # I've never needed millisecond precision ;-). However there are users + # of coloredlogs that do want milliseconds to be shown [2] so we + # provide a shortcut to make it easy. + # + # [1] https://stackoverflow.com/questions/6290739/python-logging-use-milliseconds-in-time-format + # [2] https://github.com/xolox/python-coloredlogs/issues/16 + if kw.get('milliseconds'): + parser = FormatStringParser(style=style) + if not (parser.contains_field(formatter_options['fmt'], 'msecs') + or '%f' in formatter_options['datefmt']): + pattern = parser.get_pattern('asctime') + replacements = {'%': '%(msecs)03d', '{': '{msecs:03}', '$': '${msecs}'} + formatter_options['fmt'] = pattern.sub( + r'\g<0>,' + replacements[style], + formatter_options['fmt'], + ) + # Do we need to make %(hostname) available to the formatter? + HostNameFilter.install( + fmt=formatter_options['fmt'], + handler=handler, + style=style, + use_chroot=kw.get('use_chroot', True), + ) + # Do we need to make %(programname) available to the formatter? + ProgramNameFilter.install( + fmt=formatter_options['fmt'], + handler=handler, + programname=kw.get('programname'), + style=style, + ) + # Do we need to make %(username) available to the formatter? + UserNameFilter.install( + fmt=formatter_options['fmt'], + handler=handler, + username=kw.get('username'), + style=style, + ) + # Inject additional formatter arguments specific to ColoredFormatter? + if use_colors: + for name, environment_name in (('field_styles', 'COLOREDLOGS_FIELD_STYLES'), + ('level_styles', 'COLOREDLOGS_LEVEL_STYLES')): + value = kw.get(name) + if value is None: + # If no styles have been specified we'll fall back + # to the styles defined by the environment variable. + environment_value = os.environ.get(environment_name) + if environment_value is not None: + value = parse_encoded_styles(environment_value) + if value is not None: + formatter_options[name] = value + # Create a (possibly colored) formatter. + formatter_type = ColoredFormatter if use_colors else BasicFormatter + handler.setFormatter(formatter_type(**formatter_options)) + # Adjust the level of the selected logger. + adjust_level(logger, level) + # Install the stream handler. + logger.addHandler(handler) + + +def check_style(value): + """ + Validate a logging format style. + + :param value: The logging format style to validate (any value). + :returns: The logging format character (a string of one character). + :raises: :exc:`~exceptions.ValueError` when the given style isn't supported. + + On Python 3.2+ this function accepts the logging format styles ``%``, ``{`` + and ``$`` while on older versions only ``%`` is accepted (because older + Python versions don't support alternative logging format styles). + """ + if sys.version_info[:2] >= (3, 2): + if value not in FORMAT_STYLE_PATTERNS: + msg = "Unsupported logging format style! (%r)" + raise ValueError(format(msg, value)) + elif value != DEFAULT_FORMAT_STYLE: + msg = "Format string styles other than %r require Python 3.2+!" + raise ValueError(msg, DEFAULT_FORMAT_STYLE) + return value + + +def increase_verbosity(): + """ + Increase the verbosity of the root handler by one defined level. + + Understands custom logging levels like defined by my ``verboselogs`` + module. + """ + defined_levels = sorted(set(find_defined_levels().values())) + current_index = defined_levels.index(get_level()) + selected_index = max(0, current_index - 1) + set_level(defined_levels[selected_index]) + + +def decrease_verbosity(): + """ + Decrease the verbosity of the root handler by one defined level. + + Understands custom logging levels like defined by my ``verboselogs`` + module. + """ + defined_levels = sorted(set(find_defined_levels().values())) + current_index = defined_levels.index(get_level()) + selected_index = min(current_index + 1, len(defined_levels) - 1) + set_level(defined_levels[selected_index]) + + +def is_verbose(): + """ + Check whether the log level of the root handler is set to a verbose level. + + :returns: ``True`` if the root handler is verbose, ``False`` if not. + """ + return get_level() < DEFAULT_LOG_LEVEL + + +def get_level(): + """ + Get the logging level of the root handler. + + :returns: The logging level of the root handler (an integer) or + :data:`DEFAULT_LOG_LEVEL` (if no root handler exists). + """ + handler, logger = find_handler(logging.getLogger(), match_stream_handler) + return handler.level if handler else DEFAULT_LOG_LEVEL + + +def set_level(level): + """ + Set the logging level of the root handler. + + :param level: The logging level to filter on (an integer or string). + + If no root handler exists yet this automatically calls :func:`install()`. + """ + handler, logger = find_handler(logging.getLogger(), match_stream_handler) + if handler and logger: + # Change the level of the existing handler. + handler.setLevel(level_to_number(level)) + # Adjust the level of the selected logger. + adjust_level(logger, level) + else: + # Create a new handler with the given level. + install(level=level) + + +def adjust_level(logger, level): + """ + Increase a logger's verbosity up to the requested level. + + :param logger: The logger to change (a :class:`~logging.Logger` object). + :param level: The log level to enable (a string or number). + + This function is used by functions like :func:`install()`, + :func:`increase_verbosity()` and :func:`.enable_system_logging()` to adjust + a logger's level so that log messages up to the requested log level are + propagated to the configured output handler(s). + + It uses :func:`logging.Logger.getEffectiveLevel()` to check whether + `logger` propagates or swallows log messages of the requested `level` and + sets the logger's level to the requested level if it would otherwise + swallow log messages. + + Effectively this function will "widen the scope of logging" when asked to + do so but it will never "narrow the scope of logging". This is because I am + convinced that filtering of log messages should (primarily) be decided by + handlers. + """ + level = level_to_number(level) + if logger.getEffectiveLevel() > level: + logger.setLevel(level) + + +def find_defined_levels(): + """ + Find the defined logging levels. + + :returns: A dictionary with level names as keys and integers as values. + + Here's what the result looks like by default (when + no custom levels or level names have been defined): + + >>> find_defined_levels() + {'NOTSET': 0, + 'DEBUG': 10, + 'INFO': 20, + 'WARN': 30, + 'WARNING': 30, + 'ERROR': 40, + 'FATAL': 50, + 'CRITICAL': 50} + """ + defined_levels = {} + for name in dir(logging): + if name.isupper(): + value = getattr(logging, name) + if isinstance(value, int): + defined_levels[name] = value + return defined_levels + + +def level_to_number(value): + """ + Coerce a logging level name to a number. + + :param value: A logging level (integer or string). + :returns: The number of the log level (an integer). + + This function translates log level names into their numeric values.. + """ + if is_string(value): + try: + defined_levels = find_defined_levels() + value = defined_levels[value.upper()] + except KeyError: + # Don't fail on unsupported log levels. + value = DEFAULT_LOG_LEVEL + return value + + +def find_level_aliases(): + """ + Find log level names which are aliases of each other. + + :returns: A dictionary that maps aliases to their canonical name. + + .. note:: Canonical names are chosen to be the alias with the longest + string length so that e.g. ``WARN`` is an alias for ``WARNING`` + instead of the other way around. + + Here's what the result looks like by default (when + no custom levels or level names have been defined): + + >>> from coloredlogs import find_level_aliases + >>> find_level_aliases() + {'WARN': 'WARNING', 'FATAL': 'CRITICAL'} + """ + mapping = collections.defaultdict(list) + for name, value in find_defined_levels().items(): + mapping[value].append(name) + aliases = {} + for value, names in mapping.items(): + if len(names) > 1: + names = sorted(names, key=lambda n: len(n)) + canonical_name = names.pop() + for alias in names: + aliases[alias] = canonical_name + return aliases + + +def parse_encoded_styles(text, normalize_key=None): + """ + Parse text styles encoded in a string into a nested data structure. + + :param text: The encoded styles (a string). + :returns: A dictionary in the structure of the :data:`DEFAULT_FIELD_STYLES` + and :data:`DEFAULT_LEVEL_STYLES` dictionaries. + + Here's an example of how this function works: + + >>> from coloredlogs import parse_encoded_styles + >>> from pprint import pprint + >>> encoded_styles = 'debug=green;warning=yellow;error=red;critical=red,bold' + >>> pprint(parse_encoded_styles(encoded_styles)) + {'debug': {'color': 'green'}, + 'warning': {'color': 'yellow'}, + 'error': {'color': 'red'}, + 'critical': {'bold': True, 'color': 'red'}} + """ + parsed_styles = {} + for assignment in split(text, ';'): + name, _, styles = assignment.partition('=') + target = parsed_styles.setdefault(name, {}) + for token in split(styles, ','): + # When this code was originally written, setting background colors + # wasn't supported yet, so there was no need to disambiguate + # between the text color and background color. This explains why + # a color name or number implies setting the text color (for + # backwards compatibility). + if token.isdigit(): + target['color'] = int(token) + elif token in ANSI_COLOR_CODES: + target['color'] = token + elif '=' in token: + name, _, value = token.partition('=') + if name in ('color', 'background'): + if value.isdigit(): + target[name] = int(value) + elif value in ANSI_COLOR_CODES: + target[name] = value + else: + target[token] = True + return parsed_styles + + +def find_hostname(use_chroot=True): + """ + Find the host name to include in log messages. + + :param use_chroot: Use the name of the chroot when inside a chroot? + (boolean, defaults to :data:`True`) + :returns: A suitable host name (a string). + + Looks for :data:`CHROOT_FILES` that have a nonempty first line (taken to be + the chroot name). If none are found then :func:`socket.gethostname()` is + used as a fall back. + """ + for chroot_file in CHROOT_FILES: + try: + with open(chroot_file) as handle: + first_line = next(handle) + name = first_line.strip() + if name: + return name + except Exception: + pass + return socket.gethostname() + + +def find_program_name(): + """ + Select a suitable program name to embed in log messages. + + :returns: One of the following strings (in decreasing order of preference): + + 1. The base name of the currently running Python program or + script (based on the value at index zero of :data:`sys.argv`). + 2. The base name of the Python executable (based on + :data:`sys.executable`). + 3. The string 'python'. + """ + # Gotcha: sys.argv[0] is '-c' if Python is started with the -c option. + return ((os.path.basename(sys.argv[0]) if sys.argv and sys.argv[0] != '-c' else '') + or (os.path.basename(sys.executable) if sys.executable else '') + or 'python') + + +def find_username(): + """ + Find the username to include in log messages. + + :returns: A suitable username (a string). + + On UNIX systems this uses the :mod:`pwd` module which means ``root`` will + be reported when :man:`sudo` is used (as it should). If this fails (for + example on Windows) then :func:`getpass.getuser()` is used as a fall back. + """ + try: + import pwd + uid = os.getuid() + entry = pwd.getpwuid(uid) + return entry.pw_name + except Exception: + import getpass + return getpass.getuser() + + +def replace_handler(logger, match_handler, reconfigure): + """ + Prepare to replace a handler. + + :param logger: Refer to :func:`find_handler()`. + :param match_handler: Refer to :func:`find_handler()`. + :param reconfigure: :data:`True` if an existing handler should be replaced, + :data:`False` otherwise. + :returns: A tuple of two values: + + 1. The matched :class:`~logging.Handler` object or :data:`None` + if no handler was matched. + 2. The :class:`~logging.Logger` to which the matched handler was + attached or the logger given to :func:`replace_handler()`. + """ + handler, other_logger = find_handler(logger, match_handler) + if handler and other_logger and reconfigure: + # Remove the existing handler from the logger that its attached to + # so that we can install a new handler that behaves differently. + other_logger.removeHandler(handler) + # Switch to the logger that the existing handler was attached to so + # that reconfiguration doesn't narrow the scope of logging. + logger = other_logger + return handler, logger + + +def find_handler(logger, match_handler): + """ + Find a (specific type of) handler in the propagation tree of a logger. + + :param logger: The logger to check (a :class:`~logging.Logger` object). + :param match_handler: A callable that receives a :class:`~logging.Handler` + object and returns :data:`True` to match a handler or + :data:`False` to skip that handler and continue + searching for a match. + :returns: A tuple of two values: + + 1. The matched :class:`~logging.Handler` object or :data:`None` + if no handler was matched. + 2. The :class:`~logging.Logger` object to which the handler is + attached or :data:`None` if no handler was matched. + + This function finds a logging handler (of the given type) attached to a + logger or one of its parents (see :func:`walk_propagation_tree()`). It uses + the undocumented :class:`~logging.Logger.handlers` attribute to find + handlers attached to a logger, however it won't raise an exception if the + attribute isn't available. The advantages of this approach are: + + - This works regardless of whether :mod:`coloredlogs` attached the handler + or other Python code attached the handler. + + - This will correctly recognize the situation where the given logger has no + handlers but :attr:`~logging.Logger.propagate` is enabled and the logger + has a parent logger that does have a handler attached. + """ + for logger in walk_propagation_tree(logger): + for handler in getattr(logger, 'handlers', []): + if match_handler(handler): + return handler, logger + return None, None + + +def match_stream_handler(handler, streams=[]): + """ + Identify stream handlers writing to the given streams(s). + + :param handler: The :class:`~logging.Handler` class to check. + :param streams: A sequence of streams to match (defaults to matching + :data:`~sys.stdout` and :data:`~sys.stderr`). + :returns: :data:`True` if the handler is a :class:`~logging.StreamHandler` + logging to the given stream(s), :data:`False` otherwise. + + This function can be used as a callback for :func:`find_handler()`. + """ + return (isinstance(handler, logging.StreamHandler) + and getattr(handler, 'stream') in (streams or (sys.stdout, sys.stderr))) + + +def walk_propagation_tree(logger): + """ + Walk through the propagation hierarchy of the given logger. + + :param logger: The logger whose hierarchy to walk (a + :class:`~logging.Logger` object). + :returns: A generator of :class:`~logging.Logger` objects. + + .. note:: This uses the undocumented :class:`logging.Logger.parent` + attribute to find higher level loggers, however it won't + raise an exception if the attribute isn't available. + """ + while isinstance(logger, logging.Logger): + # Yield the logger to our caller. + yield logger + # Check if the logger has propagation enabled. + if logger.propagate: + # Continue with the parent logger. We use getattr() because the + # `parent' attribute isn't documented so properly speaking we + # shouldn't break if it's not available. + logger = getattr(logger, 'parent', None) + else: + # The propagation chain stops here. + logger = None + + +class BasicFormatter(logging.Formatter): + + """ + Log :class:`~logging.Formatter` that supports ``%f`` for millisecond formatting. + + This class extends :class:`~logging.Formatter` to enable the use of ``%f`` + for millisecond formatting in date/time strings, to allow for the type of + flexibility requested in issue `#45`_. + + .. _#45: https://github.com/xolox/python-coloredlogs/issues/45 + """ + + def formatTime(self, record, datefmt=None): + """ + Format the date/time of a log record. + + :param record: A :class:`~logging.LogRecord` object. + :param datefmt: A date/time format string (defaults to :data:`DEFAULT_DATE_FORMAT`). + :returns: The formatted date/time (a string). + + This method overrides :func:`~logging.Formatter.formatTime()` to set + `datefmt` to :data:`DEFAULT_DATE_FORMAT` when the caller hasn't + specified a date format. + + When `datefmt` contains the token ``%f`` it will be replaced by the + value of ``%(msecs)03d`` (refer to issue `#45`_ for use cases). + """ + # The default value of the following argument is defined here so + # that Sphinx doesn't embed the default value in the generated + # documentation (because the result is awkward to read). + datefmt = datefmt or DEFAULT_DATE_FORMAT + # Replace %f with the value of %(msecs)03d. + if '%f' in datefmt: + datefmt = datefmt.replace('%f', '%03d' % record.msecs) + # Delegate the actual date/time formatting to the base formatter. + return logging.Formatter.formatTime(self, record, datefmt) + + +class ColoredFormatter(BasicFormatter): + + """ + Log :class:`~logging.Formatter` that uses `ANSI escape sequences`_ to create colored logs. + + :class:`ColoredFormatter` inherits from :class:`BasicFormatter` to enable + the use of ``%f`` for millisecond formatting in date/time strings. + + .. note:: If you want to use :class:`ColoredFormatter` on Windows then you + need to call :func:`~humanfriendly.terminal.enable_ansi_support()`. + This is done for you when you call :func:`coloredlogs.install()`. + """ + + def __init__(self, fmt=None, datefmt=None, style=DEFAULT_FORMAT_STYLE, level_styles=None, field_styles=None): + """ + Initialize a :class:`ColoredFormatter` object. + + :param fmt: A log format string (defaults to :data:`DEFAULT_LOG_FORMAT`). + :param datefmt: A date/time format string (defaults to :data:`None`, + but see the documentation of + :func:`BasicFormatter.formatTime()`). + :param style: One of the characters ``%``, ``{`` or ``$`` (defaults to + :data:`DEFAULT_FORMAT_STYLE`) + :param level_styles: A dictionary with custom level styles + (defaults to :data:`DEFAULT_LEVEL_STYLES`). + :param field_styles: A dictionary with custom field styles + (defaults to :data:`DEFAULT_FIELD_STYLES`). + :raises: Refer to :func:`check_style()`. + + This initializer uses :func:`colorize_format()` to inject ANSI escape + sequences in the log format string before it is passed to the + initializer of the base class. + """ + self.nn = NameNormalizer() + # The default values of the following arguments are defined here so + # that Sphinx doesn't embed the default values in the generated + # documentation (because the result is awkward to read). + fmt = fmt or DEFAULT_LOG_FORMAT + self.level_styles = self.nn.normalize_keys(DEFAULT_LEVEL_STYLES if level_styles is None else level_styles) + self.field_styles = self.nn.normalize_keys(DEFAULT_FIELD_STYLES if field_styles is None else field_styles) + # Rewrite the format string to inject ANSI escape sequences. + kw = dict(fmt=self.colorize_format(fmt, style), datefmt=datefmt) + # If we were given a non-default logging format style we pass it on + # to our superclass. At this point check_style() will have already + # complained that the use of alternative logging format styles + # requires Python 3.2 or newer. + if style != DEFAULT_FORMAT_STYLE: + kw['style'] = style + # Initialize the superclass with the rewritten format string. + logging.Formatter.__init__(self, **kw) + + def colorize_format(self, fmt, style=DEFAULT_FORMAT_STYLE): + """ + Rewrite a logging format string to inject ANSI escape sequences. + + :param fmt: The log format string. + :param style: One of the characters ``%``, ``{`` or ``$`` (defaults to + :data:`DEFAULT_FORMAT_STYLE`). + :returns: The logging format string with ANSI escape sequences. + + This method takes a logging format string like the ones you give to + :class:`logging.Formatter` and processes it as follows: + + 1. First the logging format string is separated into formatting + directives versus surrounding text (according to the given `style`). + + 2. Then formatting directives and surrounding text are grouped + based on whitespace delimiters (in the surrounding text). + + 3. For each group styling is selected as follows: + + 1. If the group contains a single formatting directive that has + a style defined then the whole group is styled accordingly. + + 2. If the group contains multiple formatting directives that + have styles defined then each formatting directive is styled + individually and surrounding text isn't styled. + + As an example consider the default log format (:data:`DEFAULT_LOG_FORMAT`):: + + %(asctime)s %(hostname)s %(name)s[%(process)d] %(levelname)s %(message)s + + The default field styles (:data:`DEFAULT_FIELD_STYLES`) define a style for the + `name` field but not for the `process` field, however because both fields + are part of the same whitespace delimited token they'll be highlighted + together in the style defined for the `name` field. + """ + result = [] + parser = FormatStringParser(style=style) + for group in parser.get_grouped_pairs(fmt): + applicable_styles = [self.nn.get(self.field_styles, token.name) for token in group if token.name] + if sum(map(bool, applicable_styles)) == 1: + # If exactly one (1) field style is available for the group of + # tokens then all of the tokens will be styled the same way. + # This provides a limited form of backwards compatibility with + # the (intended) behavior of coloredlogs before the release of + # version 10. + result.append(ansi_wrap( + ''.join(token.text for token in group), + **next(s for s in applicable_styles if s) + )) + else: + for token in group: + text = token.text + if token.name: + field_styles = self.nn.get(self.field_styles, token.name) + if field_styles: + text = ansi_wrap(text, **field_styles) + result.append(text) + return ''.join(result) + + def format(self, record): + """ + Apply level-specific styling to log records. + + :param record: A :class:`~logging.LogRecord` object. + :returns: The result of :func:`logging.Formatter.format()`. + + This method injects ANSI escape sequences that are specific to the + level of each log record (because such logic cannot be expressed in the + syntax of a log format string). It works by making a copy of the log + record, changing the `msg` field inside the copy and passing the copy + into the :func:`~logging.Formatter.format()` method of the base + class. + """ + style = self.nn.get(self.level_styles, record.levelname) + # After the introduction of the `Empty' class it was reported in issue + # 33 that format() can be called when `Empty' has already been garbage + # collected. This explains the (otherwise rather out of place) `Empty + # is not None' check in the following `if' statement. The reasoning + # here is that it's much better to log a message without formatting + # then to raise an exception ;-). + # + # For more details refer to issue 33 on GitHub: + # https://github.com/xolox/python-coloredlogs/issues/33 + if style and Empty is not None: + # Due to the way that Python's logging module is structured and + # documented the only (IMHO) clean way to customize its behavior is + # to change incoming LogRecord objects before they get to the base + # formatter. However we don't want to break other formatters and + # handlers, so we copy the log record. + # + # In the past this used copy.copy() but as reported in issue 29 + # (which is reproducible) this can cause deadlocks. The following + # Python voodoo is intended to accomplish the same thing as + # copy.copy() without all of the generalization and overhead that + # we don't need for our -very limited- use case. + # + # For more details refer to issue 29 on GitHub: + # https://github.com/xolox/python-coloredlogs/issues/29 + copy = Empty() + copy.__class__ = record.__class__ + copy.__dict__.update(record.__dict__) + copy.msg = ansi_wrap(coerce_string(record.msg), **style) + record = copy + # Delegate the remaining formatting to the base formatter. + return logging.Formatter.format(self, record) + + +class Empty(object): + """An empty class used to copy :class:`~logging.LogRecord` objects without reinitializing them.""" + + +class HostNameFilter(logging.Filter): + + """ + Log filter to enable the ``%(hostname)s`` format. + + Python's :mod:`logging` module doesn't expose the system's host name while + I consider this to be a valuable addition. Fortunately it's very easy to + expose additional fields in format strings: :func:`filter()` simply sets + the ``hostname`` attribute of each :class:`~logging.LogRecord` object it + receives and this is enough to enable the use of the ``%(hostname)s`` + expression in format strings. + + You can install this log filter as follows:: + + >>> import coloredlogs, logging + >>> handler = logging.StreamHandler() + >>> handler.addFilter(coloredlogs.HostNameFilter()) + >>> handler.setFormatter(logging.Formatter('[%(hostname)s] %(message)s')) + >>> logger = logging.getLogger() + >>> logger.addHandler(handler) + >>> logger.setLevel(logging.INFO) + >>> logger.info("Does it work?") + [peter-macbook] Does it work? + + Of course :func:`coloredlogs.install()` does all of this for you :-). + """ + + @classmethod + def install(cls, handler, fmt=None, use_chroot=True, style=DEFAULT_FORMAT_STYLE): + """ + Install the :class:`HostNameFilter` on a log handler (only if needed). + + :param fmt: The log format string to check for ``%(hostname)``. + :param style: One of the characters ``%``, ``{`` or ``$`` (defaults to + :data:`DEFAULT_FORMAT_STYLE`). + :param handler: The logging handler on which to install the filter. + :param use_chroot: Refer to :func:`find_hostname()`. + + If `fmt` is given the filter will only be installed if `fmt` uses the + ``hostname`` field. If `fmt` is not given the filter is installed + unconditionally. + """ + if fmt: + parser = FormatStringParser(style=style) + if not parser.contains_field(fmt, 'hostname'): + return + handler.addFilter(cls(use_chroot)) + + def __init__(self, use_chroot=True): + """ + Initialize a :class:`HostNameFilter` object. + + :param use_chroot: Refer to :func:`find_hostname()`. + """ + self.hostname = find_hostname(use_chroot) + + def filter(self, record): + """Set each :class:`~logging.LogRecord`'s `hostname` field.""" + # Modify the record. + record.hostname = self.hostname + # Don't filter the record. + return 1 + + +class ProgramNameFilter(logging.Filter): + + """ + Log filter to enable the ``%(programname)s`` format. + + Python's :mod:`logging` module doesn't expose the name of the currently + running program while I consider this to be a useful addition. Fortunately + it's very easy to expose additional fields in format strings: + :func:`filter()` simply sets the ``programname`` attribute of each + :class:`~logging.LogRecord` object it receives and this is enough to enable + the use of the ``%(programname)s`` expression in format strings. + + Refer to :class:`HostNameFilter` for an example of how to manually install + these log filters. + """ + + @classmethod + def install(cls, handler, fmt, programname=None, style=DEFAULT_FORMAT_STYLE): + """ + Install the :class:`ProgramNameFilter` (only if needed). + + :param fmt: The log format string to check for ``%(programname)``. + :param style: One of the characters ``%``, ``{`` or ``$`` (defaults to + :data:`DEFAULT_FORMAT_STYLE`). + :param handler: The logging handler on which to install the filter. + :param programname: Refer to :func:`__init__()`. + + If `fmt` is given the filter will only be installed if `fmt` uses the + ``programname`` field. If `fmt` is not given the filter is installed + unconditionally. + """ + if fmt: + parser = FormatStringParser(style=style) + if not parser.contains_field(fmt, 'programname'): + return + handler.addFilter(cls(programname)) + + def __init__(self, programname=None): + """ + Initialize a :class:`ProgramNameFilter` object. + + :param programname: The program name to use (defaults to the result of + :func:`find_program_name()`). + """ + self.programname = programname or find_program_name() + + def filter(self, record): + """Set each :class:`~logging.LogRecord`'s `programname` field.""" + # Modify the record. + record.programname = self.programname + # Don't filter the record. + return 1 + + +class UserNameFilter(logging.Filter): + + """ + Log filter to enable the ``%(username)s`` format. + + Python's :mod:`logging` module doesn't expose the username of the currently + logged in user as requested in `#76`_. Given that :class:`HostNameFilter` + and :class:`ProgramNameFilter` are already provided by `coloredlogs` it + made sense to provide :class:`UserNameFilter` as well. + + Refer to :class:`HostNameFilter` for an example of how to manually install + these log filters. + + .. _#76: https://github.com/xolox/python-coloredlogs/issues/76 + """ + + @classmethod + def install(cls, handler, fmt, username=None, style=DEFAULT_FORMAT_STYLE): + """ + Install the :class:`UserNameFilter` (only if needed). + + :param fmt: The log format string to check for ``%(username)``. + :param style: One of the characters ``%``, ``{`` or ``$`` (defaults to + :data:`DEFAULT_FORMAT_STYLE`). + :param handler: The logging handler on which to install the filter. + :param username: Refer to :func:`__init__()`. + + If `fmt` is given the filter will only be installed if `fmt` uses the + ``username`` field. If `fmt` is not given the filter is installed + unconditionally. + """ + if fmt: + parser = FormatStringParser(style=style) + if not parser.contains_field(fmt, 'username'): + return + handler.addFilter(cls(username)) + + def __init__(self, username=None): + """ + Initialize a :class:`UserNameFilter` object. + + :param username: The username to use (defaults to the + result of :func:`find_username()`). + """ + self.username = username or find_username() + + def filter(self, record): + """Set each :class:`~logging.LogRecord`'s `username` field.""" + # Modify the record. + record.username = self.username + # Don't filter the record. + return 1 + + +class StandardErrorHandler(logging.StreamHandler): + + """ + A :class:`~logging.StreamHandler` that gets the value of :data:`sys.stderr` for each log message. + + The :class:`StandardErrorHandler` class enables `monkey patching of + sys.stderr `_. It's + basically the same as the ``logging._StderrHandler`` class present in + Python 3 but it will be available regardless of Python version. This + handler is used by :func:`coloredlogs.install()` to improve compatibility + with the Python standard library. + """ + + def __init__(self, level=logging.NOTSET): + """Initialize a :class:`StandardErrorHandler` object.""" + logging.Handler.__init__(self, level) + + @property + def stream(self): + """Get the value of :data:`sys.stderr` (a file-like object).""" + return sys.stderr + + +class FormatStringParser(object): + + """ + Shallow logging format string parser. + + This class enables introspection and manipulation of logging format strings + in the three styles supported by the :mod:`logging` module starting from + Python 3.2 (``%``, ``{`` and ``$``). + """ + + def __init__(self, style=DEFAULT_FORMAT_STYLE): + """ + Initialize a :class:`FormatStringParser` object. + + :param style: One of the characters ``%``, ``{`` or ``$`` (defaults to + :data:`DEFAULT_FORMAT_STYLE`). + :raises: Refer to :func:`check_style()`. + """ + self.style = check_style(style) + self.capturing_pattern = FORMAT_STYLE_PATTERNS[style] + # Remove the capture group around the mapping key / field name. + self.raw_pattern = self.capturing_pattern.replace(r'(\w+)', r'\w+') + # After removing the inner capture group we add an outer capture group + # to make the pattern suitable for simple tokenization using re.split(). + self.tokenize_pattern = re.compile('(%s)' % self.raw_pattern, re.VERBOSE) + # Compile a regular expression for finding field names. + self.name_pattern = re.compile(self.capturing_pattern, re.VERBOSE) + + def contains_field(self, format_string, field_name): + """ + Get the field names referenced by a format string. + + :param format_string: The logging format string. + :returns: A list of strings with field names. + """ + return field_name in self.get_field_names(format_string) + + def get_field_names(self, format_string): + """ + Get the field names referenced by a format string. + + :param format_string: The logging format string. + :returns: A list of strings with field names. + """ + return self.name_pattern.findall(format_string) + + def get_grouped_pairs(self, format_string): + """ + Group the results of :func:`get_pairs()` separated by whitespace. + + :param format_string: The logging format string. + :returns: A list of lists of :class:`FormatStringToken` objects. + """ + # Step 1: Split simple tokens (without a name) into + # their whitespace parts and non-whitespace parts. + separated = [] + pattern = re.compile(r'(\s+)') + for token in self.get_pairs(format_string): + if token.name: + separated.append(token) + else: + separated.extend( + FormatStringToken(name=None, text=text) + for text in pattern.split(token.text) if text + ) + # Step 2: Group tokens together based on whitespace. + current_group = [] + grouped_pairs = [] + for token in separated: + if token.text.isspace(): + if current_group: + grouped_pairs.append(current_group) + grouped_pairs.append([token]) + current_group = [] + else: + current_group.append(token) + if current_group: + grouped_pairs.append(current_group) + return grouped_pairs + + def get_pairs(self, format_string): + """ + Tokenize a logging format string and extract field names from tokens. + + :param format_string: The logging format string. + :returns: A generator of :class:`FormatStringToken` objects. + """ + for token in self.get_tokens(format_string): + match = self.name_pattern.search(token) + name = match.group(1) if match else None + yield FormatStringToken(name=name, text=token) + + def get_pattern(self, field_name): + """ + Get a regular expression to match a formatting directive that references the given field name. + + :param field_name: The name of the field to match (a string). + :returns: A compiled regular expression object. + """ + return re.compile(self.raw_pattern.replace(r'\w+', field_name), re.VERBOSE) + + def get_tokens(self, format_string): + """ + Tokenize a logging format string. + + :param format_string: The logging format string. + :returns: A list of strings with formatting directives separated from surrounding text. + """ + return [t for t in self.tokenize_pattern.split(format_string) if t] + + +class FormatStringToken(collections.namedtuple('FormatStringToken', 'text, name')): + + """ + A named tuple for the results of :func:`FormatStringParser.get_pairs()`. + + .. attribute:: name + + The field name referenced in `text` (a string). If `text` doesn't + contain a formatting directive this will be :data:`None`. + + .. attribute:: text + + The text extracted from the logging format string (a string). + """ + + +class NameNormalizer(object): + + """Responsible for normalizing field and level names.""" + + def __init__(self): + """Initialize a :class:`NameNormalizer` object.""" + self.aliases = {k.lower(): v.lower() for k, v in find_level_aliases().items()} + + def normalize_name(self, name): + """ + Normalize a field or level name. + + :param name: The field or level name (a string). + :returns: The normalized name (a string). + + Transforms all strings to lowercase and resolves level name aliases + (refer to :func:`find_level_aliases()`) to their canonical name: + + >>> from coloredlogs import NameNormalizer + >>> from humanfriendly import format_table + >>> nn = NameNormalizer() + >>> sample_names = ['DEBUG', 'INFO', 'WARN', 'WARNING', 'ERROR', 'FATAL', 'CRITICAL'] + >>> print(format_table([(n, nn.normalize_name(n)) for n in sample_names])) + ----------------------- + | DEBUG | debug | + | INFO | info | + | WARN | warning | + | WARNING | warning | + | ERROR | error | + | FATAL | critical | + | CRITICAL | critical | + ----------------------- + """ + name = name.lower() + if name in self.aliases: + name = self.aliases[name] + return name + + def normalize_keys(self, value): + """ + Normalize the keys of a dictionary using :func:`normalize_name()`. + + :param value: The dictionary to normalize. + :returns: A dictionary with normalized keys. + """ + return {self.normalize_name(k): v for k, v in value.items()} + + def get(self, normalized_dict, name): + """ + Get a value from a dictionary after normalizing the key. + + :param normalized_dict: A dictionary produced by :func:`normalize_keys()`. + :param name: A key to normalize and get from the dictionary. + :returns: The value of the normalized key (if any). + """ + return normalized_dict.get(self.normalize_name(name)) diff --git a/python_embeded/Lib/site-packages/coloredlogs/cli.py b/python_embeded/Lib/site-packages/coloredlogs/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..d3133363857e0a8b1c99312ec6bf1f03eb2243bd --- /dev/null +++ b/python_embeded/Lib/site-packages/coloredlogs/cli.py @@ -0,0 +1,106 @@ +# Command line interface for the coloredlogs package. +# +# Author: Peter Odding +# Last Change: December 15, 2017 +# URL: https://coloredlogs.readthedocs.io + +""" +Usage: coloredlogs [OPTIONS] [ARGS] + +The coloredlogs program provides a simple command line interface for the Python +package by the same name. + +Supported options: + + -c, --convert, --to-html + + Capture the output of an external command (given by the positional + arguments) and convert ANSI escape sequences in the output to HTML. + + If the `coloredlogs' program is attached to an interactive terminal it will + write the generated HTML to a temporary file and open that file in a web + browser, otherwise the generated HTML will be written to standard output. + + This requires the `script' program to fake the external command into + thinking that it's attached to an interactive terminal (in order to enable + output of ANSI escape sequences). + + If the command didn't produce any output then no HTML will be produced on + standard output, this is to avoid empty emails from cron jobs. + + -d, --demo + + Perform a simple demonstration of the coloredlogs package to show the + colored logging on an interactive terminal. + + -h, --help + + Show this message and exit. +""" + +# Standard library modules. +import functools +import getopt +import logging +import sys +import tempfile +import webbrowser + +# External dependencies. +from humanfriendly.terminal import connected_to_terminal, output, usage, warning + +# Modules included in our package. +from coloredlogs.converter import capture, convert +from coloredlogs.demo import demonstrate_colored_logging + +# Initialize a logger for this module. +logger = logging.getLogger(__name__) + + +def main(): + """Command line interface for the ``coloredlogs`` program.""" + actions = [] + try: + # Parse the command line arguments. + options, arguments = getopt.getopt(sys.argv[1:], 'cdh', [ + 'convert', 'to-html', 'demo', 'help', + ]) + # Map command line options to actions. + for option, value in options: + if option in ('-c', '--convert', '--to-html'): + actions.append(functools.partial(convert_command_output, *arguments)) + arguments = [] + elif option in ('-d', '--demo'): + actions.append(demonstrate_colored_logging) + elif option in ('-h', '--help'): + usage(__doc__) + return + else: + assert False, "Programming error: Unhandled option!" + if not actions: + usage(__doc__) + return + except Exception as e: + warning("Error: %s", e) + sys.exit(1) + for function in actions: + function() + + +def convert_command_output(*command): + """ + Command line interface for ``coloredlogs --to-html``. + + Takes a command (and its arguments) and runs the program under ``script`` + (emulating an interactive terminal), intercepts the output of the command + and converts ANSI escape sequences in the output to HTML. + """ + captured_output = capture(command) + converted_output = convert(captured_output) + if connected_to_terminal(): + fd, temporary_file = tempfile.mkstemp(suffix='.html') + with open(temporary_file, 'w') as handle: + handle.write(converted_output) + webbrowser.open(temporary_file) + elif captured_output and not captured_output.isspace(): + output(converted_output) diff --git a/python_embeded/Lib/site-packages/coloredlogs/demo.py b/python_embeded/Lib/site-packages/coloredlogs/demo.py new file mode 100644 index 0000000000000000000000000000000000000000..7d38af556c79b07aa39d57b50e6f61d1209fba05 --- /dev/null +++ b/python_embeded/Lib/site-packages/coloredlogs/demo.py @@ -0,0 +1,49 @@ +# Demonstration of the coloredlogs package. +# +# Author: Peter Odding +# Last Change: January 14, 2018 +# URL: https://coloredlogs.readthedocs.io + +"""A simple demonstration of the `coloredlogs` package.""" + +# Standard library modules. +import os +import time + +# Modules included in our package. +import coloredlogs + +# If my verbose logger is installed, we'll use that for the demo. +try: + from verboselogs import VerboseLogger as getLogger +except ImportError: + from logging import getLogger + +# Initialize a logger for this module. +logger = getLogger(__name__) + +DEMO_DELAY = float(os.environ.get('COLOREDLOGS_DEMO_DELAY', '1')) +"""The number of seconds between each message emitted by :func:`demonstrate_colored_logging()`.""" + + +def demonstrate_colored_logging(): + """Interactively demonstrate the :mod:`coloredlogs` package.""" + # Determine the available logging levels and order them by numeric value. + decorated_levels = [] + defined_levels = coloredlogs.find_defined_levels() + normalizer = coloredlogs.NameNormalizer() + for name, level in defined_levels.items(): + if name != 'NOTSET': + item = (level, normalizer.normalize_name(name)) + if item not in decorated_levels: + decorated_levels.append(item) + ordered_levels = sorted(decorated_levels) + # Initialize colored output to the terminal, default to the most + # verbose logging level but enable the user the customize it. + coloredlogs.install(level=os.environ.get('COLOREDLOGS_LOG_LEVEL', ordered_levels[0][1])) + # Print some examples with different timestamps. + for level, name in ordered_levels: + log_method = getattr(logger, name, None) + if log_method: + log_method("message with level %s (%i)", name, level) + time.sleep(DEMO_DELAY) diff --git a/python_embeded/Lib/site-packages/coloredlogs/syslog.py b/python_embeded/Lib/site-packages/coloredlogs/syslog.py new file mode 100644 index 0000000000000000000000000000000000000000..5fd4629ab56288bbfe0269ae6ba619db5d3756bc --- /dev/null +++ b/python_embeded/Lib/site-packages/coloredlogs/syslog.py @@ -0,0 +1,292 @@ +# Easy to use system logging for Python's logging module. +# +# Author: Peter Odding +# Last Change: December 10, 2020 +# URL: https://coloredlogs.readthedocs.io + +""" +Easy to use UNIX system logging for Python's :mod:`logging` module. + +Admittedly system logging has little to do with colored terminal output, however: + +- The `coloredlogs` package is my attempt to do Python logging right and system + logging is an important part of that equation. + +- I've seen a surprising number of quirks and mistakes in system logging done + in Python, for example including ``%(asctime)s`` in a format string (the + system logging daemon is responsible for adding timestamps and thus you end + up with duplicate timestamps that make the logs awful to read :-). + +- The ``%(programname)s`` filter originated in my system logging code and I + wanted it in `coloredlogs` so the step to include this module wasn't that big. + +- As a bonus this Python module now has a test suite and proper documentation. + +So there :-P. Go take a look at :func:`enable_system_logging()`. +""" + +# Standard library modules. +import logging +import logging.handlers +import os +import socket +import sys + +# External dependencies. +from humanfriendly import coerce_boolean +from humanfriendly.compat import on_macos, on_windows + +# Modules included in our package. +from coloredlogs import ( + DEFAULT_LOG_LEVEL, + ProgramNameFilter, + adjust_level, + find_program_name, + level_to_number, + replace_handler, +) + +LOG_DEVICE_MACOSX = '/var/run/syslog' +"""The pathname of the log device on Mac OS X (a string).""" + +LOG_DEVICE_UNIX = '/dev/log' +"""The pathname of the log device on Linux and most other UNIX systems (a string).""" + +DEFAULT_LOG_FORMAT = '%(programname)s[%(process)d]: %(levelname)s %(message)s' +""" +The default format for log messages sent to the system log (a string). + +The ``%(programname)s`` format requires :class:`~coloredlogs.ProgramNameFilter` +but :func:`enable_system_logging()` takes care of this for you. + +The ``name[pid]:`` construct (specifically the colon) in the format allows +rsyslogd_ to extract the ``$programname`` from each log message, which in turn +allows configuration files in ``/etc/rsyslog.d/*.conf`` to filter these log +messages to a separate log file (if the need arises). + +.. _rsyslogd: https://en.wikipedia.org/wiki/Rsyslog +""" + +# Initialize a logger for this module. +logger = logging.getLogger(__name__) + + +class SystemLogging(object): + + """Context manager to enable system logging.""" + + def __init__(self, *args, **kw): + """ + Initialize a :class:`SystemLogging` object. + + :param args: Positional arguments to :func:`enable_system_logging()`. + :param kw: Keyword arguments to :func:`enable_system_logging()`. + """ + self.args = args + self.kw = kw + self.handler = None + + def __enter__(self): + """Enable system logging when entering the context.""" + if self.handler is None: + self.handler = enable_system_logging(*self.args, **self.kw) + return self.handler + + def __exit__(self, exc_type=None, exc_value=None, traceback=None): + """ + Disable system logging when leaving the context. + + .. note:: If an exception is being handled when we leave the context a + warning message including traceback is logged *before* system + logging is disabled. + """ + if self.handler is not None: + if exc_type is not None: + logger.warning("Disabling system logging due to unhandled exception!", exc_info=True) + (self.kw.get('logger') or logging.getLogger()).removeHandler(self.handler) + self.handler = None + + +def enable_system_logging(programname=None, fmt=None, logger=None, reconfigure=True, **kw): + """ + Redirect :mod:`logging` messages to the system log (e.g. ``/var/log/syslog``). + + :param programname: The program name to embed in log messages (a string, defaults + to the result of :func:`~coloredlogs.find_program_name()`). + :param fmt: The log format for system log messages (a string, defaults to + :data:`DEFAULT_LOG_FORMAT`). + :param logger: The logger to which the :class:`~logging.handlers.SysLogHandler` + should be connected (defaults to the root logger). + :param level: The logging level for the :class:`~logging.handlers.SysLogHandler` + (defaults to :data:`.DEFAULT_LOG_LEVEL`). This value is coerced + using :func:`~coloredlogs.level_to_number()`. + :param reconfigure: If :data:`True` (the default) multiple calls to + :func:`enable_system_logging()` will each override + the previous configuration. + :param kw: Refer to :func:`connect_to_syslog()`. + :returns: A :class:`~logging.handlers.SysLogHandler` object or + :data:`None`. If an existing handler is found and `reconfigure` + is :data:`False` the existing handler object is returned. If the + connection to the system logging daemon fails :data:`None` is + returned. + + As of release 15.0 this function uses :func:`is_syslog_supported()` to + check whether system logging is supported and appropriate before it's + enabled. + + .. note:: When the logger's effective level is too restrictive it is + relaxed (refer to `notes about log levels`_ for details). + """ + # Check whether system logging is supported / appropriate. + if not is_syslog_supported(): + return None + # Provide defaults for omitted arguments. + programname = programname or find_program_name() + logger = logger or logging.getLogger() + fmt = fmt or DEFAULT_LOG_FORMAT + level = level_to_number(kw.get('level', DEFAULT_LOG_LEVEL)) + # Check whether system logging is already enabled. + handler, logger = replace_handler(logger, match_syslog_handler, reconfigure) + # Make sure reconfiguration is allowed or not relevant. + if not (handler and not reconfigure): + # Create a system logging handler. + handler = connect_to_syslog(**kw) + # Make sure the handler was successfully created. + if handler: + # Enable the use of %(programname)s. + ProgramNameFilter.install(handler=handler, fmt=fmt, programname=programname) + # Connect the formatter, handler and logger. + handler.setFormatter(logging.Formatter(fmt)) + logger.addHandler(handler) + # Adjust the level of the selected logger. + adjust_level(logger, level) + return handler + + +def connect_to_syslog(address=None, facility=None, level=None): + """ + Create a :class:`~logging.handlers.SysLogHandler`. + + :param address: The device file or network address of the system logging + daemon (a string or tuple, defaults to the result of + :func:`find_syslog_address()`). + :param facility: Refer to :class:`~logging.handlers.SysLogHandler`. + Defaults to ``LOG_USER``. + :param level: The logging level for the :class:`~logging.handlers.SysLogHandler` + (defaults to :data:`.DEFAULT_LOG_LEVEL`). This value is coerced + using :func:`~coloredlogs.level_to_number()`. + :returns: A :class:`~logging.handlers.SysLogHandler` object or :data:`None` (if the + system logging daemon is unavailable). + + The process of connecting to the system logging daemon goes as follows: + + - The following two socket types are tried (in decreasing preference): + + 1. :data:`~socket.SOCK_RAW` avoids truncation of log messages but may + not be supported. + 2. :data:`~socket.SOCK_STREAM` (TCP) supports longer messages than the + default (which is UDP). + """ + if not address: + address = find_syslog_address() + if facility is None: + facility = logging.handlers.SysLogHandler.LOG_USER + if level is None: + level = DEFAULT_LOG_LEVEL + for socktype in socket.SOCK_RAW, socket.SOCK_STREAM, None: + kw = dict(facility=facility, address=address) + if socktype is not None: + kw['socktype'] = socktype + try: + handler = logging.handlers.SysLogHandler(**kw) + except IOError: + # IOError is a superclass of socket.error which can be raised if the system + # logging daemon is unavailable. + pass + else: + handler.setLevel(level_to_number(level)) + return handler + + +def find_syslog_address(): + """ + Find the most suitable destination for system log messages. + + :returns: The pathname of a log device (a string) or an address/port tuple as + supported by :class:`~logging.handlers.SysLogHandler`. + + On Mac OS X this prefers :data:`LOG_DEVICE_MACOSX`, after that :data:`LOG_DEVICE_UNIX` + is checked for existence. If both of these device files don't exist the default used + by :class:`~logging.handlers.SysLogHandler` is returned. + """ + if sys.platform == 'darwin' and os.path.exists(LOG_DEVICE_MACOSX): + return LOG_DEVICE_MACOSX + elif os.path.exists(LOG_DEVICE_UNIX): + return LOG_DEVICE_UNIX + else: + return 'localhost', logging.handlers.SYSLOG_UDP_PORT + + +def is_syslog_supported(): + """ + Determine whether system logging is supported. + + :returns: + + :data:`True` if system logging is supported and can be enabled, + :data:`False` if system logging is not supported or there are good + reasons for not enabling it. + + The decision making process here is as follows: + + Override + If the environment variable ``$COLOREDLOGS_SYSLOG`` is set it is evaluated + using :func:`~humanfriendly.coerce_boolean()` and the resulting value + overrides the platform detection discussed below, this allows users to + override the decision making process if they disagree / know better. + + Linux / UNIX + On systems that are not Windows or MacOS (see below) we assume UNIX which + means either syslog is available or sending a bunch of UDP packets to + nowhere won't hurt anyone... + + Microsoft Windows + Over the years I've had multiple reports of :pypi:`coloredlogs` spewing + extremely verbose errno 10057 warning messages to the console (once for + each log message I suppose) so I now assume it a default that + "syslog-style system logging" is not generally available on Windows. + + Apple MacOS + There's cPython issue `#38780`_ which seems to result in a fatal exception + when the Python interpreter shuts down. This is (way) worse than not + having system logging enabled. The error message mentioned in `#38780`_ + has actually been following me around for years now, see for example: + + - https://github.com/xolox/python-rotate-backups/issues/9 mentions Docker + images implying Linux, so not strictly the same as `#38780`_. + + - https://github.com/xolox/python-npm-accel/issues/4 is definitely related + to `#38780`_ and is what eventually prompted me to add the + :func:`is_syslog_supported()` logic. + + .. _#38780: https://bugs.python.org/issue38780 + """ + override = os.environ.get("COLOREDLOGS_SYSLOG") + if override is not None: + return coerce_boolean(override) + else: + return not (on_windows() or on_macos()) + + +def match_syslog_handler(handler): + """ + Identify system logging handlers. + + :param handler: The :class:`~logging.Handler` class to check. + :returns: :data:`True` if the handler is a + :class:`~logging.handlers.SysLogHandler`, + :data:`False` otherwise. + + This function can be used as a callback for :func:`.find_handler()`. + """ + return isinstance(handler, logging.handlers.SysLogHandler) diff --git a/python_embeded/Lib/site-packages/coloredlogs/tests.py b/python_embeded/Lib/site-packages/coloredlogs/tests.py new file mode 100644 index 0000000000000000000000000000000000000000..650d3281a8584c1e863347643444f55db463edf9 --- /dev/null +++ b/python_embeded/Lib/site-packages/coloredlogs/tests.py @@ -0,0 +1,673 @@ +# Automated tests for the `coloredlogs' package. +# +# Author: Peter Odding +# Last Change: June 11, 2021 +# URL: https://coloredlogs.readthedocs.io + +"""Automated tests for the `coloredlogs` package.""" + +# Standard library modules. +import contextlib +import logging +import logging.handlers +import os +import re +import subprocess +import sys +import tempfile + +# External dependencies. +from humanfriendly.compat import StringIO +from humanfriendly.terminal import ANSI_COLOR_CODES, ANSI_CSI, ansi_style, ansi_wrap +from humanfriendly.testing import PatchedAttribute, PatchedItem, TestCase, retry +from humanfriendly.text import format, random_string + +# The module we're testing. +import coloredlogs +import coloredlogs.cli +from coloredlogs import ( + CHROOT_FILES, + ColoredFormatter, + NameNormalizer, + decrease_verbosity, + find_defined_levels, + find_handler, + find_hostname, + find_program_name, + find_username, + get_level, + increase_verbosity, + install, + is_verbose, + level_to_number, + match_stream_handler, + parse_encoded_styles, + set_level, + walk_propagation_tree, +) +from coloredlogs.demo import demonstrate_colored_logging +from coloredlogs.syslog import SystemLogging, is_syslog_supported, match_syslog_handler +from coloredlogs.converter import ( + ColoredCronMailer, + EIGHT_COLOR_PALETTE, + capture, + convert, +) + +# External test dependencies. +from capturer import CaptureOutput +from verboselogs import VerboseLogger + +# Compiled regular expression that matches a single line of output produced by +# the default log format (does not include matching of ANSI escape sequences). +PLAIN_TEXT_PATTERN = re.compile(r''' + (?P \d{4}-\d{2}-\d{2} ) + \s (?P