hxrron commited on
Commit
bcf119b
·
verified ·
1 Parent(s): 5fd9823

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +4 -0
  2. python_embeded/Lib/site-packages/Deprecated-1.2.18.dist-info/RECORD +12 -0
  3. python_embeded/Lib/site-packages/Deprecated-1.2.18.dist-info/WHEEL +6 -0
  4. python_embeded/Lib/site-packages/click-8.2.1.dist-info/INSTALLER +1 -0
  5. python_embeded/Lib/site-packages/click-8.2.1.dist-info/METADATA +82 -0
  6. python_embeded/Lib/site-packages/click-8.2.1.dist-info/RECORD +38 -0
  7. python_embeded/Lib/site-packages/click/__init__.py +123 -0
  8. python_embeded/Lib/site-packages/click/_compat.py +622 -0
  9. python_embeded/Lib/site-packages/color_matcher-0.6.0.dist-info/INSTALLER +1 -0
  10. python_embeded/Lib/site-packages/color_matcher-0.6.0.dist-info/LICENSE +674 -0
  11. python_embeded/Lib/site-packages/color_matcher-0.6.0.dist-info/METADATA +24 -0
  12. python_embeded/Lib/site-packages/color_matcher-0.6.0.dist-info/WHEEL +5 -0
  13. python_embeded/Lib/site-packages/color_matcher-0.6.0.dist-info/entry_points.txt +2 -0
  14. python_embeded/Lib/site-packages/color_matcher-0.6.0.dist-info/top_level.txt +2 -0
  15. python_embeded/Lib/site-packages/color_matcher/__init__.py +25 -0
  16. python_embeded/Lib/site-packages/color_matcher/baseclass.py +105 -0
  17. python_embeded/Lib/site-packages/color_matcher/hist_matcher.py +77 -0
  18. python_embeded/Lib/site-packages/color_matcher/io_handler.py +128 -0
  19. python_embeded/Lib/site-packages/color_matcher/mvgd_matcher.py +207 -0
  20. python_embeded/Lib/site-packages/color_matcher/normalizer.py +78 -0
  21. python_embeded/Lib/site-packages/color_matcher/reinhard_matcher.py +84 -0
  22. python_embeded/Lib/site-packages/color_matcher/top_level.py +98 -0
  23. python_embeded/Lib/site-packages/colorama-0.4.6.dist-info/METADATA +441 -0
  24. python_embeded/Lib/site-packages/colorama-0.4.6.dist-info/RECORD +33 -0
  25. python_embeded/Lib/site-packages/colorama-0.4.6.dist-info/REQUESTED +0 -0
  26. python_embeded/Lib/site-packages/colorama-0.4.6.dist-info/WHEEL +5 -0
  27. python_embeded/Lib/site-packages/colorama/ansi.py +102 -0
  28. python_embeded/Lib/site-packages/colorama/ansitowin32.py +277 -0
  29. python_embeded/Lib/site-packages/colorama/initialise.py +121 -0
  30. python_embeded/Lib/site-packages/colorama/winterm.py +195 -0
  31. python_embeded/Lib/site-packages/coloredlogs-15.0.1.dist-info/INSTALLER +1 -0
  32. python_embeded/Lib/site-packages/coloredlogs-15.0.1.dist-info/LICENSE.txt +20 -0
  33. python_embeded/Lib/site-packages/coloredlogs-15.0.1.dist-info/METADATA +291 -0
  34. python_embeded/Lib/site-packages/coloredlogs-15.0.1.dist-info/RECORD +23 -0
  35. python_embeded/Lib/site-packages/coloredlogs-15.0.1.dist-info/WHEEL +6 -0
  36. python_embeded/Lib/site-packages/coloredlogs-15.0.1.dist-info/entry_points.txt +3 -0
  37. python_embeded/Lib/site-packages/coloredlogs-15.0.1.dist-info/top_level.txt +1 -0
  38. python_embeded/Lib/site-packages/coloredlogs/__init__.py +1524 -0
  39. python_embeded/Lib/site-packages/coloredlogs/cli.py +106 -0
  40. python_embeded/Lib/site-packages/coloredlogs/demo.py +49 -0
  41. python_embeded/Lib/site-packages/coloredlogs/syslog.py +292 -0
  42. python_embeded/Lib/site-packages/coloredlogs/tests.py +673 -0
  43. python_embeded/Lib/site-packages/colour/py.typed +0 -0
  44. python_embeded/Lib/site-packages/colour_science-0.4.6.dist-info/METADATA +2062 -0
  45. python_embeded/Lib/site-packages/colour_science-0.4.6.dist-info/REQUESTED +0 -0
  46. python_embeded/Lib/site-packages/diffusers-0.34.0.dist-info/INSTALLER +1 -0
  47. python_embeded/Lib/site-packages/diffusers-0.34.0.dist-info/LICENSE +201 -0
  48. python_embeded/Lib/site-packages/diffusers-0.34.0.dist-info/METADATA +372 -0
  49. python_embeded/Lib/site-packages/diffusers-0.34.0.dist-info/RECORD +0 -0
  50. python_embeded/Lib/site-packages/diffusers-0.34.0.dist-info/REQUESTED +0 -0
.gitattributes CHANGED
@@ -33,3 +33,7 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ python_embeded/python.exe filter=lfs diff=lfs merge=lfs -text
37
+ python_embeded/vcruntime140.dll filter=lfs diff=lfs merge=lfs -text
38
+ python_embeded/libssl-3.dll filter=lfs diff=lfs merge=lfs -text
39
+ python_embeded/sqlite3.dll filter=lfs diff=lfs merge=lfs -text
python_embeded/Lib/site-packages/Deprecated-1.2.18.dist-info/RECORD ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Deprecated-1.2.18.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ Deprecated-1.2.18.dist-info/LICENSE.rst,sha256=HoPt0VvkGbXVveNy4yXlJ_9PmRX1SOfHUxS0H2aZ6Dw,1081
3
+ Deprecated-1.2.18.dist-info/METADATA,sha256=4CrUw5Bl8_NsBuZYe0Nw-mIwQnVpT1CnmBYU9BqOuq8,5725
4
+ Deprecated-1.2.18.dist-info/RECORD,,
5
+ Deprecated-1.2.18.dist-info/WHEEL,sha256=9Hm2OB-j1QcCUq9Jguht7ayGIIZBRTdOXD1qg9cCgPM,109
6
+ Deprecated-1.2.18.dist-info/top_level.txt,sha256=nHbOYawKPQQE5lQl-toUB1JBRJjUyn_m_Mb8RVJ0RjA,11
7
+ deprecated/__init__.py,sha256=yZNbmDKXF4PLtp_Ikdb_9ObJLkHuFSUHvqidFTKKGFM,351
8
+ deprecated/__pycache__/__init__.cpython-312.pyc,,
9
+ deprecated/__pycache__/classic.cpython-312.pyc,,
10
+ deprecated/__pycache__/sphinx.cpython-312.pyc,,
11
+ deprecated/classic.py,sha256=7WXOt4Vf1NhrUznm8ypjS50CMyAdZwrGT58Lhb8fW14,10609
12
+ deprecated/sphinx.py,sha256=cOKnXbDyFAwDr5O7HBEpgQrx-J-qfp57sfdK_LabDxs,11109
python_embeded/Lib/site-packages/Deprecated-1.2.18.dist-info/WHEEL ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (75.8.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py2-none-any
5
+ Tag: py3-none-any
6
+
python_embeded/Lib/site-packages/click-8.2.1.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
python_embeded/Lib/site-packages/click-8.2.1.dist-info/METADATA ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: click
3
+ Version: 8.2.1
4
+ Summary: Composable command line interface toolkit
5
+ Maintainer-email: Pallets <contact@palletsprojects.com>
6
+ Requires-Python: >=3.10
7
+ Description-Content-Type: text/markdown
8
+ License-Expression: BSD-3-Clause
9
+ Classifier: Development Status :: 5 - Production/Stable
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Programming Language :: Python
13
+ Classifier: Typing :: Typed
14
+ License-File: LICENSE.txt
15
+ Requires-Dist: colorama; platform_system == 'Windows'
16
+ Project-URL: Changes, https://click.palletsprojects.com/page/changes/
17
+ Project-URL: Chat, https://discord.gg/pallets
18
+ Project-URL: Documentation, https://click.palletsprojects.com/
19
+ Project-URL: Donate, https://palletsprojects.com/donate
20
+ Project-URL: Source, https://github.com/pallets/click/
21
+
22
+ # $ click_
23
+
24
+ Click is a Python package for creating beautiful command line interfaces
25
+ in a composable way with as little code as necessary. It's the "Command
26
+ Line Interface Creation Kit". It's highly configurable but comes with
27
+ sensible defaults out of the box.
28
+
29
+ It aims to make the process of writing command line tools quick and fun
30
+ while also preventing any frustration caused by the inability to
31
+ implement an intended CLI API.
32
+
33
+ Click in three points:
34
+
35
+ - Arbitrary nesting of commands
36
+ - Automatic help page generation
37
+ - Supports lazy loading of subcommands at runtime
38
+
39
+
40
+ ## A Simple Example
41
+
42
+ ```python
43
+ import click
44
+
45
+ @click.command()
46
+ @click.option("--count", default=1, help="Number of greetings.")
47
+ @click.option("--name", prompt="Your name", help="The person to greet.")
48
+ def hello(count, name):
49
+ """Simple program that greets NAME for a total of COUNT times."""
50
+ for _ in range(count):
51
+ click.echo(f"Hello, {name}!")
52
+
53
+ if __name__ == '__main__':
54
+ hello()
55
+ ```
56
+
57
+ ```
58
+ $ python hello.py --count=3
59
+ Your name: Click
60
+ Hello, Click!
61
+ Hello, Click!
62
+ Hello, Click!
63
+ ```
64
+
65
+
66
+ ## Donate
67
+
68
+ The Pallets organization develops and supports Click and other popular
69
+ packages. In order to grow the community of contributors and users, and
70
+ allow the maintainers to devote more time to the projects, [please
71
+ donate today][].
72
+
73
+ [please donate today]: https://palletsprojects.com/donate
74
+
75
+ ## Contributing
76
+
77
+ See our [detailed contributing documentation][contrib] for many ways to
78
+ contribute, including reporting issues, requesting features, asking or answering
79
+ questions, and making PRs.
80
+
81
+ [contrib]: https://palletsprojects.com/contributing/
82
+
python_embeded/Lib/site-packages/click-8.2.1.dist-info/RECORD ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ click-8.2.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ click-8.2.1.dist-info/METADATA,sha256=dI1MbhHTLoKD2tNCCGnx9rK2gok23HDNylFeLKdLSik,2471
3
+ click-8.2.1.dist-info/RECORD,,
4
+ click-8.2.1.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82
5
+ click-8.2.1.dist-info/licenses/LICENSE.txt,sha256=morRBqOU6FO_4h9C9OctWSgZoigF2ZG18ydQKSkrZY0,1475
6
+ click/__init__.py,sha256=6YyS1aeyknZ0LYweWozNZy0A9nZ_11wmYIhv3cbQrYo,4473
7
+ click/__pycache__/__init__.cpython-312.pyc,,
8
+ click/__pycache__/_compat.cpython-312.pyc,,
9
+ click/__pycache__/_termui_impl.cpython-312.pyc,,
10
+ click/__pycache__/_textwrap.cpython-312.pyc,,
11
+ click/__pycache__/_winconsole.cpython-312.pyc,,
12
+ click/__pycache__/core.cpython-312.pyc,,
13
+ click/__pycache__/decorators.cpython-312.pyc,,
14
+ click/__pycache__/exceptions.cpython-312.pyc,,
15
+ click/__pycache__/formatting.cpython-312.pyc,,
16
+ click/__pycache__/globals.cpython-312.pyc,,
17
+ click/__pycache__/parser.cpython-312.pyc,,
18
+ click/__pycache__/shell_completion.cpython-312.pyc,,
19
+ click/__pycache__/termui.cpython-312.pyc,,
20
+ click/__pycache__/testing.cpython-312.pyc,,
21
+ click/__pycache__/types.cpython-312.pyc,,
22
+ click/__pycache__/utils.cpython-312.pyc,,
23
+ click/_compat.py,sha256=v3xBZkFbvA1BXPRkFfBJc6-pIwPI7345m-kQEnpVAs4,18693
24
+ click/_termui_impl.py,sha256=ASXhLi9IQIc0Js9KQSS-3-SLZcPet3VqysBf9WgbbpI,26712
25
+ click/_textwrap.py,sha256=BOae0RQ6vg3FkNgSJyOoGzG1meGMxJ_ukWVZKx_v-0o,1400
26
+ click/_winconsole.py,sha256=_vxUuUaxwBhoR0vUWCNuHY8VUefiMdCIyU2SXPqoF-A,8465
27
+ click/core.py,sha256=gUhpNS9cFBGdEXXdisGVG-eRvGf49RTyFagxulqwdFw,117343
28
+ click/decorators.py,sha256=5P7abhJtAQYp_KHgjUvhMv464ERwOzrv2enNknlwHyQ,18461
29
+ click/exceptions.py,sha256=1rdtXgHJ1b3OjGkN-UpXB9t_HCBihJvh_DtpmLmwn9s,9891
30
+ click/formatting.py,sha256=Bhqx4QXdKQ9W4WKknIwj5KPKFmtduGOuGq1yw_THLZ8,9726
31
+ click/globals.py,sha256=gM-Nh6A4M0HB_SgkaF5M4ncGGMDHc_flHXu9_oh4GEU,1923
32
+ click/parser.py,sha256=nU1Ah2p11q29ul1vNdU9swPo_PUuKrxU6YXToi71q1c,18979
33
+ click/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
34
+ click/shell_completion.py,sha256=CQSGdjgun4ORbOZrXP0CVhEtPx4knsufOkRsDiK64cM,19857
35
+ click/termui.py,sha256=vAYrKC2a7f_NfEIhAThEVYfa__ib5XQbTSCGtJlABRA,30847
36
+ click/testing.py,sha256=2eLdAaCJCGToP5Tw-XN8JjrDb3wbJIfARxg3d0crW5M,18702
37
+ click/types.py,sha256=KBTRxN28cR1VZ5mb9iJX98MQSw_p9SGzljqfEI8z5Tw,38389
38
+ click/utils.py,sha256=b1Mm-usEDBHtEwcPltPIn3zSK4nw2KTp5GC7_oSTlLo,20245
python_embeded/Lib/site-packages/click/__init__.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Click is a simple Python module inspired by the stdlib optparse to make
3
+ writing command line scripts fun. Unlike other modules, it's based
4
+ around a simple API that does not come with too much magic and is
5
+ composable.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from .core import Argument as Argument
11
+ from .core import Command as Command
12
+ from .core import CommandCollection as CommandCollection
13
+ from .core import Context as Context
14
+ from .core import Group as Group
15
+ from .core import Option as Option
16
+ from .core import Parameter as Parameter
17
+ from .decorators import argument as argument
18
+ from .decorators import command as command
19
+ from .decorators import confirmation_option as confirmation_option
20
+ from .decorators import group as group
21
+ from .decorators import help_option as help_option
22
+ from .decorators import make_pass_decorator as make_pass_decorator
23
+ from .decorators import option as option
24
+ from .decorators import pass_context as pass_context
25
+ from .decorators import pass_obj as pass_obj
26
+ from .decorators import password_option as password_option
27
+ from .decorators import version_option as version_option
28
+ from .exceptions import Abort as Abort
29
+ from .exceptions import BadArgumentUsage as BadArgumentUsage
30
+ from .exceptions import BadOptionUsage as BadOptionUsage
31
+ from .exceptions import BadParameter as BadParameter
32
+ from .exceptions import ClickException as ClickException
33
+ from .exceptions import FileError as FileError
34
+ from .exceptions import MissingParameter as MissingParameter
35
+ from .exceptions import NoSuchOption as NoSuchOption
36
+ from .exceptions import UsageError as UsageError
37
+ from .formatting import HelpFormatter as HelpFormatter
38
+ from .formatting import wrap_text as wrap_text
39
+ from .globals import get_current_context as get_current_context
40
+ from .termui import clear as clear
41
+ from .termui import confirm as confirm
42
+ from .termui import echo_via_pager as echo_via_pager
43
+ from .termui import edit as edit
44
+ from .termui import getchar as getchar
45
+ from .termui import launch as launch
46
+ from .termui import pause as pause
47
+ from .termui import progressbar as progressbar
48
+ from .termui import prompt as prompt
49
+ from .termui import secho as secho
50
+ from .termui import style as style
51
+ from .termui import unstyle as unstyle
52
+ from .types import BOOL as BOOL
53
+ from .types import Choice as Choice
54
+ from .types import DateTime as DateTime
55
+ from .types import File as File
56
+ from .types import FLOAT as FLOAT
57
+ from .types import FloatRange as FloatRange
58
+ from .types import INT as INT
59
+ from .types import IntRange as IntRange
60
+ from .types import ParamType as ParamType
61
+ from .types import Path as Path
62
+ from .types import STRING as STRING
63
+ from .types import Tuple as Tuple
64
+ from .types import UNPROCESSED as UNPROCESSED
65
+ from .types import UUID as UUID
66
+ from .utils import echo as echo
67
+ from .utils import format_filename as format_filename
68
+ from .utils import get_app_dir as get_app_dir
69
+ from .utils import get_binary_stream as get_binary_stream
70
+ from .utils import get_text_stream as get_text_stream
71
+ from .utils import open_file as open_file
72
+
73
+
74
+ def __getattr__(name: str) -> object:
75
+ import warnings
76
+
77
+ if name == "BaseCommand":
78
+ from .core import _BaseCommand
79
+
80
+ warnings.warn(
81
+ "'BaseCommand' is deprecated and will be removed in Click 9.0. Use"
82
+ " 'Command' instead.",
83
+ DeprecationWarning,
84
+ stacklevel=2,
85
+ )
86
+ return _BaseCommand
87
+
88
+ if name == "MultiCommand":
89
+ from .core import _MultiCommand
90
+
91
+ warnings.warn(
92
+ "'MultiCommand' is deprecated and will be removed in Click 9.0. Use"
93
+ " 'Group' instead.",
94
+ DeprecationWarning,
95
+ stacklevel=2,
96
+ )
97
+ return _MultiCommand
98
+
99
+ if name == "OptionParser":
100
+ from .parser import _OptionParser
101
+
102
+ warnings.warn(
103
+ "'OptionParser' is deprecated and will be removed in Click 9.0. The"
104
+ " old parser is available in 'optparse'.",
105
+ DeprecationWarning,
106
+ stacklevel=2,
107
+ )
108
+ return _OptionParser
109
+
110
+ if name == "__version__":
111
+ import importlib.metadata
112
+ import warnings
113
+
114
+ warnings.warn(
115
+ "The '__version__' attribute is deprecated and will be removed in"
116
+ " Click 9.1. Use feature detection or"
117
+ " 'importlib.metadata.version(\"click\")' instead.",
118
+ DeprecationWarning,
119
+ stacklevel=2,
120
+ )
121
+ return importlib.metadata.version("click")
122
+
123
+ raise AttributeError(name)
python_embeded/Lib/site-packages/click/_compat.py ADDED
@@ -0,0 +1,622 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import codecs
4
+ import collections.abc as cabc
5
+ import io
6
+ import os
7
+ import re
8
+ import sys
9
+ import typing as t
10
+ from types import TracebackType
11
+ from weakref import WeakKeyDictionary
12
+
13
+ CYGWIN = sys.platform.startswith("cygwin")
14
+ WIN = sys.platform.startswith("win")
15
+ auto_wrap_for_ansi: t.Callable[[t.TextIO], t.TextIO] | None = None
16
+ _ansi_re = re.compile(r"\033\[[;?0-9]*[a-zA-Z]")
17
+
18
+
19
+ def _make_text_stream(
20
+ stream: t.BinaryIO,
21
+ encoding: str | None,
22
+ errors: str | None,
23
+ force_readable: bool = False,
24
+ force_writable: bool = False,
25
+ ) -> t.TextIO:
26
+ if encoding is None:
27
+ encoding = get_best_encoding(stream)
28
+ if errors is None:
29
+ errors = "replace"
30
+ return _NonClosingTextIOWrapper(
31
+ stream,
32
+ encoding,
33
+ errors,
34
+ line_buffering=True,
35
+ force_readable=force_readable,
36
+ force_writable=force_writable,
37
+ )
38
+
39
+
40
+ def is_ascii_encoding(encoding: str) -> bool:
41
+ """Checks if a given encoding is ascii."""
42
+ try:
43
+ return codecs.lookup(encoding).name == "ascii"
44
+ except LookupError:
45
+ return False
46
+
47
+
48
+ def get_best_encoding(stream: t.IO[t.Any]) -> str:
49
+ """Returns the default stream encoding if not found."""
50
+ rv = getattr(stream, "encoding", None) or sys.getdefaultencoding()
51
+ if is_ascii_encoding(rv):
52
+ return "utf-8"
53
+ return rv
54
+
55
+
56
+ class _NonClosingTextIOWrapper(io.TextIOWrapper):
57
+ def __init__(
58
+ self,
59
+ stream: t.BinaryIO,
60
+ encoding: str | None,
61
+ errors: str | None,
62
+ force_readable: bool = False,
63
+ force_writable: bool = False,
64
+ **extra: t.Any,
65
+ ) -> None:
66
+ self._stream = stream = t.cast(
67
+ t.BinaryIO, _FixupStream(stream, force_readable, force_writable)
68
+ )
69
+ super().__init__(stream, encoding, errors, **extra)
70
+
71
+ def __del__(self) -> None:
72
+ try:
73
+ self.detach()
74
+ except Exception:
75
+ pass
76
+
77
+ def isatty(self) -> bool:
78
+ # https://bitbucket.org/pypy/pypy/issue/1803
79
+ return self._stream.isatty()
80
+
81
+
82
+ class _FixupStream:
83
+ """The new io interface needs more from streams than streams
84
+ traditionally implement. As such, this fix-up code is necessary in
85
+ some circumstances.
86
+
87
+ The forcing of readable and writable flags are there because some tools
88
+ put badly patched objects on sys (one such offender are certain version
89
+ of jupyter notebook).
90
+ """
91
+
92
+ def __init__(
93
+ self,
94
+ stream: t.BinaryIO,
95
+ force_readable: bool = False,
96
+ force_writable: bool = False,
97
+ ):
98
+ self._stream = stream
99
+ self._force_readable = force_readable
100
+ self._force_writable = force_writable
101
+
102
+ def __getattr__(self, name: str) -> t.Any:
103
+ return getattr(self._stream, name)
104
+
105
+ def read1(self, size: int) -> bytes:
106
+ f = getattr(self._stream, "read1", None)
107
+
108
+ if f is not None:
109
+ return t.cast(bytes, f(size))
110
+
111
+ return self._stream.read(size)
112
+
113
+ def readable(self) -> bool:
114
+ if self._force_readable:
115
+ return True
116
+ x = getattr(self._stream, "readable", None)
117
+ if x is not None:
118
+ return t.cast(bool, x())
119
+ try:
120
+ self._stream.read(0)
121
+ except Exception:
122
+ return False
123
+ return True
124
+
125
+ def writable(self) -> bool:
126
+ if self._force_writable:
127
+ return True
128
+ x = getattr(self._stream, "writable", None)
129
+ if x is not None:
130
+ return t.cast(bool, x())
131
+ try:
132
+ self._stream.write(b"")
133
+ except Exception:
134
+ try:
135
+ self._stream.write(b"")
136
+ except Exception:
137
+ return False
138
+ return True
139
+
140
+ def seekable(self) -> bool:
141
+ x = getattr(self._stream, "seekable", None)
142
+ if x is not None:
143
+ return t.cast(bool, x())
144
+ try:
145
+ self._stream.seek(self._stream.tell())
146
+ except Exception:
147
+ return False
148
+ return True
149
+
150
+
151
+ def _is_binary_reader(stream: t.IO[t.Any], default: bool = False) -> bool:
152
+ try:
153
+ return isinstance(stream.read(0), bytes)
154
+ except Exception:
155
+ return default
156
+ # This happens in some cases where the stream was already
157
+ # closed. In this case, we assume the default.
158
+
159
+
160
+ def _is_binary_writer(stream: t.IO[t.Any], default: bool = False) -> bool:
161
+ try:
162
+ stream.write(b"")
163
+ except Exception:
164
+ try:
165
+ stream.write("")
166
+ return False
167
+ except Exception:
168
+ pass
169
+ return default
170
+ return True
171
+
172
+
173
+ def _find_binary_reader(stream: t.IO[t.Any]) -> t.BinaryIO | None:
174
+ # We need to figure out if the given stream is already binary.
175
+ # This can happen because the official docs recommend detaching
176
+ # the streams to get binary streams. Some code might do this, so
177
+ # we need to deal with this case explicitly.
178
+ if _is_binary_reader(stream, False):
179
+ return t.cast(t.BinaryIO, stream)
180
+
181
+ buf = getattr(stream, "buffer", None)
182
+
183
+ # Same situation here; this time we assume that the buffer is
184
+ # actually binary in case it's closed.
185
+ if buf is not None and _is_binary_reader(buf, True):
186
+ return t.cast(t.BinaryIO, buf)
187
+
188
+ return None
189
+
190
+
191
+ def _find_binary_writer(stream: t.IO[t.Any]) -> t.BinaryIO | None:
192
+ # We need to figure out if the given stream is already binary.
193
+ # This can happen because the official docs recommend detaching
194
+ # the streams to get binary streams. Some code might do this, so
195
+ # we need to deal with this case explicitly.
196
+ if _is_binary_writer(stream, False):
197
+ return t.cast(t.BinaryIO, stream)
198
+
199
+ buf = getattr(stream, "buffer", None)
200
+
201
+ # Same situation here; this time we assume that the buffer is
202
+ # actually binary in case it's closed.
203
+ if buf is not None and _is_binary_writer(buf, True):
204
+ return t.cast(t.BinaryIO, buf)
205
+
206
+ return None
207
+
208
+
209
+ def _stream_is_misconfigured(stream: t.TextIO) -> bool:
210
+ """A stream is misconfigured if its encoding is ASCII."""
211
+ # If the stream does not have an encoding set, we assume it's set
212
+ # to ASCII. This appears to happen in certain unittest
213
+ # environments. It's not quite clear what the correct behavior is
214
+ # but this at least will force Click to recover somehow.
215
+ return is_ascii_encoding(getattr(stream, "encoding", None) or "ascii")
216
+
217
+
218
+ def _is_compat_stream_attr(stream: t.TextIO, attr: str, value: str | None) -> bool:
219
+ """A stream attribute is compatible if it is equal to the
220
+ desired value or the desired value is unset and the attribute
221
+ has a value.
222
+ """
223
+ stream_value = getattr(stream, attr, None)
224
+ return stream_value == value or (value is None and stream_value is not None)
225
+
226
+
227
+ def _is_compatible_text_stream(
228
+ stream: t.TextIO, encoding: str | None, errors: str | None
229
+ ) -> bool:
230
+ """Check if a stream's encoding and errors attributes are
231
+ compatible with the desired values.
232
+ """
233
+ return _is_compat_stream_attr(
234
+ stream, "encoding", encoding
235
+ ) and _is_compat_stream_attr(stream, "errors", errors)
236
+
237
+
238
+ def _force_correct_text_stream(
239
+ text_stream: t.IO[t.Any],
240
+ encoding: str | None,
241
+ errors: str | None,
242
+ is_binary: t.Callable[[t.IO[t.Any], bool], bool],
243
+ find_binary: t.Callable[[t.IO[t.Any]], t.BinaryIO | None],
244
+ force_readable: bool = False,
245
+ force_writable: bool = False,
246
+ ) -> t.TextIO:
247
+ if is_binary(text_stream, False):
248
+ binary_reader = t.cast(t.BinaryIO, text_stream)
249
+ else:
250
+ text_stream = t.cast(t.TextIO, text_stream)
251
+ # If the stream looks compatible, and won't default to a
252
+ # misconfigured ascii encoding, return it as-is.
253
+ if _is_compatible_text_stream(text_stream, encoding, errors) and not (
254
+ encoding is None and _stream_is_misconfigured(text_stream)
255
+ ):
256
+ return text_stream
257
+
258
+ # Otherwise, get the underlying binary reader.
259
+ possible_binary_reader = find_binary(text_stream)
260
+
261
+ # If that's not possible, silently use the original reader
262
+ # and get mojibake instead of exceptions.
263
+ if possible_binary_reader is None:
264
+ return text_stream
265
+
266
+ binary_reader = possible_binary_reader
267
+
268
+ # Default errors to replace instead of strict in order to get
269
+ # something that works.
270
+ if errors is None:
271
+ errors = "replace"
272
+
273
+ # Wrap the binary stream in a text stream with the correct
274
+ # encoding parameters.
275
+ return _make_text_stream(
276
+ binary_reader,
277
+ encoding,
278
+ errors,
279
+ force_readable=force_readable,
280
+ force_writable=force_writable,
281
+ )
282
+
283
+
284
+ def _force_correct_text_reader(
285
+ text_reader: t.IO[t.Any],
286
+ encoding: str | None,
287
+ errors: str | None,
288
+ force_readable: bool = False,
289
+ ) -> t.TextIO:
290
+ return _force_correct_text_stream(
291
+ text_reader,
292
+ encoding,
293
+ errors,
294
+ _is_binary_reader,
295
+ _find_binary_reader,
296
+ force_readable=force_readable,
297
+ )
298
+
299
+
300
+ def _force_correct_text_writer(
301
+ text_writer: t.IO[t.Any],
302
+ encoding: str | None,
303
+ errors: str | None,
304
+ force_writable: bool = False,
305
+ ) -> t.TextIO:
306
+ return _force_correct_text_stream(
307
+ text_writer,
308
+ encoding,
309
+ errors,
310
+ _is_binary_writer,
311
+ _find_binary_writer,
312
+ force_writable=force_writable,
313
+ )
314
+
315
+
316
+ def get_binary_stdin() -> t.BinaryIO:
317
+ reader = _find_binary_reader(sys.stdin)
318
+ if reader is None:
319
+ raise RuntimeError("Was not able to determine binary stream for sys.stdin.")
320
+ return reader
321
+
322
+
323
+ def get_binary_stdout() -> t.BinaryIO:
324
+ writer = _find_binary_writer(sys.stdout)
325
+ if writer is None:
326
+ raise RuntimeError("Was not able to determine binary stream for sys.stdout.")
327
+ return writer
328
+
329
+
330
+ def get_binary_stderr() -> t.BinaryIO:
331
+ writer = _find_binary_writer(sys.stderr)
332
+ if writer is None:
333
+ raise RuntimeError("Was not able to determine binary stream for sys.stderr.")
334
+ return writer
335
+
336
+
337
+ def get_text_stdin(encoding: str | None = None, errors: str | None = None) -> t.TextIO:
338
+ rv = _get_windows_console_stream(sys.stdin, encoding, errors)
339
+ if rv is not None:
340
+ return rv
341
+ return _force_correct_text_reader(sys.stdin, encoding, errors, force_readable=True)
342
+
343
+
344
+ def get_text_stdout(encoding: str | None = None, errors: str | None = None) -> t.TextIO:
345
+ rv = _get_windows_console_stream(sys.stdout, encoding, errors)
346
+ if rv is not None:
347
+ return rv
348
+ return _force_correct_text_writer(sys.stdout, encoding, errors, force_writable=True)
349
+
350
+
351
+ def get_text_stderr(encoding: str | None = None, errors: str | None = None) -> t.TextIO:
352
+ rv = _get_windows_console_stream(sys.stderr, encoding, errors)
353
+ if rv is not None:
354
+ return rv
355
+ return _force_correct_text_writer(sys.stderr, encoding, errors, force_writable=True)
356
+
357
+
358
+ def _wrap_io_open(
359
+ file: str | os.PathLike[str] | int,
360
+ mode: str,
361
+ encoding: str | None,
362
+ errors: str | None,
363
+ ) -> t.IO[t.Any]:
364
+ """Handles not passing ``encoding`` and ``errors`` in binary mode."""
365
+ if "b" in mode:
366
+ return open(file, mode)
367
+
368
+ return open(file, mode, encoding=encoding, errors=errors)
369
+
370
+
371
+ def open_stream(
372
+ filename: str | os.PathLike[str],
373
+ mode: str = "r",
374
+ encoding: str | None = None,
375
+ errors: str | None = "strict",
376
+ atomic: bool = False,
377
+ ) -> tuple[t.IO[t.Any], bool]:
378
+ binary = "b" in mode
379
+ filename = os.fspath(filename)
380
+
381
+ # Standard streams first. These are simple because they ignore the
382
+ # atomic flag. Use fsdecode to handle Path("-").
383
+ if os.fsdecode(filename) == "-":
384
+ if any(m in mode for m in ["w", "a", "x"]):
385
+ if binary:
386
+ return get_binary_stdout(), False
387
+ return get_text_stdout(encoding=encoding, errors=errors), False
388
+ if binary:
389
+ return get_binary_stdin(), False
390
+ return get_text_stdin(encoding=encoding, errors=errors), False
391
+
392
+ # Non-atomic writes directly go out through the regular open functions.
393
+ if not atomic:
394
+ return _wrap_io_open(filename, mode, encoding, errors), True
395
+
396
+ # Some usability stuff for atomic writes
397
+ if "a" in mode:
398
+ raise ValueError(
399
+ "Appending to an existing file is not supported, because that"
400
+ " would involve an expensive `copy`-operation to a temporary"
401
+ " file. Open the file in normal `w`-mode and copy explicitly"
402
+ " if that's what you're after."
403
+ )
404
+ if "x" in mode:
405
+ raise ValueError("Use the `overwrite`-parameter instead.")
406
+ if "w" not in mode:
407
+ raise ValueError("Atomic writes only make sense with `w`-mode.")
408
+
409
+ # Atomic writes are more complicated. They work by opening a file
410
+ # as a proxy in the same folder and then using the fdopen
411
+ # functionality to wrap it in a Python file. Then we wrap it in an
412
+ # atomic file that moves the file over on close.
413
+ import errno
414
+ import random
415
+
416
+ try:
417
+ perm: int | None = os.stat(filename).st_mode
418
+ except OSError:
419
+ perm = None
420
+
421
+ flags = os.O_RDWR | os.O_CREAT | os.O_EXCL
422
+
423
+ if binary:
424
+ flags |= getattr(os, "O_BINARY", 0)
425
+
426
+ while True:
427
+ tmp_filename = os.path.join(
428
+ os.path.dirname(filename),
429
+ f".__atomic-write{random.randrange(1 << 32):08x}",
430
+ )
431
+ try:
432
+ fd = os.open(tmp_filename, flags, 0o666 if perm is None else perm)
433
+ break
434
+ except OSError as e:
435
+ if e.errno == errno.EEXIST or (
436
+ os.name == "nt"
437
+ and e.errno == errno.EACCES
438
+ and os.path.isdir(e.filename)
439
+ and os.access(e.filename, os.W_OK)
440
+ ):
441
+ continue
442
+ raise
443
+
444
+ if perm is not None:
445
+ os.chmod(tmp_filename, perm) # in case perm includes bits in umask
446
+
447
+ f = _wrap_io_open(fd, mode, encoding, errors)
448
+ af = _AtomicFile(f, tmp_filename, os.path.realpath(filename))
449
+ return t.cast(t.IO[t.Any], af), True
450
+
451
+
452
+ class _AtomicFile:
453
+ def __init__(self, f: t.IO[t.Any], tmp_filename: str, real_filename: str) -> None:
454
+ self._f = f
455
+ self._tmp_filename = tmp_filename
456
+ self._real_filename = real_filename
457
+ self.closed = False
458
+
459
+ @property
460
+ def name(self) -> str:
461
+ return self._real_filename
462
+
463
+ def close(self, delete: bool = False) -> None:
464
+ if self.closed:
465
+ return
466
+ self._f.close()
467
+ os.replace(self._tmp_filename, self._real_filename)
468
+ self.closed = True
469
+
470
+ def __getattr__(self, name: str) -> t.Any:
471
+ return getattr(self._f, name)
472
+
473
+ def __enter__(self) -> _AtomicFile:
474
+ return self
475
+
476
+ def __exit__(
477
+ self,
478
+ exc_type: type[BaseException] | None,
479
+ exc_value: BaseException | None,
480
+ tb: TracebackType | None,
481
+ ) -> None:
482
+ self.close(delete=exc_type is not None)
483
+
484
+ def __repr__(self) -> str:
485
+ return repr(self._f)
486
+
487
+
488
+ def strip_ansi(value: str) -> str:
489
+ return _ansi_re.sub("", value)
490
+
491
+
492
+ def _is_jupyter_kernel_output(stream: t.IO[t.Any]) -> bool:
493
+ while isinstance(stream, (_FixupStream, _NonClosingTextIOWrapper)):
494
+ stream = stream._stream
495
+
496
+ return stream.__class__.__module__.startswith("ipykernel.")
497
+
498
+
499
+ def should_strip_ansi(
500
+ stream: t.IO[t.Any] | None = None, color: bool | None = None
501
+ ) -> bool:
502
+ if color is None:
503
+ if stream is None:
504
+ stream = sys.stdin
505
+ return not isatty(stream) and not _is_jupyter_kernel_output(stream)
506
+ return not color
507
+
508
+
509
+ # On Windows, wrap the output streams with colorama to support ANSI
510
+ # color codes.
511
+ # NOTE: double check is needed so mypy does not analyze this on Linux
512
+ if sys.platform.startswith("win") and WIN:
513
+ from ._winconsole import _get_windows_console_stream
514
+
515
+ def _get_argv_encoding() -> str:
516
+ import locale
517
+
518
+ return locale.getpreferredencoding()
519
+
520
+ _ansi_stream_wrappers: cabc.MutableMapping[t.TextIO, t.TextIO] = WeakKeyDictionary()
521
+
522
+ def auto_wrap_for_ansi(stream: t.TextIO, color: bool | None = None) -> t.TextIO:
523
+ """Support ANSI color and style codes on Windows by wrapping a
524
+ stream with colorama.
525
+ """
526
+ try:
527
+ cached = _ansi_stream_wrappers.get(stream)
528
+ except Exception:
529
+ cached = None
530
+
531
+ if cached is not None:
532
+ return cached
533
+
534
+ import colorama
535
+
536
+ strip = should_strip_ansi(stream, color)
537
+ ansi_wrapper = colorama.AnsiToWin32(stream, strip=strip)
538
+ rv = t.cast(t.TextIO, ansi_wrapper.stream)
539
+ _write = rv.write
540
+
541
+ def _safe_write(s: str) -> int:
542
+ try:
543
+ return _write(s)
544
+ except BaseException:
545
+ ansi_wrapper.reset_all()
546
+ raise
547
+
548
+ rv.write = _safe_write # type: ignore[method-assign]
549
+
550
+ try:
551
+ _ansi_stream_wrappers[stream] = rv
552
+ except Exception:
553
+ pass
554
+
555
+ return rv
556
+
557
+ else:
558
+
559
+ def _get_argv_encoding() -> str:
560
+ return getattr(sys.stdin, "encoding", None) or sys.getfilesystemencoding()
561
+
562
+ def _get_windows_console_stream(
563
+ f: t.TextIO, encoding: str | None, errors: str | None
564
+ ) -> t.TextIO | None:
565
+ return None
566
+
567
+
568
+ def term_len(x: str) -> int:
569
+ return len(strip_ansi(x))
570
+
571
+
572
+ def isatty(stream: t.IO[t.Any]) -> bool:
573
+ try:
574
+ return stream.isatty()
575
+ except Exception:
576
+ return False
577
+
578
+
579
+ def _make_cached_stream_func(
580
+ src_func: t.Callable[[], t.TextIO | None],
581
+ wrapper_func: t.Callable[[], t.TextIO],
582
+ ) -> t.Callable[[], t.TextIO | None]:
583
+ cache: cabc.MutableMapping[t.TextIO, t.TextIO] = WeakKeyDictionary()
584
+
585
+ def func() -> t.TextIO | None:
586
+ stream = src_func()
587
+
588
+ if stream is None:
589
+ return None
590
+
591
+ try:
592
+ rv = cache.get(stream)
593
+ except Exception:
594
+ rv = None
595
+ if rv is not None:
596
+ return rv
597
+ rv = wrapper_func()
598
+ try:
599
+ cache[stream] = rv
600
+ except Exception:
601
+ pass
602
+ return rv
603
+
604
+ return func
605
+
606
+
607
+ _default_text_stdin = _make_cached_stream_func(lambda: sys.stdin, get_text_stdin)
608
+ _default_text_stdout = _make_cached_stream_func(lambda: sys.stdout, get_text_stdout)
609
+ _default_text_stderr = _make_cached_stream_func(lambda: sys.stderr, get_text_stderr)
610
+
611
+
612
+ binary_streams: cabc.Mapping[str, t.Callable[[], t.BinaryIO]] = {
613
+ "stdin": get_binary_stdin,
614
+ "stdout": get_binary_stdout,
615
+ "stderr": get_binary_stderr,
616
+ }
617
+
618
+ text_streams: cabc.Mapping[str, t.Callable[[str | None, str | None], t.TextIO]] = {
619
+ "stdin": get_text_stdin,
620
+ "stdout": get_text_stdout,
621
+ "stderr": get_text_stderr,
622
+ }
python_embeded/Lib/site-packages/color_matcher-0.6.0.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
python_embeded/Lib/site-packages/color_matcher-0.6.0.dist-info/LICENSE ADDED
@@ -0,0 +1,674 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+ Preamble
9
+
10
+ The GNU General Public License is a free, copyleft license for
11
+ software and other kinds of works.
12
+
13
+ The licenses for most software and other practical works are designed
14
+ to take away your freedom to share and change the works. By contrast,
15
+ the GNU General Public License is intended to guarantee your freedom to
16
+ share and change all versions of a program--to make sure it remains free
17
+ software for all its users. We, the Free Software Foundation, use the
18
+ GNU General Public License for most of our software; it applies also to
19
+ any other work released this way by its authors. You can apply it to
20
+ your programs, too.
21
+
22
+ When we speak of free software, we are referring to freedom, not
23
+ price. Our General Public Licenses are designed to make sure that you
24
+ have the freedom to distribute copies of free software (and charge for
25
+ them if you wish), that you receive source code or can get it if you
26
+ want it, that you can change the software or use pieces of it in new
27
+ free programs, and that you know you can do these things.
28
+
29
+ To protect your rights, we need to prevent others from denying you
30
+ these rights or asking you to surrender the rights. Therefore, you have
31
+ certain responsibilities if you distribute copies of the software, or if
32
+ you modify it: responsibilities to respect the freedom of others.
33
+
34
+ For example, if you distribute copies of such a program, whether
35
+ gratis or for a fee, you must pass on to the recipients the same
36
+ freedoms that you received. You must make sure that they, too, receive
37
+ or can get the source code. And you must show them these terms so they
38
+ know their rights.
39
+
40
+ Developers that use the GNU GPL protect your rights with two steps:
41
+ (1) assert copyright on the software, and (2) offer you this License
42
+ giving you legal permission to copy, distribute and/or modify it.
43
+
44
+ For the developers' and authors' protection, the GPL clearly explains
45
+ that there is no warranty for this free software. For both users' and
46
+ authors' sake, the GPL requires that modified versions be marked as
47
+ changed, so that their problems will not be attributed erroneously to
48
+ authors of previous versions.
49
+
50
+ Some devices are designed to deny users access to install or run
51
+ modified versions of the software inside them, although the manufacturer
52
+ can do so. This is fundamentally incompatible with the aim of
53
+ protecting users' freedom to change the software. The systematic
54
+ pattern of such abuse occurs in the area of products for individuals to
55
+ use, which is precisely where it is most unacceptable. Therefore, we
56
+ have designed this version of the GPL to prohibit the practice for those
57
+ products. If such problems arise substantially in other domains, we
58
+ stand ready to extend this provision to those domains in future versions
59
+ of the GPL, as needed to protect the freedom of users.
60
+
61
+ Finally, every program is threatened constantly by software patents.
62
+ States should not allow patents to restrict development and use of
63
+ software on general-purpose computers, but in those that do, we wish to
64
+ avoid the special danger that patents applied to a free program could
65
+ make it effectively proprietary. To prevent this, the GPL assures that
66
+ patents cannot be used to render the program non-free.
67
+
68
+ The precise terms and conditions for copying, distribution and
69
+ modification follow.
70
+
71
+ TERMS AND CONDITIONS
72
+
73
+ 0. Definitions.
74
+
75
+ "This License" refers to version 3 of the GNU General Public License.
76
+
77
+ "Copyright" also means copyright-like laws that apply to other kinds of
78
+ works, such as semiconductor masks.
79
+
80
+ "The Program" refers to any copyrightable work licensed under this
81
+ License. Each licensee is addressed as "you". "Licensees" and
82
+ "recipients" may be individuals or organizations.
83
+
84
+ To "modify" a work means to copy from or adapt all or part of the work
85
+ in a fashion requiring copyright permission, other than the making of an
86
+ exact copy. The resulting work is called a "modified version" of the
87
+ earlier work or a work "based on" the earlier work.
88
+
89
+ A "covered work" means either the unmodified Program or a work based
90
+ on the Program.
91
+
92
+ To "propagate" a work means to do anything with it that, without
93
+ permission, would make you directly or secondarily liable for
94
+ infringement under applicable copyright law, except executing it on a
95
+ computer or modifying a private copy. Propagation includes copying,
96
+ distribution (with or without modification), making available to the
97
+ public, and in some countries other activities as well.
98
+
99
+ To "convey" a work means any kind of propagation that enables other
100
+ parties to make or receive copies. Mere interaction with a user through
101
+ a computer network, with no transfer of a copy, is not conveying.
102
+
103
+ An interactive user interface displays "Appropriate Legal Notices"
104
+ to the extent that it includes a convenient and prominently visible
105
+ feature that (1) displays an appropriate copyright notice, and (2)
106
+ tells the user that there is no warranty for the work (except to the
107
+ extent that warranties are provided), that licensees may convey the
108
+ work under this License, and how to view a copy of this License. If
109
+ the interface presents a list of user commands or options, such as a
110
+ menu, a prominent item in the list meets this criterion.
111
+
112
+ 1. Source Code.
113
+
114
+ The "source code" for a work means the preferred form of the work
115
+ for making modifications to it. "Object code" means any non-source
116
+ form of a work.
117
+
118
+ A "Standard Interface" means an interface that either is an official
119
+ standard defined by a recognized standards body, or, in the case of
120
+ interfaces specified for a particular programming language, one that
121
+ is widely used among developers working in that language.
122
+
123
+ The "System Libraries" of an executable work include anything, other
124
+ than the work as a whole, that (a) is included in the normal form of
125
+ packaging a Major Component, but which is not part of that Major
126
+ Component, and (b) serves only to enable use of the work with that
127
+ Major Component, or to implement a Standard Interface for which an
128
+ implementation is available to the public in source code form. A
129
+ "Major Component", in this context, means a major essential component
130
+ (kernel, window system, and so on) of the specific operating system
131
+ (if any) on which the executable work runs, or a compiler used to
132
+ produce the work, or an object code interpreter used to run it.
133
+
134
+ The "Corresponding Source" for a work in object code form means all
135
+ the source code needed to generate, install, and (for an executable
136
+ work) run the object code and to modify the work, including scripts to
137
+ control those activities. However, it does not include the work's
138
+ System Libraries, or general-purpose tools or generally available free
139
+ programs which are used unmodified in performing those activities but
140
+ which are not part of the work. For example, Corresponding Source
141
+ includes interface definition files associated with source files for
142
+ the work, and the source code for shared libraries and dynamically
143
+ linked subprograms that the work is specifically designed to require,
144
+ such as by intimate data communication or control flow between those
145
+ subprograms and other parts of the work.
146
+
147
+ The Corresponding Source need not include anything that users
148
+ can regenerate automatically from other parts of the Corresponding
149
+ Source.
150
+
151
+ The Corresponding Source for a work in source code form is that
152
+ same work.
153
+
154
+ 2. Basic Permissions.
155
+
156
+ All rights granted under this License are granted for the term of
157
+ copyright on the Program, and are irrevocable provided the stated
158
+ conditions are met. This License explicitly affirms your unlimited
159
+ permission to run the unmodified Program. The output from running a
160
+ covered work is covered by this License only if the output, given its
161
+ content, constitutes a covered work. This License acknowledges your
162
+ rights of fair use or other equivalent, as provided by copyright law.
163
+
164
+ You may make, run and propagate covered works that you do not
165
+ convey, without conditions so long as your license otherwise remains
166
+ in force. You may convey covered works to others for the sole purpose
167
+ of having them make modifications exclusively for you, or provide you
168
+ with facilities for running those works, provided that you comply with
169
+ the terms of this License in conveying all material for which you do
170
+ not control copyright. Those thus making or running the covered works
171
+ for you must do so exclusively on your behalf, under your direction
172
+ and control, on terms that prohibit them from making any copies of
173
+ your copyrighted material outside their relationship with you.
174
+
175
+ Conveying under any other circumstances is permitted solely under
176
+ the conditions stated below. Sublicensing is not allowed; section 10
177
+ makes it unnecessary.
178
+
179
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180
+
181
+ No covered work shall be deemed part of an effective technological
182
+ measure under any applicable law fulfilling obligations under article
183
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184
+ similar laws prohibiting or restricting circumvention of such
185
+ measures.
186
+
187
+ When you convey a covered work, you waive any legal power to forbid
188
+ circumvention of technological measures to the extent such circumvention
189
+ is effected by exercising rights under this License with respect to
190
+ the covered work, and you disclaim any intention to limit operation or
191
+ modification of the work as a means of enforcing, against the work's
192
+ users, your or third parties' legal rights to forbid circumvention of
193
+ technological measures.
194
+
195
+ 4. Conveying Verbatim Copies.
196
+
197
+ You may convey verbatim copies of the Program's source code as you
198
+ receive it, in any medium, provided that you conspicuously and
199
+ appropriately publish on each copy an appropriate copyright notice;
200
+ keep intact all notices stating that this License and any
201
+ non-permissive terms added in accord with section 7 apply to the code;
202
+ keep intact all notices of the absence of any warranty; and give all
203
+ recipients a copy of this License along with the Program.
204
+
205
+ You may charge any price or no price for each copy that you convey,
206
+ and you may offer support or warranty protection for a fee.
207
+
208
+ 5. Conveying Modified Source Versions.
209
+
210
+ You may convey a work based on the Program, or the modifications to
211
+ produce it from the Program, in the form of source code under the
212
+ terms of section 4, provided that you also meet all of these conditions:
213
+
214
+ a) The work must carry prominent notices stating that you modified
215
+ it, and giving a relevant date.
216
+
217
+ b) The work must carry prominent notices stating that it is
218
+ released under this License and any conditions added under section
219
+ 7. This requirement modifies the requirement in section 4 to
220
+ "keep intact all notices".
221
+
222
+ c) You must license the entire work, as a whole, under this
223
+ License to anyone who comes into possession of a copy. This
224
+ License will therefore apply, along with any applicable section 7
225
+ additional terms, to the whole of the work, and all its parts,
226
+ regardless of how they are packaged. This License gives no
227
+ permission to license the work in any other way, but it does not
228
+ invalidate such permission if you have separately received it.
229
+
230
+ d) If the work has interactive user interfaces, each must display
231
+ Appropriate Legal Notices; however, if the Program has interactive
232
+ interfaces that do not display Appropriate Legal Notices, your
233
+ work need not make them do so.
234
+
235
+ A compilation of a covered work with other separate and independent
236
+ works, which are not by their nature extensions of the covered work,
237
+ and which are not combined with it such as to form a larger program,
238
+ in or on a volume of a storage or distribution medium, is called an
239
+ "aggregate" if the compilation and its resulting copyright are not
240
+ used to limit the access or legal rights of the compilation's users
241
+ beyond what the individual works permit. Inclusion of a covered work
242
+ in an aggregate does not cause this License to apply to the other
243
+ parts of the aggregate.
244
+
245
+ 6. Conveying Non-Source Forms.
246
+
247
+ You may convey a covered work in object code form under the terms
248
+ of sections 4 and 5, provided that you also convey the
249
+ machine-readable Corresponding Source under the terms of this License,
250
+ in one of these ways:
251
+
252
+ a) Convey the object code in, or embodied in, a physical product
253
+ (including a physical distribution medium), accompanied by the
254
+ Corresponding Source fixed on a durable physical medium
255
+ customarily used for software interchange.
256
+
257
+ b) Convey the object code in, or embodied in, a physical product
258
+ (including a physical distribution medium), accompanied by a
259
+ written offer, valid for at least three years and valid for as
260
+ long as you offer spare parts or customer support for that product
261
+ model, to give anyone who possesses the object code either (1) a
262
+ copy of the Corresponding Source for all the software in the
263
+ product that is covered by this License, on a durable physical
264
+ medium customarily used for software interchange, for a price no
265
+ more than your reasonable cost of physically performing this
266
+ conveying of source, or (2) access to copy the
267
+ Corresponding Source from a network server at no charge.
268
+
269
+ c) Convey individual copies of the object code with a copy of the
270
+ written offer to provide the Corresponding Source. This
271
+ alternative is allowed only occasionally and noncommercially, and
272
+ only if you received the object code with such an offer, in accord
273
+ with subsection 6b.
274
+
275
+ d) Convey the object code by offering access from a designated
276
+ place (gratis or for a charge), and offer equivalent access to the
277
+ Corresponding Source in the same way through the same place at no
278
+ further charge. You need not require recipients to copy the
279
+ Corresponding Source along with the object code. If the place to
280
+ copy the object code is a network server, the Corresponding Source
281
+ may be on a different server (operated by you or a third party)
282
+ that supports equivalent copying facilities, provided you maintain
283
+ clear directions next to the object code saying where to find the
284
+ Corresponding Source. Regardless of what server hosts the
285
+ Corresponding Source, you remain obligated to ensure that it is
286
+ available for as long as needed to satisfy these requirements.
287
+
288
+ e) Convey the object code using peer-to-peer transmission, provided
289
+ you inform other peers where the object code and Corresponding
290
+ Source of the work are being offered to the general public at no
291
+ charge under subsection 6d.
292
+
293
+ A separable portion of the object code, whose source code is excluded
294
+ from the Corresponding Source as a System Library, need not be
295
+ included in conveying the object code work.
296
+
297
+ A "User Product" is either (1) a "consumer product", which means any
298
+ tangible personal property which is normally used for personal, family,
299
+ or household purposes, or (2) anything designed or sold for incorporation
300
+ into a dwelling. In determining whether a product is a consumer product,
301
+ doubtful cases shall be resolved in favor of coverage. For a particular
302
+ product received by a particular user, "normally used" refers to a
303
+ typical or common use of that class of product, regardless of the status
304
+ of the particular user or of the way in which the particular user
305
+ actually uses, or expects or is expected to use, the product. A product
306
+ is a consumer product regardless of whether the product has substantial
307
+ commercial, industrial or non-consumer uses, unless such uses represent
308
+ the only significant mode of use of the product.
309
+
310
+ "Installation Information" for a User Product means any methods,
311
+ procedures, authorization keys, or other information required to install
312
+ and execute modified versions of a covered work in that User Product from
313
+ a modified version of its Corresponding Source. The information must
314
+ suffice to ensure that the continued functioning of the modified object
315
+ code is in no case prevented or interfered with solely because
316
+ modification has been made.
317
+
318
+ If you convey an object code work under this section in, or with, or
319
+ specifically for use in, a User Product, and the conveying occurs as
320
+ part of a transaction in which the right of possession and use of the
321
+ User Product is transferred to the recipient in perpetuity or for a
322
+ fixed term (regardless of how the transaction is characterized), the
323
+ Corresponding Source conveyed under this section must be accompanied
324
+ by the Installation Information. But this requirement does not apply
325
+ if neither you nor any third party retains the ability to install
326
+ modified object code on the User Product (for example, the work has
327
+ been installed in ROM).
328
+
329
+ The requirement to provide Installation Information does not include a
330
+ requirement to continue to provide support service, warranty, or updates
331
+ for a work that has been modified or installed by the recipient, or for
332
+ the User Product in which it has been modified or installed. Access to a
333
+ network may be denied when the modification itself materially and
334
+ adversely affects the operation of the network or violates the rules and
335
+ protocols for communication across the network.
336
+
337
+ Corresponding Source conveyed, and Installation Information provided,
338
+ in accord with this section must be in a format that is publicly
339
+ documented (and with an implementation available to the public in
340
+ source code form), and must require no special password or key for
341
+ unpacking, reading or copying.
342
+
343
+ 7. Additional Terms.
344
+
345
+ "Additional permissions" are terms that supplement the terms of this
346
+ License by making exceptions from one or more of its conditions.
347
+ Additional permissions that are applicable to the entire Program shall
348
+ be treated as though they were included in this License, to the extent
349
+ that they are valid under applicable law. If additional permissions
350
+ apply only to part of the Program, that part may be used separately
351
+ under those permissions, but the entire Program remains governed by
352
+ this License without regard to the additional permissions.
353
+
354
+ When you convey a copy of a covered work, you may at your option
355
+ remove any additional permissions from that copy, or from any part of
356
+ it. (Additional permissions may be written to require their own
357
+ removal in certain cases when you modify the work.) You may place
358
+ additional permissions on material, added by you to a covered work,
359
+ for which you have or can give appropriate copyright permission.
360
+
361
+ Notwithstanding any other provision of this License, for material you
362
+ add to a covered work, you may (if authorized by the copyright holders of
363
+ that material) supplement the terms of this License with terms:
364
+
365
+ a) Disclaiming warranty or limiting liability differently from the
366
+ terms of sections 15 and 16 of this License; or
367
+
368
+ b) Requiring preservation of specified reasonable legal notices or
369
+ author attributions in that material or in the Appropriate Legal
370
+ Notices displayed by works containing it; or
371
+
372
+ c) Prohibiting misrepresentation of the origin of that material, or
373
+ requiring that modified versions of such material be marked in
374
+ reasonable ways as different from the original version; or
375
+
376
+ d) Limiting the use for publicity purposes of names of licensors or
377
+ authors of the material; or
378
+
379
+ e) Declining to grant rights under trademark law for use of some
380
+ trade names, trademarks, or service marks; or
381
+
382
+ f) Requiring indemnification of licensors and authors of that
383
+ material by anyone who conveys the material (or modified versions of
384
+ it) with contractual assumptions of liability to the recipient, for
385
+ any liability that these contractual assumptions directly impose on
386
+ those licensors and authors.
387
+
388
+ All other non-permissive additional terms are considered "further
389
+ restrictions" within the meaning of section 10. If the Program as you
390
+ received it, or any part of it, contains a notice stating that it is
391
+ governed by this License along with a term that is a further
392
+ restriction, you may remove that term. If a license document contains
393
+ a further restriction but permits relicensing or conveying under this
394
+ License, you may add to a covered work material governed by the terms
395
+ of that license document, provided that the further restriction does
396
+ not survive such relicensing or conveying.
397
+
398
+ If you add terms to a covered work in accord with this section, you
399
+ must place, in the relevant source files, a statement of the
400
+ additional terms that apply to those files, or a notice indicating
401
+ where to find the applicable terms.
402
+
403
+ Additional terms, permissive or non-permissive, may be stated in the
404
+ form of a separately written license, or stated as exceptions;
405
+ the above requirements apply either way.
406
+
407
+ 8. Termination.
408
+
409
+ You may not propagate or modify a covered work except as expressly
410
+ provided under this License. Any attempt otherwise to propagate or
411
+ modify it is void, and will automatically terminate your rights under
412
+ this License (including any patent licenses granted under the third
413
+ paragraph of section 11).
414
+
415
+ However, if you cease all violation of this License, then your
416
+ license from a particular copyright holder is reinstated (a)
417
+ provisionally, unless and until the copyright holder explicitly and
418
+ finally terminates your license, and (b) permanently, if the copyright
419
+ holder fails to notify you of the violation by some reasonable means
420
+ prior to 60 days after the cessation.
421
+
422
+ Moreover, your license from a particular copyright holder is
423
+ reinstated permanently if the copyright holder notifies you of the
424
+ violation by some reasonable means, this is the first time you have
425
+ received notice of violation of this License (for any work) from that
426
+ copyright holder, and you cure the violation prior to 30 days after
427
+ your receipt of the notice.
428
+
429
+ Termination of your rights under this section does not terminate the
430
+ licenses of parties who have received copies or rights from you under
431
+ this License. If your rights have been terminated and not permanently
432
+ reinstated, you do not qualify to receive new licenses for the same
433
+ material under section 10.
434
+
435
+ 9. Acceptance Not Required for Having Copies.
436
+
437
+ You are not required to accept this License in order to receive or
438
+ run a copy of the Program. Ancillary propagation of a covered work
439
+ occurring solely as a consequence of using peer-to-peer transmission
440
+ to receive a copy likewise does not require acceptance. However,
441
+ nothing other than this License grants you permission to propagate or
442
+ modify any covered work. These actions infringe copyright if you do
443
+ not accept this License. Therefore, by modifying or propagating a
444
+ covered work, you indicate your acceptance of this License to do so.
445
+
446
+ 10. Automatic Licensing of Downstream Recipients.
447
+
448
+ Each time you convey a covered work, the recipient automatically
449
+ receives a license from the original licensors, to run, modify and
450
+ propagate that work, subject to this License. You are not responsible
451
+ for enforcing compliance by third parties with this License.
452
+
453
+ An "entity transaction" is a transaction transferring control of an
454
+ organization, or substantially all assets of one, or subdividing an
455
+ organization, or merging organizations. If propagation of a covered
456
+ work results from an entity transaction, each party to that
457
+ transaction who receives a copy of the work also receives whatever
458
+ licenses to the work the party's predecessor in interest had or could
459
+ give under the previous paragraph, plus a right to possession of the
460
+ Corresponding Source of the work from the predecessor in interest, if
461
+ the predecessor has it or can get it with reasonable efforts.
462
+
463
+ You may not impose any further restrictions on the exercise of the
464
+ rights granted or affirmed under this License. For example, you may
465
+ not impose a license fee, royalty, or other charge for exercise of
466
+ rights granted under this License, and you may not initiate litigation
467
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
468
+ any patent claim is infringed by making, using, selling, offering for
469
+ sale, or importing the Program or any portion of it.
470
+
471
+ 11. Patents.
472
+
473
+ A "contributor" is a copyright holder who authorizes use under this
474
+ License of the Program or a work on which the Program is based. The
475
+ work thus licensed is called the contributor's "contributor version".
476
+
477
+ A contributor's "essential patent claims" are all patent claims
478
+ owned or controlled by the contributor, whether already acquired or
479
+ hereafter acquired, that would be infringed by some manner, permitted
480
+ by this License, of making, using, or selling its contributor version,
481
+ but do not include claims that would be infringed only as a
482
+ consequence of further modification of the contributor version. For
483
+ purposes of this definition, "control" includes the right to grant
484
+ patent sublicenses in a manner consistent with the requirements of
485
+ this License.
486
+
487
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
488
+ patent license under the contributor's essential patent claims, to
489
+ make, use, sell, offer for sale, import and otherwise run, modify and
490
+ propagate the contents of its contributor version.
491
+
492
+ In the following three paragraphs, a "patent license" is any express
493
+ agreement or commitment, however denominated, not to enforce a patent
494
+ (such as an express permission to practice a patent or covenant not to
495
+ sue for patent infringement). To "grant" such a patent license to a
496
+ party means to make such an agreement or commitment not to enforce a
497
+ patent against the party.
498
+
499
+ If you convey a covered work, knowingly relying on a patent license,
500
+ and the Corresponding Source of the work is not available for anyone
501
+ to copy, free of charge and under the terms of this License, through a
502
+ publicly available network server or other readily accessible means,
503
+ then you must either (1) cause the Corresponding Source to be so
504
+ available, or (2) arrange to deprive yourself of the benefit of the
505
+ patent license for this particular work, or (3) arrange, in a manner
506
+ consistent with the requirements of this License, to extend the patent
507
+ license to downstream recipients. "Knowingly relying" means you have
508
+ actual knowledge that, but for the patent license, your conveying the
509
+ covered work in a country, or your recipient's use of the covered work
510
+ in a country, would infringe one or more identifiable patents in that
511
+ country that you have reason to believe are valid.
512
+
513
+ If, pursuant to or in connection with a single transaction or
514
+ arrangement, you convey, or propagate by procuring conveyance of, a
515
+ covered work, and grant a patent license to some of the parties
516
+ receiving the covered work authorizing them to use, propagate, modify
517
+ or convey a specific copy of the covered work, then the patent license
518
+ you grant is automatically extended to all recipients of the covered
519
+ work and works based on it.
520
+
521
+ A patent license is "discriminatory" if it does not include within
522
+ the scope of its coverage, prohibits the exercise of, or is
523
+ conditioned on the non-exercise of one or more of the rights that are
524
+ specifically granted under this License. You may not convey a covered
525
+ work if you are a party to an arrangement with a third party that is
526
+ in the business of distributing software, under which you make payment
527
+ to the third party based on the extent of your activity of conveying
528
+ the work, and under which the third party grants, to any of the
529
+ parties who would receive the covered work from you, a discriminatory
530
+ patent license (a) in connection with copies of the covered work
531
+ conveyed by you (or copies made from those copies), or (b) primarily
532
+ for and in connection with specific products or compilations that
533
+ contain the covered work, unless you entered into that arrangement,
534
+ or that patent license was granted, prior to 28 March 2007.
535
+
536
+ Nothing in this License shall be construed as excluding or limiting
537
+ any implied license or other defenses to infringement that may
538
+ otherwise be available to you under applicable patent law.
539
+
540
+ 12. No Surrender of Others' Freedom.
541
+
542
+ If conditions are imposed on you (whether by court order, agreement or
543
+ otherwise) that contradict the conditions of this License, they do not
544
+ excuse you from the conditions of this License. If you cannot convey a
545
+ covered work so as to satisfy simultaneously your obligations under this
546
+ License and any other pertinent obligations, then as a consequence you may
547
+ not convey it at all. For example, if you agree to terms that obligate you
548
+ to collect a royalty for further conveying from those to whom you convey
549
+ the Program, the only way you could satisfy both those terms and this
550
+ License would be to refrain entirely from conveying the Program.
551
+
552
+ 13. Use with the GNU Affero General Public License.
553
+
554
+ Notwithstanding any other provision of this License, you have
555
+ permission to link or combine any covered work with a work licensed
556
+ under version 3 of the GNU Affero General Public License into a single
557
+ combined work, and to convey the resulting work. The terms of this
558
+ License will continue to apply to the part which is the covered work,
559
+ but the special requirements of the GNU Affero General Public License,
560
+ section 13, concerning interaction through a network will apply to the
561
+ combination as such.
562
+
563
+ 14. Revised Versions of this License.
564
+
565
+ The Free Software Foundation may publish revised and/or new versions of
566
+ the GNU General Public License from time to time. Such new versions will
567
+ be similar in spirit to the present version, but may differ in detail to
568
+ address new problems or concerns.
569
+
570
+ Each version is given a distinguishing version number. If the
571
+ Program specifies that a certain numbered version of the GNU General
572
+ Public License "or any later version" applies to it, you have the
573
+ option of following the terms and conditions either of that numbered
574
+ version or of any later version published by the Free Software
575
+ Foundation. If the Program does not specify a version number of the
576
+ GNU General Public License, you may choose any version ever published
577
+ by the Free Software Foundation.
578
+
579
+ If the Program specifies that a proxy can decide which future
580
+ versions of the GNU General Public License can be used, that proxy's
581
+ public statement of acceptance of a version permanently authorizes you
582
+ to choose that version for the Program.
583
+
584
+ Later license versions may give you additional or different
585
+ permissions. However, no additional obligations are imposed on any
586
+ author or copyright holder as a result of your choosing to follow a
587
+ later version.
588
+
589
+ 15. Disclaimer of Warranty.
590
+
591
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599
+
600
+ 16. Limitation of Liability.
601
+
602
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610
+ SUCH DAMAGES.
611
+
612
+ 17. Interpretation of Sections 15 and 16.
613
+
614
+ If the disclaimer of warranty and limitation of liability provided
615
+ above cannot be given local legal effect according to their terms,
616
+ reviewing courts shall apply local law that most closely approximates
617
+ an absolute waiver of all civil liability in connection with the
618
+ Program, unless a warranty or assumption of liability accompanies a
619
+ copy of the Program in return for a fee.
620
+
621
+ END OF TERMS AND CONDITIONS
622
+
623
+ How to Apply These Terms to Your New Programs
624
+
625
+ If you develop a new program, and you want it to be of the greatest
626
+ possible use to the public, the best way to achieve this is to make it
627
+ free software which everyone can redistribute and change under these terms.
628
+
629
+ To do so, attach the following notices to the program. It is safest
630
+ to attach them to the start of each source file to most effectively
631
+ state the exclusion of warranty; and each file should have at least
632
+ the "copyright" line and a pointer to where the full notice is found.
633
+
634
+ <one line to give the program's name and a brief idea of what it does.>
635
+ Copyright (C) <year> <name of author>
636
+
637
+ This program is free software: you can redistribute it and/or modify
638
+ it under the terms of the GNU General Public License as published by
639
+ the Free Software Foundation, either version 3 of the License, or
640
+ (at your option) any later version.
641
+
642
+ This program is distributed in the hope that it will be useful,
643
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
644
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645
+ GNU General Public License for more details.
646
+
647
+ You should have received a copy of the GNU General Public License
648
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
649
+
650
+ Also add information on how to contact you by electronic and paper mail.
651
+
652
+ If the program does terminal interaction, make it output a short
653
+ notice like this when it starts in an interactive mode:
654
+
655
+ <program> Copyright (C) <year> <name of author>
656
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657
+ This is free software, and you are welcome to redistribute it
658
+ under certain conditions; type `show c' for details.
659
+
660
+ The hypothetical commands `show w' and `show c' should show the appropriate
661
+ parts of the General Public License. Of course, your program's commands
662
+ might be different; for a GUI interface, you would use an "about box".
663
+
664
+ You should also get your employer (if you work as a programmer) or school,
665
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
666
+ For more information on this, and how to apply and follow the GNU GPL, see
667
+ <https://www.gnu.org/licenses/>.
668
+
669
+ The GNU General Public License does not permit incorporating your program
670
+ into proprietary programs. If your program is a subroutine library, you
671
+ may consider it more useful to permit linking proprietary applications with
672
+ the library. If this is what you want to do, use the GNU Lesser General
673
+ Public License instead of this License. But first, please read
674
+ <https://www.gnu.org/licenses/why-not-lgpl.html>.
python_embeded/Lib/site-packages/color_matcher-0.6.0.dist-info/METADATA ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.1
2
+ Name: color-matcher
3
+ Version: 0.6.0
4
+ Summary: Package enabling color transfer across images
5
+ Home-page: http://github.com/hahnec/color-matcher
6
+ Author: Christopher Hahne
7
+ Author-email: inbox@christopherhahne.de
8
+ License: GNU GPL V3.0
9
+ 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
10
+ Requires-Python: >=3
11
+ Description-Content-Type: text/x-rst
12
+ License-File: LICENSE
13
+ Requires-Dist: ddt
14
+ Requires-Dist: docutils
15
+ Requires-Dist: imageio
16
+ Requires-Dist: matplotlib
17
+ Requires-Dist: numpy >=1.21
18
+ Requires-Dist: packaging >=24.2
19
+
20
+ color-matcher enables color transfer across images which comes in handy for automatic color-grading
21
+ of photographs, paintings and film sequences as well as light-field and stopmotion corrections. The methods behind
22
+ the mappings are based on the approach from Reinhard et al., the Monge-Kantorovich Linearization (MKL) as proposed by
23
+ Pitie et al. and our analytical solution to a Multi-Variate Gaussian Distribution (MVGD) transfer in conjunction with
24
+ classical histogram matching. As shown below our HM-MVGD-HM compound outperforms existing methods.
python_embeded/Lib/site-packages/color_matcher-0.6.0.dist-info/WHEEL ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.42.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
python_embeded/Lib/site-packages/color_matcher-0.6.0.dist-info/entry_points.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ [console_scripts]
2
+ color-matcher = color_matcher.bin.cli:main
python_embeded/Lib/site-packages/color_matcher-0.6.0.dist-info/top_level.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ color_matcher
2
+ tests
python_embeded/Lib/site-packages/color_matcher/__init__.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ __author__ = "Christopher Hahne"
4
+ __email__ = "inbox@christopherhahne.de"
5
+ __license__ = """
6
+ Copyright (c) 2020 Christopher Hahne <inbox@christopherhahne.de>
7
+ This program is free software: you can redistribute it and/or modify
8
+ it under the terms of the GNU General Public License as published by
9
+ the Free Software Foundation, either version 3 of the License, or
10
+ (at your option) any later version.
11
+ This program is distributed in the hope that it will be useful,
12
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
+ GNU General Public License for more details.
15
+ You should have received a copy of the GNU General Public License
16
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
17
+ """
18
+
19
+ __version__ = '0.6.0'
20
+
21
+ from .top_level import ColorMatcher
22
+ from .hist_matcher import HistogramMatcher
23
+ from .mvgd_matcher import TransferMVGD
24
+ from .reinhard_matcher import ReinhardMatcher
25
+ from .baseclass import MatcherBaseclass
python_embeded/Lib/site-packages/color_matcher/baseclass.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ __author__ = "Christopher Hahne"
4
+ __email__ = "inbox@christopherhahne.de"
5
+ __license__ = """
6
+ Copyright (c) 2020 Christopher Hahne <inbox@christopherhahne.de>
7
+ This program is free software: you can redistribute it and/or modify
8
+ it under the terms of the GNU General Public License as published by
9
+ the Free Software Foundation, either version 3 of the License, or
10
+ (at your option) any later version.
11
+ This program is distributed in the hope that it will be useful,
12
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
+ GNU General Public License for more details.
15
+ You should have received a copy of the GNU General Public License
16
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
17
+ """
18
+
19
+ import numpy as np
20
+ import warnings
21
+
22
+
23
+ class MatcherBaseclass(object):
24
+
25
+ def __init__(self, *args, **kwargs):
26
+
27
+ self._src = None
28
+ self._ref = None
29
+ self._funs = []
30
+
31
+ if len(args) == 2:
32
+ self._src = args[0]
33
+ self._ref = args[1]
34
+
35
+ if bool(kwargs):
36
+ self._src = kwargs['src'] if 'src' in kwargs else self._src
37
+ self._ref = kwargs['ref'] if 'ref' in kwargs else self._ref
38
+
39
+ def validate_img_dims(self):
40
+ """
41
+ This function validates the image dimensions. It throws an exception if the dimension are unequal to 2 or 3.
42
+ """
43
+
44
+ # add third image dimension for monochromatic images
45
+ self._src = self._src[..., np.newaxis] if len(self._src.shape) == 2 else self._src
46
+ self._ref = self._ref[..., np.newaxis] if len(self._ref.shape) == 2 else self._ref
47
+
48
+ if len(self._src.shape) not in (2, 3) or len(self._ref.shape) not in (2, 3):
49
+ raise BaseException('Each image must have 2 or 3 dimensions')
50
+
51
+ return True
52
+
53
+ def validate_color_chs(self):
54
+ """
55
+ This function checks whether provided images consist of a valid number of color channels.
56
+ """
57
+
58
+ if len(self._src.shape) == 3 or len(self._ref.shape) == 3:
59
+ if self._src.shape[2] > 4 or self._ref.shape[2] > 4:
60
+ raise BaseException('Each image cannot have more than 4 color channels')
61
+ elif self._src.shape[2] == 3 and self._ref.shape[2] == 4:
62
+ self._ref = self._ref[..., :3]
63
+ elif self._src.shape[2] == 4 and self._ref.shape[2] == 3:
64
+ self._src = self._src[..., :3]
65
+ elif self._src.shape[2] == 1 and self._ref.shape[2] == 3:
66
+ self._ref = self.rgb2gray(self._ref)
67
+ elif self._src.shape[2] == 3 and self._ref.shape[2] == 1:
68
+ self._src = self.rgb2gray(self._src)
69
+
70
+ if self._src.shape[2] == 1 and self._ref.shape[2] == 1:
71
+ # restrict monochromatic transfer to histogram matching
72
+ self._funs = [self.hist_match]
73
+ warnings.warn('Transfer restricted to histogram matching due to monochromatic input')
74
+
75
+ return True
76
+
77
+ @staticmethod
78
+ def rgb2gray(rgb: np.ndarray = None, standard: str = 'HDTV') -> np.ndarray:
79
+ """ Convert RGB color space to monochromatic color space
80
+
81
+ :param rgb: input array in red, green and blue (RGB) space
82
+ :type rgb: :class:`~numpy:numpy.ndarray`
83
+ :param standard: option that determines whether head- and footroom are excluded ('HDTV') or considered otherwise
84
+ :type standard: :class:`string`
85
+ :return: array in monochromatic space
86
+ :rtype: ~numpy:np.ndarray
87
+
88
+ """
89
+
90
+ # store shape
91
+ shape = rgb.shape
92
+
93
+ # reshape image to channel vectors
94
+ rgb = rgb.reshape(-1, 3).T
95
+
96
+ # choose standard
97
+ mat = np.array([0.2126, 0.7152, 0.0722]) if standard == 'HDTV' else np.array([0.299, 0.587, 0.114])
98
+
99
+ # convert to gray
100
+ arr = np.dot(mat, rgb)
101
+
102
+ # reshape to 2-D image
103
+ arr = arr.reshape(shape[:2] + (1,))
104
+
105
+ return arr
python_embeded/Lib/site-packages/color_matcher/hist_matcher.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ __author__ = "Christopher Hahne"
4
+ __email__ = "info@christopherhahne.de"
5
+ __license__ = """
6
+ Copyright (c) 2020 Christopher Hahne <info@christopherhahne.de>
7
+
8
+ This program is free software: you can redistribute it and/or modify
9
+ it under the terms of the GNU General Public License as published by
10
+ the Free Software Foundation, either version 3 of the License, or
11
+ (at your option) any later version.
12
+
13
+ This program is distributed in the hope that it will be useful,
14
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16
+ GNU General Public License for more details.
17
+
18
+ You should have received a copy of the GNU General Public License
19
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
20
+
21
+ """
22
+
23
+ import numpy as np
24
+
25
+ from .baseclass import MatcherBaseclass
26
+
27
+
28
+ class HistogramMatcher(MatcherBaseclass):
29
+
30
+ def __init__(self, *args, **kwargs):
31
+ super(HistogramMatcher, self).__init__(*args, **kwargs)
32
+
33
+ def hist_match(self, src: np.ndarray = None, ref: np.ndarray = None) -> np.ndarray:
34
+ """
35
+
36
+ This function conducts channel-wise histogram matching which is invariant of image resolutions,
37
+ but requires the same number of color channels in both images.
38
+
39
+ :param src: Source image that requires transfer
40
+ :param ref: Palette image which serves as reference
41
+ :param res: Resulting image after the mapping
42
+
43
+ :type src: :class:`~numpy:numpy.ndarray`
44
+ :type ref: :class:`~numpy:numpy.ndarray`
45
+ :type res: :class:`~numpy:numpy.ndarray`
46
+
47
+ :return: **res**
48
+ :rtype: np.ndarray
49
+
50
+ """
51
+
52
+ # override source and reference image with arguments (if provided)
53
+ self._src = src if src is not None else self._src
54
+ self._ref = ref if ref is not None else self._ref
55
+
56
+ # parameter init
57
+ res = np.zeros_like(self._src)
58
+
59
+ for ch in range(self._src.shape[2]):
60
+
61
+ # convert to 1D arrays
62
+ src_vec = self._src[..., ch].ravel()
63
+ ref_vec = self._ref[..., ch].ravel()
64
+
65
+ # analyze histograms
66
+ _, src_idxs, src_cnts = np.unique(src_vec, return_inverse=True, return_counts=True)
67
+ ref_vals, ref_cnts = np.unique(ref_vec, return_counts=True)
68
+
69
+ # compute cumulative distribution functions
70
+ src_cdf = np.cumsum(src_cnts).astype(np.float64) / src_vec.size
71
+ ref_cdf = np.cumsum(ref_cnts).astype(np.float64) / ref_vec.size
72
+
73
+ # do the histogram mapping
74
+ interp_vals = np.interp(src_cdf, ref_cdf, ref_vals)
75
+ res[..., ch] = interp_vals[src_idxs].reshape(src[..., ch].shape)
76
+
77
+ return res
python_embeded/Lib/site-packages/color_matcher/io_handler.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ __author__ = "Christopher Hahne"
4
+ __email__ = "info@christopherhahne.de"
5
+ __license__ = """
6
+ Copyright (c) 2020 Christopher Hahne <info@christopherhahne.de>
7
+
8
+ This program is free software: you can redistribute it and/or modify
9
+ it under the terms of the GNU General Public License as published by
10
+ the Free Software Foundation, either version 3 of the License, or
11
+ (at your option) any later version.
12
+
13
+ This program is distributed in the hope that it will be useful,
14
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16
+ GNU General Public License for more details.
17
+
18
+ You should have received a copy of the GNU General Public License
19
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
20
+
21
+ """
22
+
23
+ import os
24
+ import numpy as np
25
+
26
+ try:
27
+ from PIL import Image
28
+ except ImportError:
29
+ raise ImportError('Please install pillow.')
30
+
31
+ from color_matcher.normalizer import Normalizer
32
+
33
+ FILE_EXTS = ('bmp', 'png', 'tiff', 'tif', 'jpeg', 'jpg')
34
+
35
+
36
+ def save_img_file(img, file_path: str = None, file_type: str = None) -> bool:
37
+
38
+ file_path = os.getcwd() if file_path is None else file_path
39
+ ext = os.path.splitext(file_path)[-1][1:]
40
+
41
+ if not file_type:
42
+ file_type = ext if ext == 'png' or ext == 'tiff' else 'tiff' if img.dtype == 'uint16' else 'png'
43
+
44
+ # compose new file path string if extension type changed
45
+ file_path = os.path.splitext(file_path)[-2] if file_path.endswith(FILE_EXTS) else file_path
46
+ file_type = 'png' if file_type is None else file_type
47
+ file_path += '.' + file_type
48
+
49
+ # normalization
50
+ img = Normalizer(img).uint16_norm() if file_type.__contains__('tif') else Normalizer(img).uint8_norm()
51
+
52
+ try:
53
+ import imageio
54
+ suppress_user_warning(True, category=UserWarning)
55
+ imageio.imwrite(uri=file_path, im=img)
56
+ suppress_user_warning(False, category=UserWarning)
57
+ except ImportError:
58
+ if file_type == 'png' or file_type == 'bmp':
59
+ try:
60
+ Image.fromarray(img).save(file_path, file_type, optimize=True)
61
+ #imageio.imwrite(uri=file_path, im=img)
62
+ except PermissionError as e:
63
+ raise Exception(e)
64
+
65
+ return True
66
+
67
+
68
+ def load_img_file(file_path: str = None) -> np.ndarray:
69
+
70
+ # get file extension
71
+ file_type = file_path.split('.')[-1]
72
+
73
+ if any(file_type.lower() in ext for ext in FILE_EXTS):
74
+ try:
75
+ import imageio
76
+ suppress_user_warning(True, category=UserWarning)
77
+ img = imageio.imread(uri=file_path, format=file_type)
78
+ suppress_user_warning(False, category=UserWarning)
79
+ except ImportError:
80
+ try:
81
+ img = Image.open(file_path)
82
+ except OSError or TypeError:
83
+ # support load of truncated images
84
+ from PIL import ImageFile
85
+ ImageFile.LOAD_TRUNCATED_IMAGES = True
86
+ img = Image.open(file_path)
87
+
88
+ else:
89
+ raise TypeError('Filetype %s not recognized' % file_type)
90
+
91
+ # normalize (convert to numpy array)
92
+ img = Normalizer(np.asarray(img)).type_norm()
93
+
94
+ return img
95
+
96
+
97
+ def suppress_user_warning(switch=None, category=None):
98
+
99
+ import warnings
100
+ switch = switch if switch is None else True
101
+ if switch:
102
+ warnings.filterwarnings("ignore", category=category)
103
+ else:
104
+ warnings.filterwarnings("default", category=category)
105
+
106
+
107
+ def select_file(init_dir=None, title=''):
108
+ """ get filepath from tkinter dialog """
109
+
110
+ # consider initial directory if provided
111
+ init_dir = os.path.expanduser('~/') if not init_dir else init_dir
112
+
113
+ # import tkinter while considering Python version
114
+ try:
115
+ import tkinter as tk
116
+ from tkinter.filedialog import askopenfilename
117
+ except ImportError:
118
+ import Tkinter as tk
119
+ from tkFileDialog import askopenfilename
120
+
121
+ # open window using tkinter
122
+ root = tk.Tk()
123
+ root.withdraw()
124
+ root.update()
125
+ file_path = askopenfilename(initialdir=[init_dir], title=title)
126
+ root.update()
127
+
128
+ return file_path if file_path else None
python_embeded/Lib/site-packages/color_matcher/mvgd_matcher.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ __author__ = "Christopher Hahne"
4
+ __email__ = "info@christopherhahne.de"
5
+ __license__ = """
6
+ Copyright (c) 2020 Christopher Hahne <info@christopherhahne.de>
7
+
8
+ This program is free software: you can redistribute it and/or modify
9
+ it under the terms of the GNU General Public License as published by
10
+ the Free Software Foundation, either version 3 of the License, or
11
+ (at your option) any later version.
12
+
13
+ This program is distributed in the hope that it will be useful,
14
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16
+ GNU General Public License for more details.
17
+
18
+ You should have received a copy of the GNU General Public License
19
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
20
+
21
+ """
22
+
23
+ import numpy as np
24
+
25
+ from .baseclass import MatcherBaseclass
26
+ from types import FunctionType
27
+
28
+
29
+ class TransferMVGD(MatcherBaseclass):
30
+
31
+ def __init__(self, *args, **kwargs):
32
+ super(TransferMVGD, self).__init__(*args, **kwargs)
33
+
34
+ # extract method from kwargs (if available)
35
+ self._fun_dict = {'mvgd': self.analytical_solver, 'mkl': self.mkl_solver}
36
+ try:
37
+ self._fun_name = [kw for kw in list(self._fun_dict.keys()) if kwargs['method'].__contains__(kw)][0]
38
+ except (BaseException, IndexError):
39
+ # default function
40
+ self._fun_name = 'mkl'
41
+ self._fun_call = self._fun_dict[self._fun_name] if self._fun_name in self._fun_dict else self.mkl_solver
42
+
43
+ # initialize variables
44
+ self.r, self.z, self.cov_r, self.cov_z, self.mu_r, self.mu_z, self.transfer_mat = [None]*7
45
+
46
+ def init_vars(self):
47
+
48
+ # reshape source and reference images
49
+ self.r, self.z = self._src.reshape([-1, self._src.shape[2]]).T, self._ref.reshape([-1, self._ref.shape[2]]).T
50
+
51
+ # compute covariance matrices
52
+ self.cov_r, self.cov_z = np.cov(self.r), np.cov(self.z)
53
+
54
+ # compute color channel means
55
+ self.mu_r, self.mu_z = self.r.mean(axis=1)[..., np.newaxis], self.z.mean(axis=1)[..., np.newaxis]
56
+
57
+ # validate dimensionality
58
+ self.check_dims()
59
+
60
+ def multivar_transfer(self, src: np.ndarray = None, ref: np.ndarray = None, fun: FunctionType = None) -> np.ndarray:
61
+ """
62
+
63
+ Transfer function to map colors based on for Multi-Variate Gaussian Distributions (MVGDs).
64
+
65
+ :param src: Source image that requires transfer
66
+ :param ref: Palette image which serves as reference
67
+ :param fun: Optional argument to pass a transfer function to solve for covariance matrices
68
+ :param res: Resulting image after the mapping
69
+
70
+ :type src: :class:`~numpy:numpy.ndarray`
71
+ :type ref: :class:`~numpy:numpy.ndarray`
72
+ :type res: :class:`~numpy:numpy.ndarray`
73
+
74
+ :return: **res**
75
+ :rtype: np.ndarray
76
+
77
+ """
78
+
79
+ # override source and reference image with arguments (if provided)
80
+ self._src = src if src is not None else self._src
81
+ self._ref = ref if ref is not None else self._ref
82
+
83
+ # check if three color channels are provided
84
+ self.validate_color_chs()
85
+
86
+ # re-initialize variables to account for change in src and ref when passed to self.transfer()
87
+ self.init_vars()
88
+
89
+ # set solver function for transfer matrix
90
+ self._fun_call = fun if fun is FunctionType else self._fun_call
91
+
92
+ # compute transfer matrix
93
+ self.transfer_mat = self._fun_call()
94
+
95
+ # transfer the intensity distributions
96
+ res = np.dot(self.transfer_mat, self.r - self.mu_r) + self.mu_z
97
+
98
+ # reshape pixel array
99
+ res = res.T.reshape(self._src.shape)
100
+
101
+ return res
102
+
103
+ def mkl_solver(self):
104
+ """
105
+ This function computes the transfer matrix based on the Monge-Kantorovich Linearization (MKL).
106
+
107
+ :return: **transfer_mat**: Transfer matrix
108
+ :type transfer_mat: :class:`~numpy:numpy.ndarray`
109
+ :rtype: np.ndarray
110
+
111
+ """
112
+
113
+ # validate dimensionality
114
+ self.check_dims()
115
+
116
+ eig_val_r, eig_vec_r = np.linalg.eig(self.cov_r)
117
+ eig_val_r[eig_val_r < 0] = 0
118
+ val_r = np.diag(np.sqrt(eig_val_r[::-1]))
119
+ vec_r = np.array(eig_vec_r[:, ::-1])
120
+ inv_r = np.diag(1. / (np.diag(val_r + np.spacing(1))))
121
+
122
+ mat_c = val_r @ vec_r.T @ self.cov_z @ vec_r @ val_r
123
+ eig_val_c, eig_vec_c = np.linalg.eig(mat_c)
124
+ eig_val_c[eig_val_c < 0] = 0
125
+ val_c = np.diag(np.sqrt(eig_val_c))
126
+
127
+ self.transfer_mat = vec_r @ inv_r @ eig_vec_c @ val_c @ eig_vec_c.T @ inv_r @ vec_r.T
128
+
129
+ return self.transfer_mat
130
+
131
+ def analytical_solver(self) -> np.ndarray:
132
+ """
133
+ An analytical solution to the linear equation system of Multi-Variate Gaussian Distributions (MVGDs).
134
+
135
+ :return: **transfer_mat**: Transfer matrix
136
+ :type transfer_mat: :class:`~numpy:numpy.ndarray`
137
+ :rtype: np.ndarray
138
+
139
+ """
140
+
141
+ # validate dimensionality
142
+ self.check_dims()
143
+ if self.r.shape[-1] != self.z.shape[-1]:
144
+ raise Exception('Analytical MVGD solution requires spatial dimensions of both images to be equal')
145
+
146
+ cov_r_inv = np.linalg.pinv(self.cov_r)
147
+ cov_z_inv = np.linalg.pinv(self.cov_z)
148
+
149
+ # compute transfer matrix using analytical method
150
+ self.transfer_mat = np.linalg.pinv((self.z-self.mu_z).T @ cov_z_inv) @ (self.r-self.mu_r).T @ cov_r_inv
151
+
152
+ return self.transfer_mat
153
+
154
+ @staticmethod
155
+ def w2_dist(mu_a: np.ndarray, mu_b: np.ndarray, cov_a: np.ndarray, cov_b: np.ndarray) -> float:
156
+ """
157
+ Wasserstein-2 distance metric is a similarity measure for Gaussian distributions
158
+
159
+ :param mu_a: Gaussian mean of distribution *a*
160
+ :param mu_b: Gaussian mean of distribution *b*
161
+ :param cov_a: Covariance matrix of distribution *a*
162
+ :param cov_b: Covariance matrix of distribution *b*
163
+
164
+ :type mu_a: :class:`~numpy:numpy.ndarray`
165
+ :type mu_b: :class:`~numpy:numpy.ndarray`
166
+ :type cov_a: :class:`~numpy:numpy.ndarray`
167
+ :type cov_b: :class:`~numpy:numpy.ndarray`
168
+
169
+ :return: **scalar**: Wasserstein-2 metric as a scalar
170
+ :rtype: float
171
+ """
172
+
173
+ mean_dist = np.sum((mu_a-mu_b)**2)
174
+ 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))
175
+
176
+ return float(mean_dist + vars_dist)
177
+
178
+ def w2_img_dist(self, img_a: np.ndarray, img_b:np.ndarray):
179
+
180
+ """
181
+ Wasserstein-2 image distance metric is a similarity measure for Gaussian distributions
182
+
183
+ :param img_a: Image array *a*
184
+ :param img_b: Image array *b*
185
+
186
+ :type img_a: :class:`~numpy:numpy.ndarray`
187
+ :type img_b: :class:`~numpy:numpy.ndarray`
188
+
189
+ :return: **scalar**: Wasserstein-2 image metric as a scalar
190
+ :rtype: float
191
+ """
192
+
193
+ mu_a, mu_b = np.mean(img_a, axis=(0, 1)), np.mean(img_b, axis=(0, 1))
194
+ cov_a, cov_b = np.cov(img_a.reshape(-1, 3).T), np.cov(img_b.reshape(-1, 3).T)
195
+ w2_img_dist = self.w2_dist(mu_a, mu_b, cov_a, cov_b)
196
+
197
+ return w2_img_dist
198
+
199
+ def check_dims(self):
200
+ """
201
+ Catch error for wrong color channel number (e.g., gray scale image)
202
+
203
+ :return: None
204
+ """
205
+
206
+ if np.ndim(self.cov_r) == 0 or np.ndim(self.cov_z) == 0:
207
+ raise Exception('Wrong color channel dimensionality for %s method' % self._fun_name)
python_embeded/Lib/site-packages/color_matcher/normalizer.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ __author__ = "Christopher Hahne"
4
+ __email__ = "info@christopherhahne.de"
5
+ __license__ = """
6
+ Copyright (c) 2019 Christopher Hahne <info@christopherhahne.de>
7
+
8
+ This program is free software: you can redistribute it and/or modify
9
+ it under the terms of the GNU General Public License as published by
10
+ the Free Software Foundation, either version 3 of the License, or
11
+ (at your option) any later version.
12
+
13
+ This program is distributed in the hope that it will be useful,
14
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16
+ GNU General Public License for more details.
17
+
18
+ You should have received a copy of the GNU General Public License
19
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
20
+
21
+ """
22
+
23
+ import numpy as np
24
+
25
+
26
+ class Normalizer(object):
27
+
28
+ def __init__(self, data=None, min=None, max=None):
29
+
30
+ self._data, self._min, self._max = None, None, None
31
+ self._var_init(data, min, max)
32
+
33
+ def _var_init(self, data=None, min=None, max=None):
34
+
35
+ self._data = self._data if data is None else np.asarray(data, dtype='float64')
36
+ self._dtype = str(self._data.dtype) if isinstance(self._data, np.ndarray) else 'float64'
37
+
38
+ self._min = self._min if min is None else min
39
+ self._max = self._max if max is None else max
40
+ self._min = self._data.min() if not any([self._min, min]) and isinstance(self._data, np.ndarray) else self._min
41
+ self._max = self._data.max() if not any([self._max, max]) and isinstance(self._data, np.ndarray) else self._max
42
+
43
+ def uint16_norm(self):
44
+ """ normalize image array to 16-bit unsigned integer """
45
+
46
+ return np.asarray(np.round(self.norm_fun()*(2**16-1)), dtype=np.uint16)
47
+
48
+ def uint8_norm(self):
49
+ """ normalize image array to 8-bit unsigned integer """
50
+
51
+ return np.asarray(np.round(self.norm_fun()*(2**8-1)), dtype=np.uint8)
52
+
53
+ def type_norm(self, data=None, min=None, max=None, new_min=None, new_max=None):
54
+ """ normalize numpy image array for provided data type """
55
+
56
+ self._var_init(data, min, max)
57
+
58
+ if self._dtype.startswith(('int', 'uint')):
59
+ new_max = np.iinfo(np.dtype(self._dtype)).max if new_max is None else new_max
60
+ new_min = np.iinfo(np.dtype(self._dtype)).min if new_min is None else new_min
61
+ img_norm = np.round(self.norm_fun() * (new_max - new_min) + new_min)
62
+ else:
63
+ new_max = 1.0 if new_max is None else new_max
64
+ new_min = 0.0 if new_min is None else new_min
65
+ img_norm = self.norm_fun() * (new_max - new_min) + new_min
66
+
67
+ return np.asarray(img_norm, dtype=self._dtype)
68
+
69
+ def norm_fun(self):
70
+ """ normalize image to values between 1 and 0 """
71
+
72
+ norm = (self._data - self._min) / (self._max - self._min) if self._max != (self._min and 0) else self._data
73
+
74
+ # prevent wrap-around
75
+ norm[norm < 0] = 0
76
+ norm[norm > 1] = 1
77
+
78
+ return norm
python_embeded/Lib/site-packages/color_matcher/reinhard_matcher.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from .baseclass import MatcherBaseclass
4
+
5
+ LMS_MAT = np.array([[0.3811, 0.5783, 0.0402], [0.1967, 0.7244, 0.0782], [0.0241, 0.1288, 0.8444]])
6
+ LMS_MAT_INV = np.array([[4.4679, -3.5873, 0.1193], [-1.2186, 2.3809, -0.1624], [0.0497, -0.2439, 1.2045]])
7
+
8
+
9
+ class ReinhardMatcher(MatcherBaseclass):
10
+
11
+ def __init__(self, *args, **kwargs):
12
+ super(ReinhardMatcher, self).__init__(*args, **kwargs)
13
+
14
+ def reinhard(self, src: np.ndarray = None, ref: np.ndarray = None) -> np.ndarray:
15
+ """
16
+
17
+ This function conducts color matching based on the principles proposed by Reinhard et al.
18
+ The paper of the original work can be found at https://www.cs.tau.ac.il/~turkel/imagepapers/ColorTransfer.pdf
19
+
20
+ :param src: Source image that requires transfer
21
+ :param ref: Palette image which serves as reference
22
+ :param res: Resulting image after the mapping
23
+
24
+ :type src: :class:`~numpy:numpy.ndarray`
25
+ :type ref: :class:`~numpy:numpy.ndarray`
26
+ :type res: :class:`~numpy:numpy.ndarray`
27
+
28
+ :return: **res**
29
+ :rtype: np.ndarray
30
+
31
+ """
32
+
33
+ # override source and reference image with arguments (if provided)
34
+ self._src = src if src is not None else self._src
35
+ self._ref = ref if ref is not None else self._ref
36
+
37
+ # get image dimensions after validating that 3 color channels are present
38
+ m, n, p = self._src.shape if self.validate_color_chs() else self._src.shape + (1,)
39
+
40
+ # flatten images along spatial dimensions
41
+ src = self._src.reshape((-1, p)).transpose()
42
+ ref = self._ref.reshape((-1, p)).transpose()
43
+
44
+ # replace zeros with small value for numerical stability
45
+ src[src == 0] = 1/(2**8-1)
46
+ ref[ref == 0] = 1/(2**8-1)
47
+
48
+ # convert to LMS color space
49
+ lms_src = np.dot(LMS_MAT, src)
50
+ lms_ref = np.dot(LMS_MAT, ref)
51
+
52
+ # convert data to logarithmic LMS color space to eliminate skew
53
+ lms_src = np.log10(lms_src)
54
+ lms_ref = np.log10(lms_ref)
55
+
56
+ # PCA transform matrices according to Rudermann et al.
57
+ b = np.array([[1/np.sqrt(3), 0, 0], [0, 1/np.sqrt(6), 0], [0, 0, 1/np.sqrt(2)]])
58
+ c = np.array([[1, 1, 1], [1, 1, -2], [1, -1, 0]])
59
+
60
+ # convert to Lab space
61
+ lab_src = np.dot(np.dot(b, c), lms_src)
62
+ lab_ref = np.dot(np.dot(b, c), lms_ref)
63
+
64
+ # compute statistical measures
65
+ mean_src, std_src = np.mean(lab_src, axis=1), np.std(lab_src, axis=1)
66
+ mean_ref, std_ref = np.mean(lab_ref, axis=1), np.std(lab_ref, axis=1)
67
+
68
+ # compute ratios of standard deviations channel-wise
69
+ std_ratios = std_ref / std_src
70
+
71
+ # apply statistical alignment channel-wise
72
+ res_lab = ((lab_src.T - mean_src) * std_ratios + mean_ref).T
73
+
74
+ # convert back to LMS
75
+ lms_res = np.dot(np.dot(c.T, b), res_lab)
76
+ lms_res = 10**lms_res
77
+
78
+ # convert back to RGB
79
+ res = np.dot(LMS_MAT_INV, lms_res).transpose()
80
+
81
+ # reshape to 2-D image
82
+ res = res.reshape((m, n, p))
83
+
84
+ return res
python_embeded/Lib/site-packages/color_matcher/top_level.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ __author__ = "Christopher Hahne"
4
+ __email__ = "info@christopherhahne.de"
5
+ __license__ = """
6
+ Copyright (c) 2020 Christopher Hahne <info@christopherhahne.de>
7
+
8
+ This program is free software: you can redistribute it and/or modify
9
+ it under the terms of the GNU General Public License as published by
10
+ the Free Software Foundation, either version 3 of the License, or
11
+ (at your option) any later version.
12
+
13
+ This program is distributed in the hope that it will be useful,
14
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16
+ GNU General Public License for more details.
17
+
18
+ You should have received a copy of the GNU General Public License
19
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
20
+
21
+ """
22
+
23
+ from color_matcher.hist_matcher import HistogramMatcher
24
+ from color_matcher.mvgd_matcher import TransferMVGD
25
+ from color_matcher.reinhard_matcher import ReinhardMatcher
26
+ import numpy as np
27
+
28
+ METHODS = ('default', 'hm', 'reinhard', 'mvgd', 'mkl', 'hm-mvgd-hm', 'hm-mkl-hm')
29
+
30
+
31
+ class ColorMatcher(HistogramMatcher, ReinhardMatcher, TransferMVGD):
32
+
33
+ def __init__(self, *args, **kwargs):
34
+ super(ColorMatcher, self).__init__(*args, **kwargs)
35
+
36
+ self._method = kwargs['method'] if 'method' in kwargs else 'default'
37
+ self._funs = []
38
+
39
+ def main(self) -> np.ndarray:
40
+ """
41
+ The main function is the high-level entry point performing the mapping based on instantiation arguments.
42
+
43
+ :return: Resulting image after color mapping
44
+ :rtype: np.ndarray
45
+ """
46
+
47
+ self.transfer()
48
+
49
+ return self._src
50
+
51
+ def transfer(self, src: np.ndarray = None, ref: np.ndarray = None, method: str = None) -> np.ndarray:
52
+ """
53
+
54
+ Transfer function to map colors based on provided transfer method.
55
+
56
+ :param src: Source image that requires transfer
57
+ :param ref: Palette image which serves as reference
58
+ :param method: ('default', 'hm', 'reinhard', 'mvgd', 'mkl', 'hm-mvgd-hm', 'hm-mkl-hm') determining color mapping
59
+
60
+ :type src: :class:`~numpy:numpy.ndarray`
61
+ :type ref: :class:`~numpy:numpy.ndarray`
62
+ :type method: :class:`str`
63
+
64
+ :return: Resulting image after color mapping
65
+ :rtype: np.ndarray
66
+
67
+ """
68
+
69
+ # assign input arguments to variables (if provided)
70
+ self._method = self._method.lower() if method is None else method.lower()
71
+ self._src = src if src is not None else self._src
72
+ self._ref = ref if ref is not None else self._ref
73
+
74
+ # color transfer methods (to be iterated through)
75
+ if self._method == METHODS[0]:
76
+ self._funs = [self.multivar_transfer]
77
+ elif self._method == METHODS[1]:
78
+ self._funs = [self.hist_match]
79
+ elif self._method == METHODS[2]:
80
+ self._funs = [self.reinhard]
81
+ elif self._method in METHODS[3:5]:
82
+ self._funs = [self.multivar_transfer]
83
+ elif self._method in METHODS[5:]:
84
+ self._funs = [self.hist_match, self.multivar_transfer, self.hist_match]
85
+ else:
86
+ raise BaseException('Method type \'%s\' not recognized' % method)
87
+
88
+ # check if three color channels are provided
89
+ self.validate_img_dims()
90
+
91
+ # check provided color channels
92
+ self.validate_color_chs()
93
+
94
+ # proceed with the color match
95
+ for fun in self._funs:
96
+ self._src = fun(self._src, self._ref)
97
+
98
+ return self._src
python_embeded/Lib/site-packages/colorama-0.4.6.dist-info/METADATA ADDED
@@ -0,0 +1,441 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.1
2
+ Name: colorama
3
+ Version: 0.4.6
4
+ Summary: Cross-platform colored terminal text.
5
+ Project-URL: Homepage, https://github.com/tartley/colorama
6
+ Author-email: Jonathan Hartley <tartley@tartley.com>
7
+ License-File: LICENSE.txt
8
+ Keywords: ansi,color,colour,crossplatform,terminal,text,windows,xplatform
9
+ Classifier: Development Status :: 5 - Production/Stable
10
+ Classifier: Environment :: Console
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: BSD License
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python
15
+ Classifier: Programming Language :: Python :: 2
16
+ Classifier: Programming Language :: Python :: 2.7
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.7
19
+ Classifier: Programming Language :: Python :: 3.8
20
+ Classifier: Programming Language :: Python :: 3.9
21
+ Classifier: Programming Language :: Python :: 3.10
22
+ Classifier: Programming Language :: Python :: Implementation :: CPython
23
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
24
+ Classifier: Topic :: Terminals
25
+ Requires-Python: !=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*,>=2.7
26
+ Description-Content-Type: text/x-rst
27
+
28
+ .. image:: https://img.shields.io/pypi/v/colorama.svg
29
+ :target: https://pypi.org/project/colorama/
30
+ :alt: Latest Version
31
+
32
+ .. image:: https://img.shields.io/pypi/pyversions/colorama.svg
33
+ :target: https://pypi.org/project/colorama/
34
+ :alt: Supported Python versions
35
+
36
+ .. image:: https://github.com/tartley/colorama/actions/workflows/test.yml/badge.svg
37
+ :target: https://github.com/tartley/colorama/actions/workflows/test.yml
38
+ :alt: Build Status
39
+
40
+ Colorama
41
+ ========
42
+
43
+ Makes ANSI escape character sequences (for producing colored terminal text and
44
+ cursor positioning) work under MS Windows.
45
+
46
+ .. |donate| image:: https://www.paypalobjects.com/en_US/i/btn/btn_donate_SM.gif
47
+ :target: https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=2MZ9D2GMLYCUJ&item_name=Colorama&currency_code=USD
48
+ :alt: Donate with Paypal
49
+
50
+ `PyPI for releases <https://pypi.org/project/colorama/>`_ |
51
+ `Github for source <https://github.com/tartley/colorama>`_ |
52
+ `Colorama for enterprise on Tidelift <https://github.com/tartley/colorama/blob/master/ENTERPRISE.md>`_
53
+
54
+ If you find Colorama useful, please |donate| to the authors. Thank you!
55
+
56
+ Installation
57
+ ------------
58
+
59
+ Tested on CPython 2.7, 3.7, 3.8, 3.9 and 3.10 and Pypy 2.7 and 3.8.
60
+
61
+ No requirements other than the standard library.
62
+
63
+ .. code-block:: bash
64
+
65
+ pip install colorama
66
+ # or
67
+ conda install -c anaconda colorama
68
+
69
+ Description
70
+ -----------
71
+
72
+ ANSI escape character sequences have long been used to produce colored terminal
73
+ text and cursor positioning on Unix and Macs. Colorama makes this work on
74
+ Windows, too, by wrapping ``stdout``, stripping ANSI sequences it finds (which
75
+ would appear as gobbledygook in the output), and converting them into the
76
+ appropriate win32 calls to modify the state of the terminal. On other platforms,
77
+ Colorama does nothing.
78
+
79
+ This has the upshot of providing a simple cross-platform API for printing
80
+ colored terminal text from Python, and has the happy side-effect that existing
81
+ applications or libraries which use ANSI sequences to produce colored output on
82
+ Linux or Macs can now also work on Windows, simply by calling
83
+ ``colorama.just_fix_windows_console()`` (since v0.4.6) or ``colorama.init()``
84
+ (all versions, but may have other side-effects – see below).
85
+
86
+ An alternative approach is to install ``ansi.sys`` on Windows machines, which
87
+ provides the same behaviour for all applications running in terminals. Colorama
88
+ is intended for situations where that isn't easy (e.g., maybe your app doesn't
89
+ have an installer.)
90
+
91
+ Demo scripts in the source code repository print some colored text using
92
+ ANSI sequences. Compare their output under Gnome-terminal's built in ANSI
93
+ handling, versus on Windows Command-Prompt using Colorama:
94
+
95
+ .. image:: https://github.com/tartley/colorama/raw/master/screenshots/ubuntu-demo.png
96
+ :width: 661
97
+ :height: 357
98
+ :alt: ANSI sequences on Ubuntu under gnome-terminal.
99
+
100
+ .. image:: https://github.com/tartley/colorama/raw/master/screenshots/windows-demo.png
101
+ :width: 668
102
+ :height: 325
103
+ :alt: Same ANSI sequences on Windows, using Colorama.
104
+
105
+ These screenshots show that, on Windows, Colorama does not support ANSI 'dim
106
+ text'; it looks the same as 'normal text'.
107
+
108
+ Usage
109
+ -----
110
+
111
+ Initialisation
112
+ ..............
113
+
114
+ If the only thing you want from Colorama is to get ANSI escapes to work on
115
+ Windows, then run:
116
+
117
+ .. code-block:: python
118
+
119
+ from colorama import just_fix_windows_console
120
+ just_fix_windows_console()
121
+
122
+ If you're on a recent version of Windows 10 or better, and your stdout/stderr
123
+ are pointing to a Windows console, then this will flip the magic configuration
124
+ switch to enable Windows' built-in ANSI support.
125
+
126
+ If you're on an older version of Windows, and your stdout/stderr are pointing to
127
+ a Windows console, then this will wrap ``sys.stdout`` and/or ``sys.stderr`` in a
128
+ magic file object that intercepts ANSI escape sequences and issues the
129
+ appropriate Win32 calls to emulate them.
130
+
131
+ In all other circumstances, it does nothing whatsoever. Basically the idea is
132
+ that this makes Windows act like Unix with respect to ANSI escape handling.
133
+
134
+ It's safe to call this function multiple times. It's safe to call this function
135
+ on non-Windows platforms, but it won't do anything. It's safe to call this
136
+ function when one or both of your stdout/stderr are redirected to a file – it
137
+ won't do anything to those streams.
138
+
139
+ Alternatively, you can use the older interface with more features (but also more
140
+ potential footguns):
141
+
142
+ .. code-block:: python
143
+
144
+ from colorama import init
145
+ init()
146
+
147
+ This does the same thing as ``just_fix_windows_console``, except for the
148
+ following differences:
149
+
150
+ - It's not safe to call ``init`` multiple times; you can end up with multiple
151
+ layers of wrapping and broken ANSI support.
152
+
153
+ - Colorama will apply a heuristic to guess whether stdout/stderr support ANSI,
154
+ and if it thinks they don't, then it will wrap ``sys.stdout`` and
155
+ ``sys.stderr`` in a magic file object that strips out ANSI escape sequences
156
+ before printing them. This happens on all platforms, and can be convenient if
157
+ you want to write your code to emit ANSI escape sequences unconditionally, and
158
+ let Colorama decide whether they should actually be output. But note that
159
+ Colorama's heuristic is not particularly clever.
160
+
161
+ - ``init`` also accepts explicit keyword args to enable/disable various
162
+ functionality – see below.
163
+
164
+ To stop using Colorama before your program exits, simply call ``deinit()``.
165
+ This will restore ``stdout`` and ``stderr`` to their original values, so that
166
+ Colorama is disabled. To resume using Colorama again, call ``reinit()``; it is
167
+ cheaper than calling ``init()`` again (but does the same thing).
168
+
169
+ Most users should depend on ``colorama >= 0.4.6``, and use
170
+ ``just_fix_windows_console``. The old ``init`` interface will be supported
171
+ indefinitely for backwards compatibility, but we don't plan to fix any issues
172
+ with it, also for backwards compatibility.
173
+
174
+ Colored Output
175
+ ..............
176
+
177
+ Cross-platform printing of colored text can then be done using Colorama's
178
+ constant shorthand for ANSI escape sequences. These are deliberately
179
+ rudimentary, see below.
180
+
181
+ .. code-block:: python
182
+
183
+ from colorama import Fore, Back, Style
184
+ print(Fore.RED + 'some red text')
185
+ print(Back.GREEN + 'and with a green background')
186
+ print(Style.DIM + 'and in dim text')
187
+ print(Style.RESET_ALL)
188
+ print('back to normal now')
189
+
190
+ ...or simply by manually printing ANSI sequences from your own code:
191
+
192
+ .. code-block:: python
193
+
194
+ print('\033[31m' + 'some red text')
195
+ print('\033[39m') # and reset to default color
196
+
197
+ ...or, Colorama can be used in conjunction with existing ANSI libraries
198
+ such as the venerable `Termcolor <https://pypi.org/project/termcolor/>`_
199
+ the fabulous `Blessings <https://pypi.org/project/blessings/>`_,
200
+ or the incredible `_Rich <https://pypi.org/project/rich/>`_.
201
+
202
+ If you wish Colorama's Fore, Back and Style constants were more capable,
203
+ then consider using one of the above highly capable libraries to generate
204
+ colors, etc, and use Colorama just for its primary purpose: to convert
205
+ those ANSI sequences to also work on Windows:
206
+
207
+ SIMILARLY, do not send PRs adding the generation of new ANSI types to Colorama.
208
+ We are only interested in converting ANSI codes to win32 API calls, not
209
+ shortcuts like the above to generate ANSI characters.
210
+
211
+ .. code-block:: python
212
+
213
+ from colorama import just_fix_windows_console
214
+ from termcolor import colored
215
+
216
+ # use Colorama to make Termcolor work on Windows too
217
+ just_fix_windows_console()
218
+
219
+ # then use Termcolor for all colored text output
220
+ print(colored('Hello, World!', 'green', 'on_red'))
221
+
222
+ Available formatting constants are::
223
+
224
+ Fore: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET.
225
+ Back: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET.
226
+ Style: DIM, NORMAL, BRIGHT, RESET_ALL
227
+
228
+ ``Style.RESET_ALL`` resets foreground, background, and brightness. Colorama will
229
+ perform this reset automatically on program exit.
230
+
231
+ These are fairly well supported, but not part of the standard::
232
+
233
+ Fore: LIGHTBLACK_EX, LIGHTRED_EX, LIGHTGREEN_EX, LIGHTYELLOW_EX, LIGHTBLUE_EX, LIGHTMAGENTA_EX, LIGHTCYAN_EX, LIGHTWHITE_EX
234
+ Back: LIGHTBLACK_EX, LIGHTRED_EX, LIGHTGREEN_EX, LIGHTYELLOW_EX, LIGHTBLUE_EX, LIGHTMAGENTA_EX, LIGHTCYAN_EX, LIGHTWHITE_EX
235
+
236
+ Cursor Positioning
237
+ ..................
238
+
239
+ ANSI codes to reposition the cursor are supported. See ``demos/demo06.py`` for
240
+ an example of how to generate them.
241
+
242
+ Init Keyword Args
243
+ .................
244
+
245
+ ``init()`` accepts some ``**kwargs`` to override default behaviour.
246
+
247
+ init(autoreset=False):
248
+ If you find yourself repeatedly sending reset sequences to turn off color
249
+ changes at the end of every print, then ``init(autoreset=True)`` will
250
+ automate that:
251
+
252
+ .. code-block:: python
253
+
254
+ from colorama import init
255
+ init(autoreset=True)
256
+ print(Fore.RED + 'some red text')
257
+ print('automatically back to default color again')
258
+
259
+ init(strip=None):
260
+ Pass ``True`` or ``False`` to override whether ANSI codes should be
261
+ stripped from the output. The default behaviour is to strip if on Windows
262
+ or if output is redirected (not a tty).
263
+
264
+ init(convert=None):
265
+ Pass ``True`` or ``False`` to override whether to convert ANSI codes in the
266
+ output into win32 calls. The default behaviour is to convert if on Windows
267
+ and output is to a tty (terminal).
268
+
269
+ init(wrap=True):
270
+ On Windows, Colorama works by replacing ``sys.stdout`` and ``sys.stderr``
271
+ with proxy objects, which override the ``.write()`` method to do their work.
272
+ If this wrapping causes you problems, then this can be disabled by passing
273
+ ``init(wrap=False)``. The default behaviour is to wrap if ``autoreset`` or
274
+ ``strip`` or ``convert`` are True.
275
+
276
+ When wrapping is disabled, colored printing on non-Windows platforms will
277
+ continue to work as normal. To do cross-platform colored output, you can
278
+ use Colorama's ``AnsiToWin32`` proxy directly:
279
+
280
+ .. code-block:: python
281
+
282
+ import sys
283
+ from colorama import init, AnsiToWin32
284
+ init(wrap=False)
285
+ stream = AnsiToWin32(sys.stderr).stream
286
+
287
+ # Python 2
288
+ print >>stream, Fore.BLUE + 'blue text on stderr'
289
+
290
+ # Python 3
291
+ print(Fore.BLUE + 'blue text on stderr', file=stream)
292
+
293
+ Recognised ANSI Sequences
294
+ .........................
295
+
296
+ ANSI sequences generally take the form::
297
+
298
+ ESC [ <param> ; <param> ... <command>
299
+
300
+ Where ``<param>`` is an integer, and ``<command>`` is a single letter. Zero or
301
+ more params are passed to a ``<command>``. If no params are passed, it is
302
+ generally synonymous with passing a single zero. No spaces exist in the
303
+ sequence; they have been inserted here simply to read more easily.
304
+
305
+ The only ANSI sequences that Colorama converts into win32 calls are::
306
+
307
+ ESC [ 0 m # reset all (colors and brightness)
308
+ ESC [ 1 m # bright
309
+ ESC [ 2 m # dim (looks same as normal brightness)
310
+ ESC [ 22 m # normal brightness
311
+
312
+ # FOREGROUND:
313
+ ESC [ 30 m # black
314
+ ESC [ 31 m # red
315
+ ESC [ 32 m # green
316
+ ESC [ 33 m # yellow
317
+ ESC [ 34 m # blue
318
+ ESC [ 35 m # magenta
319
+ ESC [ 36 m # cyan
320
+ ESC [ 37 m # white
321
+ ESC [ 39 m # reset
322
+
323
+ # BACKGROUND
324
+ ESC [ 40 m # black
325
+ ESC [ 41 m # red
326
+ ESC [ 42 m # green
327
+ ESC [ 43 m # yellow
328
+ ESC [ 44 m # blue
329
+ ESC [ 45 m # magenta
330
+ ESC [ 46 m # cyan
331
+ ESC [ 47 m # white
332
+ ESC [ 49 m # reset
333
+
334
+ # cursor positioning
335
+ ESC [ y;x H # position cursor at x across, y down
336
+ ESC [ y;x f # position cursor at x across, y down
337
+ ESC [ n A # move cursor n lines up
338
+ ESC [ n B # move cursor n lines down
339
+ ESC [ n C # move cursor n characters forward
340
+ ESC [ n D # move cursor n characters backward
341
+
342
+ # clear the screen
343
+ ESC [ mode J # clear the screen
344
+
345
+ # clear the line
346
+ ESC [ mode K # clear the line
347
+
348
+ Multiple numeric params to the ``'m'`` command can be combined into a single
349
+ sequence::
350
+
351
+ ESC [ 36 ; 45 ; 1 m # bright cyan text on magenta background
352
+
353
+ All other ANSI sequences of the form ``ESC [ <param> ; <param> ... <command>``
354
+ are silently stripped from the output on Windows.
355
+
356
+ Any other form of ANSI sequence, such as single-character codes or alternative
357
+ initial characters, are not recognised or stripped. It would be cool to add
358
+ them though. Let me know if it would be useful for you, via the Issues on
359
+ GitHub.
360
+
361
+ Status & Known Problems
362
+ -----------------------
363
+
364
+ I've personally only tested it on Windows XP (CMD, Console2), Ubuntu
365
+ (gnome-terminal, xterm), and OS X.
366
+
367
+ Some valid ANSI sequences aren't recognised.
368
+
369
+ If you're hacking on the code, see `README-hacking.md`_. ESPECIALLY, see the
370
+ explanation there of why we do not want PRs that allow Colorama to generate new
371
+ types of ANSI codes.
372
+
373
+ See outstanding issues and wish-list:
374
+ https://github.com/tartley/colorama/issues
375
+
376
+ If anything doesn't work for you, or doesn't do what you expected or hoped for,
377
+ I'd love to hear about it on that issues list, would be delighted by patches,
378
+ and would be happy to grant commit access to anyone who submits a working patch
379
+ or two.
380
+
381
+ .. _README-hacking.md: README-hacking.md
382
+
383
+ License
384
+ -------
385
+
386
+ Copyright Jonathan Hartley & Arnon Yaari, 2013-2020. BSD 3-Clause license; see
387
+ LICENSE file.
388
+
389
+ Professional support
390
+ --------------------
391
+
392
+ .. |tideliftlogo| image:: https://cdn2.hubspot.net/hubfs/4008838/website/logos/logos_for_download/Tidelift_primary-shorthand-logo.png
393
+ :alt: Tidelift
394
+ :target: https://tidelift.com/subscription/pkg/pypi-colorama?utm_source=pypi-colorama&utm_medium=referral&utm_campaign=readme
395
+
396
+ .. list-table::
397
+ :widths: 10 100
398
+
399
+ * - |tideliftlogo|
400
+ - Professional support for colorama is available as part of the
401
+ `Tidelift Subscription`_.
402
+ Tidelift gives software development teams a single source for purchasing
403
+ and maintaining their software, with professional grade assurances from
404
+ the experts who know it best, while seamlessly integrating with existing
405
+ tools.
406
+
407
+ .. _Tidelift Subscription: https://tidelift.com/subscription/pkg/pypi-colorama?utm_source=pypi-colorama&utm_medium=referral&utm_campaign=readme
408
+
409
+ Thanks
410
+ ------
411
+
412
+ See the CHANGELOG for more thanks!
413
+
414
+ * Marc Schlaich (schlamar) for a ``setup.py`` fix for Python2.5.
415
+ * Marc Abramowitz, reported & fixed a crash on exit with closed ``stdout``,
416
+ providing a solution to issue #7's setuptools/distutils debate,
417
+ and other fixes.
418
+ * User 'eryksun', for guidance on correctly instantiating ``ctypes.windll``.
419
+ * Matthew McCormick for politely pointing out a longstanding crash on non-Win.
420
+ * Ben Hoyt, for a magnificent fix under 64-bit Windows.
421
+ * Jesse at Empty Square for submitting a fix for examples in the README.
422
+ * User 'jamessp', an observant documentation fix for cursor positioning.
423
+ * User 'vaal1239', Dave Mckee & Lackner Kristof for a tiny but much-needed Win7
424
+ fix.
425
+ * Julien Stuyck, for wisely suggesting Python3 compatible updates to README.
426
+ * Daniel Griffith for multiple fabulous patches.
427
+ * Oscar Lesta for a valuable fix to stop ANSI chars being sent to non-tty
428
+ output.
429
+ * Roger Binns, for many suggestions, valuable feedback, & bug reports.
430
+ * Tim Golden for thought and much appreciated feedback on the initial idea.
431
+ * User 'Zearin' for updates to the README file.
432
+ * John Szakmeister for adding support for light colors
433
+ * Charles Merriam for adding documentation to demos
434
+ * Jurko for a fix on 64-bit Windows CPython2.5 w/o ctypes
435
+ * Florian Bruhin for a fix when stdout or stderr are None
436
+ * Thomas Weininger for fixing ValueError on Windows
437
+ * Remi Rampin for better Github integration and fixes to the README file
438
+ * Simeon Visser for closing a file handle using 'with' and updating classifiers
439
+ to include Python 3.3 and 3.4
440
+ * Andy Neff for fixing RESET of LIGHT_EX colors.
441
+ * Jonathan Hartley for the initial idea and implementation.
python_embeded/Lib/site-packages/colorama-0.4.6.dist-info/RECORD ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ colorama-0.4.6.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ colorama-0.4.6.dist-info/METADATA,sha256=e67SnrUMOym9sz_4TjF3vxvAV4T3aF7NyqRHHH3YEMw,17158
3
+ colorama-0.4.6.dist-info/RECORD,,
4
+ colorama-0.4.6.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ colorama-0.4.6.dist-info/WHEEL,sha256=cdcF4Fbd0FPtw2EMIOwH-3rSOTUdTCeOSXRMD1iLUb8,105
6
+ colorama-0.4.6.dist-info/direct_url.json,sha256=VZjQx-E-Db2UzSXVfM9xE7dRsKQmFiU6JaiCGOsB3kU,276
7
+ colorama-0.4.6.dist-info/licenses/LICENSE.txt,sha256=ysNcAmhuXQSlpxQL-zs25zrtSWZW6JEQLkKIhteTAxg,1491
8
+ colorama/__init__.py,sha256=wePQA4U20tKgYARySLEC047ucNX-g8pRLpYBuiHlLb8,266
9
+ colorama/__pycache__/__init__.cpython-312.pyc,,
10
+ colorama/__pycache__/ansi.cpython-312.pyc,,
11
+ colorama/__pycache__/ansitowin32.cpython-312.pyc,,
12
+ colorama/__pycache__/initialise.cpython-312.pyc,,
13
+ colorama/__pycache__/win32.cpython-312.pyc,,
14
+ colorama/__pycache__/winterm.cpython-312.pyc,,
15
+ colorama/ansi.py,sha256=Top4EeEuaQdBWdteKMEcGOTeKeF19Q-Wo_6_Cj5kOzQ,2522
16
+ colorama/ansitowin32.py,sha256=vPNYa3OZbxjbuFyaVo0Tmhmy1FZ1lKMWCnT7odXpItk,11128
17
+ colorama/initialise.py,sha256=-hIny86ClXo39ixh5iSCfUIa2f_h_bgKRDW7gqs-KLU,3325
18
+ colorama/tests/__init__.py,sha256=MkgPAEzGQd-Rq0w0PZXSX2LadRWhUECcisJY8lSrm4Q,75
19
+ colorama/tests/__pycache__/__init__.cpython-312.pyc,,
20
+ colorama/tests/__pycache__/ansi_test.cpython-312.pyc,,
21
+ colorama/tests/__pycache__/ansitowin32_test.cpython-312.pyc,,
22
+ colorama/tests/__pycache__/initialise_test.cpython-312.pyc,,
23
+ colorama/tests/__pycache__/isatty_test.cpython-312.pyc,,
24
+ colorama/tests/__pycache__/utils.cpython-312.pyc,,
25
+ colorama/tests/__pycache__/winterm_test.cpython-312.pyc,,
26
+ colorama/tests/ansi_test.py,sha256=FeViDrUINIZcr505PAxvU4AjXz1asEiALs9GXMhwRaE,2839
27
+ colorama/tests/ansitowin32_test.py,sha256=RN7AIhMJ5EqDsYaCjVo-o4u8JzDD4ukJbmevWKS70rY,10678
28
+ colorama/tests/initialise_test.py,sha256=BbPy-XfyHwJ6zKozuQOvNvQZzsx9vdb_0bYXn7hsBTc,6741
29
+ colorama/tests/isatty_test.py,sha256=Pg26LRpv0yQDB5Ac-sxgVXG7hsA1NYvapFgApZfYzZg,1866
30
+ colorama/tests/utils.py,sha256=1IIRylG39z5-dzq09R_ngufxyPZxgldNbrxKxUGwGKE,1079
31
+ colorama/tests/winterm_test.py,sha256=qoWFPEjym5gm2RuMwpf3pOis3a5r_PJZFCzK254JL8A,3709
32
+ colorama/win32.py,sha256=YQOKwMTwtGBbsY4dL5HYTvwTeP9wIQra5MvPNddpxZs,6181
33
+ colorama/winterm.py,sha256=XCQFDHjPi6AHYNdZwy0tA02H-Jh48Jp-HvCjeLeLp3U,7134
python_embeded/Lib/site-packages/colorama-0.4.6.dist-info/REQUESTED ADDED
File without changes
python_embeded/Lib/site-packages/colorama-0.4.6.dist-info/WHEEL ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.11.1
3
+ Root-Is-Purelib: true
4
+ Tag: py2-none-any
5
+ Tag: py3-none-any
python_embeded/Lib/site-packages/colorama/ansi.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
2
+ '''
3
+ This module generates ANSI character codes to printing colors to terminals.
4
+ See: http://en.wikipedia.org/wiki/ANSI_escape_code
5
+ '''
6
+
7
+ CSI = '\033['
8
+ OSC = '\033]'
9
+ BEL = '\a'
10
+
11
+
12
+ def code_to_chars(code):
13
+ return CSI + str(code) + 'm'
14
+
15
+ def set_title(title):
16
+ return OSC + '2;' + title + BEL
17
+
18
+ def clear_screen(mode=2):
19
+ return CSI + str(mode) + 'J'
20
+
21
+ def clear_line(mode=2):
22
+ return CSI + str(mode) + 'K'
23
+
24
+
25
+ class AnsiCodes(object):
26
+ def __init__(self):
27
+ # the subclasses declare class attributes which are numbers.
28
+ # Upon instantiation we define instance attributes, which are the same
29
+ # as the class attributes but wrapped with the ANSI escape sequence
30
+ for name in dir(self):
31
+ if not name.startswith('_'):
32
+ value = getattr(self, name)
33
+ setattr(self, name, code_to_chars(value))
34
+
35
+
36
+ class AnsiCursor(object):
37
+ def UP(self, n=1):
38
+ return CSI + str(n) + 'A'
39
+ def DOWN(self, n=1):
40
+ return CSI + str(n) + 'B'
41
+ def FORWARD(self, n=1):
42
+ return CSI + str(n) + 'C'
43
+ def BACK(self, n=1):
44
+ return CSI + str(n) + 'D'
45
+ def POS(self, x=1, y=1):
46
+ return CSI + str(y) + ';' + str(x) + 'H'
47
+
48
+
49
+ class AnsiFore(AnsiCodes):
50
+ BLACK = 30
51
+ RED = 31
52
+ GREEN = 32
53
+ YELLOW = 33
54
+ BLUE = 34
55
+ MAGENTA = 35
56
+ CYAN = 36
57
+ WHITE = 37
58
+ RESET = 39
59
+
60
+ # These are fairly well supported, but not part of the standard.
61
+ LIGHTBLACK_EX = 90
62
+ LIGHTRED_EX = 91
63
+ LIGHTGREEN_EX = 92
64
+ LIGHTYELLOW_EX = 93
65
+ LIGHTBLUE_EX = 94
66
+ LIGHTMAGENTA_EX = 95
67
+ LIGHTCYAN_EX = 96
68
+ LIGHTWHITE_EX = 97
69
+
70
+
71
+ class AnsiBack(AnsiCodes):
72
+ BLACK = 40
73
+ RED = 41
74
+ GREEN = 42
75
+ YELLOW = 43
76
+ BLUE = 44
77
+ MAGENTA = 45
78
+ CYAN = 46
79
+ WHITE = 47
80
+ RESET = 49
81
+
82
+ # These are fairly well supported, but not part of the standard.
83
+ LIGHTBLACK_EX = 100
84
+ LIGHTRED_EX = 101
85
+ LIGHTGREEN_EX = 102
86
+ LIGHTYELLOW_EX = 103
87
+ LIGHTBLUE_EX = 104
88
+ LIGHTMAGENTA_EX = 105
89
+ LIGHTCYAN_EX = 106
90
+ LIGHTWHITE_EX = 107
91
+
92
+
93
+ class AnsiStyle(AnsiCodes):
94
+ BRIGHT = 1
95
+ DIM = 2
96
+ NORMAL = 22
97
+ RESET_ALL = 0
98
+
99
+ Fore = AnsiFore()
100
+ Back = AnsiBack()
101
+ Style = AnsiStyle()
102
+ Cursor = AnsiCursor()
python_embeded/Lib/site-packages/colorama/ansitowin32.py ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
2
+ import re
3
+ import sys
4
+ import os
5
+
6
+ from .ansi import AnsiFore, AnsiBack, AnsiStyle, Style, BEL
7
+ from .winterm import enable_vt_processing, WinTerm, WinColor, WinStyle
8
+ from .win32 import windll, winapi_test
9
+
10
+
11
+ winterm = None
12
+ if windll is not None:
13
+ winterm = WinTerm()
14
+
15
+
16
+ class StreamWrapper(object):
17
+ '''
18
+ Wraps a stream (such as stdout), acting as a transparent proxy for all
19
+ attribute access apart from method 'write()', which is delegated to our
20
+ Converter instance.
21
+ '''
22
+ def __init__(self, wrapped, converter):
23
+ # double-underscore everything to prevent clashes with names of
24
+ # attributes on the wrapped stream object.
25
+ self.__wrapped = wrapped
26
+ self.__convertor = converter
27
+
28
+ def __getattr__(self, name):
29
+ return getattr(self.__wrapped, name)
30
+
31
+ def __enter__(self, *args, **kwargs):
32
+ # special method lookup bypasses __getattr__/__getattribute__, see
33
+ # https://stackoverflow.com/questions/12632894/why-doesnt-getattr-work-with-exit
34
+ # thus, contextlib magic methods are not proxied via __getattr__
35
+ return self.__wrapped.__enter__(*args, **kwargs)
36
+
37
+ def __exit__(self, *args, **kwargs):
38
+ return self.__wrapped.__exit__(*args, **kwargs)
39
+
40
+ def __setstate__(self, state):
41
+ self.__dict__ = state
42
+
43
+ def __getstate__(self):
44
+ return self.__dict__
45
+
46
+ def write(self, text):
47
+ self.__convertor.write(text)
48
+
49
+ def isatty(self):
50
+ stream = self.__wrapped
51
+ if 'PYCHARM_HOSTED' in os.environ:
52
+ if stream is not None and (stream is sys.__stdout__ or stream is sys.__stderr__):
53
+ return True
54
+ try:
55
+ stream_isatty = stream.isatty
56
+ except AttributeError:
57
+ return False
58
+ else:
59
+ return stream_isatty()
60
+
61
+ @property
62
+ def closed(self):
63
+ stream = self.__wrapped
64
+ try:
65
+ return stream.closed
66
+ # AttributeError in the case that the stream doesn't support being closed
67
+ # ValueError for the case that the stream has already been detached when atexit runs
68
+ except (AttributeError, ValueError):
69
+ return True
70
+
71
+
72
+ class AnsiToWin32(object):
73
+ '''
74
+ Implements a 'write()' method which, on Windows, will strip ANSI character
75
+ sequences from the text, and if outputting to a tty, will convert them into
76
+ win32 function calls.
77
+ '''
78
+ ANSI_CSI_RE = re.compile('\001?\033\\[((?:\\d|;)*)([a-zA-Z])\002?') # Control Sequence Introducer
79
+ ANSI_OSC_RE = re.compile('\001?\033\\]([^\a]*)(\a)\002?') # Operating System Command
80
+
81
+ def __init__(self, wrapped, convert=None, strip=None, autoreset=False):
82
+ # The wrapped stream (normally sys.stdout or sys.stderr)
83
+ self.wrapped = wrapped
84
+
85
+ # should we reset colors to defaults after every .write()
86
+ self.autoreset = autoreset
87
+
88
+ # create the proxy wrapping our output stream
89
+ self.stream = StreamWrapper(wrapped, self)
90
+
91
+ on_windows = os.name == 'nt'
92
+ # We test if the WinAPI works, because even if we are on Windows
93
+ # we may be using a terminal that doesn't support the WinAPI
94
+ # (e.g. Cygwin Terminal). In this case it's up to the terminal
95
+ # to support the ANSI codes.
96
+ conversion_supported = on_windows and winapi_test()
97
+ try:
98
+ fd = wrapped.fileno()
99
+ except Exception:
100
+ fd = -1
101
+ system_has_native_ansi = not on_windows or enable_vt_processing(fd)
102
+ have_tty = not self.stream.closed and self.stream.isatty()
103
+ need_conversion = conversion_supported and not system_has_native_ansi
104
+
105
+ # should we strip ANSI sequences from our output?
106
+ if strip is None:
107
+ strip = need_conversion or not have_tty
108
+ self.strip = strip
109
+
110
+ # should we should convert ANSI sequences into win32 calls?
111
+ if convert is None:
112
+ convert = need_conversion and have_tty
113
+ self.convert = convert
114
+
115
+ # dict of ansi codes to win32 functions and parameters
116
+ self.win32_calls = self.get_win32_calls()
117
+
118
+ # are we wrapping stderr?
119
+ self.on_stderr = self.wrapped is sys.stderr
120
+
121
+ def should_wrap(self):
122
+ '''
123
+ True if this class is actually needed. If false, then the output
124
+ stream will not be affected, nor will win32 calls be issued, so
125
+ wrapping stdout is not actually required. This will generally be
126
+ False on non-Windows platforms, unless optional functionality like
127
+ autoreset has been requested using kwargs to init()
128
+ '''
129
+ return self.convert or self.strip or self.autoreset
130
+
131
+ def get_win32_calls(self):
132
+ if self.convert and winterm:
133
+ return {
134
+ AnsiStyle.RESET_ALL: (winterm.reset_all, ),
135
+ AnsiStyle.BRIGHT: (winterm.style, WinStyle.BRIGHT),
136
+ AnsiStyle.DIM: (winterm.style, WinStyle.NORMAL),
137
+ AnsiStyle.NORMAL: (winterm.style, WinStyle.NORMAL),
138
+ AnsiFore.BLACK: (winterm.fore, WinColor.BLACK),
139
+ AnsiFore.RED: (winterm.fore, WinColor.RED),
140
+ AnsiFore.GREEN: (winterm.fore, WinColor.GREEN),
141
+ AnsiFore.YELLOW: (winterm.fore, WinColor.YELLOW),
142
+ AnsiFore.BLUE: (winterm.fore, WinColor.BLUE),
143
+ AnsiFore.MAGENTA: (winterm.fore, WinColor.MAGENTA),
144
+ AnsiFore.CYAN: (winterm.fore, WinColor.CYAN),
145
+ AnsiFore.WHITE: (winterm.fore, WinColor.GREY),
146
+ AnsiFore.RESET: (winterm.fore, ),
147
+ AnsiFore.LIGHTBLACK_EX: (winterm.fore, WinColor.BLACK, True),
148
+ AnsiFore.LIGHTRED_EX: (winterm.fore, WinColor.RED, True),
149
+ AnsiFore.LIGHTGREEN_EX: (winterm.fore, WinColor.GREEN, True),
150
+ AnsiFore.LIGHTYELLOW_EX: (winterm.fore, WinColor.YELLOW, True),
151
+ AnsiFore.LIGHTBLUE_EX: (winterm.fore, WinColor.BLUE, True),
152
+ AnsiFore.LIGHTMAGENTA_EX: (winterm.fore, WinColor.MAGENTA, True),
153
+ AnsiFore.LIGHTCYAN_EX: (winterm.fore, WinColor.CYAN, True),
154
+ AnsiFore.LIGHTWHITE_EX: (winterm.fore, WinColor.GREY, True),
155
+ AnsiBack.BLACK: (winterm.back, WinColor.BLACK),
156
+ AnsiBack.RED: (winterm.back, WinColor.RED),
157
+ AnsiBack.GREEN: (winterm.back, WinColor.GREEN),
158
+ AnsiBack.YELLOW: (winterm.back, WinColor.YELLOW),
159
+ AnsiBack.BLUE: (winterm.back, WinColor.BLUE),
160
+ AnsiBack.MAGENTA: (winterm.back, WinColor.MAGENTA),
161
+ AnsiBack.CYAN: (winterm.back, WinColor.CYAN),
162
+ AnsiBack.WHITE: (winterm.back, WinColor.GREY),
163
+ AnsiBack.RESET: (winterm.back, ),
164
+ AnsiBack.LIGHTBLACK_EX: (winterm.back, WinColor.BLACK, True),
165
+ AnsiBack.LIGHTRED_EX: (winterm.back, WinColor.RED, True),
166
+ AnsiBack.LIGHTGREEN_EX: (winterm.back, WinColor.GREEN, True),
167
+ AnsiBack.LIGHTYELLOW_EX: (winterm.back, WinColor.YELLOW, True),
168
+ AnsiBack.LIGHTBLUE_EX: (winterm.back, WinColor.BLUE, True),
169
+ AnsiBack.LIGHTMAGENTA_EX: (winterm.back, WinColor.MAGENTA, True),
170
+ AnsiBack.LIGHTCYAN_EX: (winterm.back, WinColor.CYAN, True),
171
+ AnsiBack.LIGHTWHITE_EX: (winterm.back, WinColor.GREY, True),
172
+ }
173
+ return dict()
174
+
175
+ def write(self, text):
176
+ if self.strip or self.convert:
177
+ self.write_and_convert(text)
178
+ else:
179
+ self.wrapped.write(text)
180
+ self.wrapped.flush()
181
+ if self.autoreset:
182
+ self.reset_all()
183
+
184
+
185
+ def reset_all(self):
186
+ if self.convert:
187
+ self.call_win32('m', (0,))
188
+ elif not self.strip and not self.stream.closed:
189
+ self.wrapped.write(Style.RESET_ALL)
190
+
191
+
192
+ def write_and_convert(self, text):
193
+ '''
194
+ Write the given text to our wrapped stream, stripping any ANSI
195
+ sequences from the text, and optionally converting them into win32
196
+ calls.
197
+ '''
198
+ cursor = 0
199
+ text = self.convert_osc(text)
200
+ for match in self.ANSI_CSI_RE.finditer(text):
201
+ start, end = match.span()
202
+ self.write_plain_text(text, cursor, start)
203
+ self.convert_ansi(*match.groups())
204
+ cursor = end
205
+ self.write_plain_text(text, cursor, len(text))
206
+
207
+
208
+ def write_plain_text(self, text, start, end):
209
+ if start < end:
210
+ self.wrapped.write(text[start:end])
211
+ self.wrapped.flush()
212
+
213
+
214
+ def convert_ansi(self, paramstring, command):
215
+ if self.convert:
216
+ params = self.extract_params(command, paramstring)
217
+ self.call_win32(command, params)
218
+
219
+
220
+ def extract_params(self, command, paramstring):
221
+ if command in 'Hf':
222
+ params = tuple(int(p) if len(p) != 0 else 1 for p in paramstring.split(';'))
223
+ while len(params) < 2:
224
+ # defaults:
225
+ params = params + (1,)
226
+ else:
227
+ params = tuple(int(p) for p in paramstring.split(';') if len(p) != 0)
228
+ if len(params) == 0:
229
+ # defaults:
230
+ if command in 'JKm':
231
+ params = (0,)
232
+ elif command in 'ABCD':
233
+ params = (1,)
234
+
235
+ return params
236
+
237
+
238
+ def call_win32(self, command, params):
239
+ if command == 'm':
240
+ for param in params:
241
+ if param in self.win32_calls:
242
+ func_args = self.win32_calls[param]
243
+ func = func_args[0]
244
+ args = func_args[1:]
245
+ kwargs = dict(on_stderr=self.on_stderr)
246
+ func(*args, **kwargs)
247
+ elif command in 'J':
248
+ winterm.erase_screen(params[0], on_stderr=self.on_stderr)
249
+ elif command in 'K':
250
+ winterm.erase_line(params[0], on_stderr=self.on_stderr)
251
+ elif command in 'Hf': # cursor position - absolute
252
+ winterm.set_cursor_position(params, on_stderr=self.on_stderr)
253
+ elif command in 'ABCD': # cursor position - relative
254
+ n = params[0]
255
+ # A - up, B - down, C - forward, D - back
256
+ x, y = {'A': (0, -n), 'B': (0, n), 'C': (n, 0), 'D': (-n, 0)}[command]
257
+ winterm.cursor_adjust(x, y, on_stderr=self.on_stderr)
258
+
259
+
260
+ def convert_osc(self, text):
261
+ for match in self.ANSI_OSC_RE.finditer(text):
262
+ start, end = match.span()
263
+ text = text[:start] + text[end:]
264
+ paramstring, command = match.groups()
265
+ if command == BEL:
266
+ if paramstring.count(";") == 1:
267
+ params = paramstring.split(";")
268
+ # 0 - change title and icon (we will only change title)
269
+ # 1 - change icon (we don't support this)
270
+ # 2 - change title
271
+ if params[0] in '02':
272
+ winterm.set_title(params[1])
273
+ return text
274
+
275
+
276
+ def flush(self):
277
+ self.wrapped.flush()
python_embeded/Lib/site-packages/colorama/initialise.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
2
+ import atexit
3
+ import contextlib
4
+ import sys
5
+
6
+ from .ansitowin32 import AnsiToWin32
7
+
8
+
9
+ def _wipe_internal_state_for_tests():
10
+ global orig_stdout, orig_stderr
11
+ orig_stdout = None
12
+ orig_stderr = None
13
+
14
+ global wrapped_stdout, wrapped_stderr
15
+ wrapped_stdout = None
16
+ wrapped_stderr = None
17
+
18
+ global atexit_done
19
+ atexit_done = False
20
+
21
+ global fixed_windows_console
22
+ fixed_windows_console = False
23
+
24
+ try:
25
+ # no-op if it wasn't registered
26
+ atexit.unregister(reset_all)
27
+ except AttributeError:
28
+ # python 2: no atexit.unregister. Oh well, we did our best.
29
+ pass
30
+
31
+
32
+ def reset_all():
33
+ if AnsiToWin32 is not None: # Issue #74: objects might become None at exit
34
+ AnsiToWin32(orig_stdout).reset_all()
35
+
36
+
37
+ def init(autoreset=False, convert=None, strip=None, wrap=True):
38
+
39
+ if not wrap and any([autoreset, convert, strip]):
40
+ raise ValueError('wrap=False conflicts with any other arg=True')
41
+
42
+ global wrapped_stdout, wrapped_stderr
43
+ global orig_stdout, orig_stderr
44
+
45
+ orig_stdout = sys.stdout
46
+ orig_stderr = sys.stderr
47
+
48
+ if sys.stdout is None:
49
+ wrapped_stdout = None
50
+ else:
51
+ sys.stdout = wrapped_stdout = \
52
+ wrap_stream(orig_stdout, convert, strip, autoreset, wrap)
53
+ if sys.stderr is None:
54
+ wrapped_stderr = None
55
+ else:
56
+ sys.stderr = wrapped_stderr = \
57
+ wrap_stream(orig_stderr, convert, strip, autoreset, wrap)
58
+
59
+ global atexit_done
60
+ if not atexit_done:
61
+ atexit.register(reset_all)
62
+ atexit_done = True
63
+
64
+
65
+ def deinit():
66
+ if orig_stdout is not None:
67
+ sys.stdout = orig_stdout
68
+ if orig_stderr is not None:
69
+ sys.stderr = orig_stderr
70
+
71
+
72
+ def just_fix_windows_console():
73
+ global fixed_windows_console
74
+
75
+ if sys.platform != "win32":
76
+ return
77
+ if fixed_windows_console:
78
+ return
79
+ if wrapped_stdout is not None or wrapped_stderr is not None:
80
+ # Someone already ran init() and it did stuff, so we won't second-guess them
81
+ return
82
+
83
+ # On newer versions of Windows, AnsiToWin32.__init__ will implicitly enable the
84
+ # native ANSI support in the console as a side-effect. We only need to actually
85
+ # replace sys.stdout/stderr if we're in the old-style conversion mode.
86
+ new_stdout = AnsiToWin32(sys.stdout, convert=None, strip=None, autoreset=False)
87
+ if new_stdout.convert:
88
+ sys.stdout = new_stdout
89
+ new_stderr = AnsiToWin32(sys.stderr, convert=None, strip=None, autoreset=False)
90
+ if new_stderr.convert:
91
+ sys.stderr = new_stderr
92
+
93
+ fixed_windows_console = True
94
+
95
+ @contextlib.contextmanager
96
+ def colorama_text(*args, **kwargs):
97
+ init(*args, **kwargs)
98
+ try:
99
+ yield
100
+ finally:
101
+ deinit()
102
+
103
+
104
+ def reinit():
105
+ if wrapped_stdout is not None:
106
+ sys.stdout = wrapped_stdout
107
+ if wrapped_stderr is not None:
108
+ sys.stderr = wrapped_stderr
109
+
110
+
111
+ def wrap_stream(stream, convert, strip, autoreset, wrap):
112
+ if wrap:
113
+ wrapper = AnsiToWin32(stream,
114
+ convert=convert, strip=strip, autoreset=autoreset)
115
+ if wrapper.should_wrap():
116
+ stream = wrapper.stream
117
+ return stream
118
+
119
+
120
+ # Use this for initial setup as well, to reduce code duplication
121
+ _wipe_internal_state_for_tests()
python_embeded/Lib/site-packages/colorama/winterm.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
2
+ try:
3
+ from msvcrt import get_osfhandle
4
+ except ImportError:
5
+ def get_osfhandle(_):
6
+ raise OSError("This isn't windows!")
7
+
8
+
9
+ from . import win32
10
+
11
+ # from wincon.h
12
+ class WinColor(object):
13
+ BLACK = 0
14
+ BLUE = 1
15
+ GREEN = 2
16
+ CYAN = 3
17
+ RED = 4
18
+ MAGENTA = 5
19
+ YELLOW = 6
20
+ GREY = 7
21
+
22
+ # from wincon.h
23
+ class WinStyle(object):
24
+ NORMAL = 0x00 # dim text, dim background
25
+ BRIGHT = 0x08 # bright text, dim background
26
+ BRIGHT_BACKGROUND = 0x80 # dim text, bright background
27
+
28
+ class WinTerm(object):
29
+
30
+ def __init__(self):
31
+ self._default = win32.GetConsoleScreenBufferInfo(win32.STDOUT).wAttributes
32
+ self.set_attrs(self._default)
33
+ self._default_fore = self._fore
34
+ self._default_back = self._back
35
+ self._default_style = self._style
36
+ # In order to emulate LIGHT_EX in windows, we borrow the BRIGHT style.
37
+ # So that LIGHT_EX colors and BRIGHT style do not clobber each other,
38
+ # we track them separately, since LIGHT_EX is overwritten by Fore/Back
39
+ # and BRIGHT is overwritten by Style codes.
40
+ self._light = 0
41
+
42
+ def get_attrs(self):
43
+ return self._fore + self._back * 16 + (self._style | self._light)
44
+
45
+ def set_attrs(self, value):
46
+ self._fore = value & 7
47
+ self._back = (value >> 4) & 7
48
+ self._style = value & (WinStyle.BRIGHT | WinStyle.BRIGHT_BACKGROUND)
49
+
50
+ def reset_all(self, on_stderr=None):
51
+ self.set_attrs(self._default)
52
+ self.set_console(attrs=self._default)
53
+ self._light = 0
54
+
55
+ def fore(self, fore=None, light=False, on_stderr=False):
56
+ if fore is None:
57
+ fore = self._default_fore
58
+ self._fore = fore
59
+ # Emulate LIGHT_EX with BRIGHT Style
60
+ if light:
61
+ self._light |= WinStyle.BRIGHT
62
+ else:
63
+ self._light &= ~WinStyle.BRIGHT
64
+ self.set_console(on_stderr=on_stderr)
65
+
66
+ def back(self, back=None, light=False, on_stderr=False):
67
+ if back is None:
68
+ back = self._default_back
69
+ self._back = back
70
+ # Emulate LIGHT_EX with BRIGHT_BACKGROUND Style
71
+ if light:
72
+ self._light |= WinStyle.BRIGHT_BACKGROUND
73
+ else:
74
+ self._light &= ~WinStyle.BRIGHT_BACKGROUND
75
+ self.set_console(on_stderr=on_stderr)
76
+
77
+ def style(self, style=None, on_stderr=False):
78
+ if style is None:
79
+ style = self._default_style
80
+ self._style = style
81
+ self.set_console(on_stderr=on_stderr)
82
+
83
+ def set_console(self, attrs=None, on_stderr=False):
84
+ if attrs is None:
85
+ attrs = self.get_attrs()
86
+ handle = win32.STDOUT
87
+ if on_stderr:
88
+ handle = win32.STDERR
89
+ win32.SetConsoleTextAttribute(handle, attrs)
90
+
91
+ def get_position(self, handle):
92
+ position = win32.GetConsoleScreenBufferInfo(handle).dwCursorPosition
93
+ # Because Windows coordinates are 0-based,
94
+ # and win32.SetConsoleCursorPosition expects 1-based.
95
+ position.X += 1
96
+ position.Y += 1
97
+ return position
98
+
99
+ def set_cursor_position(self, position=None, on_stderr=False):
100
+ if position is None:
101
+ # I'm not currently tracking the position, so there is no default.
102
+ # position = self.get_position()
103
+ return
104
+ handle = win32.STDOUT
105
+ if on_stderr:
106
+ handle = win32.STDERR
107
+ win32.SetConsoleCursorPosition(handle, position)
108
+
109
+ def cursor_adjust(self, x, y, on_stderr=False):
110
+ handle = win32.STDOUT
111
+ if on_stderr:
112
+ handle = win32.STDERR
113
+ position = self.get_position(handle)
114
+ adjusted_position = (position.Y + y, position.X + x)
115
+ win32.SetConsoleCursorPosition(handle, adjusted_position, adjust=False)
116
+
117
+ def erase_screen(self, mode=0, on_stderr=False):
118
+ # 0 should clear from the cursor to the end of the screen.
119
+ # 1 should clear from the cursor to the beginning of the screen.
120
+ # 2 should clear the entire screen, and move cursor to (1,1)
121
+ handle = win32.STDOUT
122
+ if on_stderr:
123
+ handle = win32.STDERR
124
+ csbi = win32.GetConsoleScreenBufferInfo(handle)
125
+ # get the number of character cells in the current buffer
126
+ cells_in_screen = csbi.dwSize.X * csbi.dwSize.Y
127
+ # get number of character cells before current cursor position
128
+ cells_before_cursor = csbi.dwSize.X * csbi.dwCursorPosition.Y + csbi.dwCursorPosition.X
129
+ if mode == 0:
130
+ from_coord = csbi.dwCursorPosition
131
+ cells_to_erase = cells_in_screen - cells_before_cursor
132
+ elif mode == 1:
133
+ from_coord = win32.COORD(0, 0)
134
+ cells_to_erase = cells_before_cursor
135
+ elif mode == 2:
136
+ from_coord = win32.COORD(0, 0)
137
+ cells_to_erase = cells_in_screen
138
+ else:
139
+ # invalid mode
140
+ return
141
+ # fill the entire screen with blanks
142
+ win32.FillConsoleOutputCharacter(handle, ' ', cells_to_erase, from_coord)
143
+ # now set the buffer's attributes accordingly
144
+ win32.FillConsoleOutputAttribute(handle, self.get_attrs(), cells_to_erase, from_coord)
145
+ if mode == 2:
146
+ # put the cursor where needed
147
+ win32.SetConsoleCursorPosition(handle, (1, 1))
148
+
149
+ def erase_line(self, mode=0, on_stderr=False):
150
+ # 0 should clear from the cursor to the end of the line.
151
+ # 1 should clear from the cursor to the beginning of the line.
152
+ # 2 should clear the entire line.
153
+ handle = win32.STDOUT
154
+ if on_stderr:
155
+ handle = win32.STDERR
156
+ csbi = win32.GetConsoleScreenBufferInfo(handle)
157
+ if mode == 0:
158
+ from_coord = csbi.dwCursorPosition
159
+ cells_to_erase = csbi.dwSize.X - csbi.dwCursorPosition.X
160
+ elif mode == 1:
161
+ from_coord = win32.COORD(0, csbi.dwCursorPosition.Y)
162
+ cells_to_erase = csbi.dwCursorPosition.X
163
+ elif mode == 2:
164
+ from_coord = win32.COORD(0, csbi.dwCursorPosition.Y)
165
+ cells_to_erase = csbi.dwSize.X
166
+ else:
167
+ # invalid mode
168
+ return
169
+ # fill the entire screen with blanks
170
+ win32.FillConsoleOutputCharacter(handle, ' ', cells_to_erase, from_coord)
171
+ # now set the buffer's attributes accordingly
172
+ win32.FillConsoleOutputAttribute(handle, self.get_attrs(), cells_to_erase, from_coord)
173
+
174
+ def set_title(self, title):
175
+ win32.SetConsoleTitle(title)
176
+
177
+
178
+ def enable_vt_processing(fd):
179
+ if win32.windll is None or not win32.winapi_test():
180
+ return False
181
+
182
+ try:
183
+ handle = get_osfhandle(fd)
184
+ mode = win32.GetConsoleMode(handle)
185
+ win32.SetConsoleMode(
186
+ handle,
187
+ mode | win32.ENABLE_VIRTUAL_TERMINAL_PROCESSING,
188
+ )
189
+
190
+ mode = win32.GetConsoleMode(handle)
191
+ if mode & win32.ENABLE_VIRTUAL_TERMINAL_PROCESSING:
192
+ return True
193
+ # Can get TypeError in testsuite where 'fd' is a Mock()
194
+ except (OSError, TypeError):
195
+ return False
python_embeded/Lib/site-packages/coloredlogs-15.0.1.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
python_embeded/Lib/site-packages/coloredlogs-15.0.1.dist-info/LICENSE.txt ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright (c) 2020 Peter Odding
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
python_embeded/Lib/site-packages/coloredlogs-15.0.1.dist-info/METADATA ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.1
2
+ Name: coloredlogs
3
+ Version: 15.0.1
4
+ Summary: Colored terminal output for Python's logging module
5
+ Home-page: https://coloredlogs.readthedocs.io
6
+ Author: Peter Odding
7
+ Author-email: peter@peterodding.com
8
+ License: MIT
9
+ Platform: UNKNOWN
10
+ Classifier: Development Status :: 5 - Production/Stable
11
+ Classifier: Environment :: Console
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Intended Audience :: Information Technology
14
+ Classifier: Intended Audience :: System Administrators
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Operating System :: MacOS
17
+ Classifier: Operating System :: Microsoft :: Windows
18
+ Classifier: Operating System :: POSIX
19
+ Classifier: Operating System :: Unix
20
+ Classifier: Programming Language :: Python
21
+ Classifier: Programming Language :: Python :: 2
22
+ Classifier: Programming Language :: Python :: 2.7
23
+ Classifier: Programming Language :: Python :: 3
24
+ Classifier: Programming Language :: Python :: 3.5
25
+ Classifier: Programming Language :: Python :: 3.6
26
+ Classifier: Programming Language :: Python :: 3.7
27
+ Classifier: Programming Language :: Python :: 3.8
28
+ Classifier: Programming Language :: Python :: Implementation :: CPython
29
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
30
+ Classifier: Topic :: Communications
31
+ Classifier: Topic :: Scientific/Engineering :: Human Machine Interfaces
32
+ Classifier: Topic :: Software Development
33
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
34
+ Classifier: Topic :: Software Development :: User Interfaces
35
+ Classifier: Topic :: System
36
+ Classifier: Topic :: System :: Shells
37
+ Classifier: Topic :: System :: System Shells
38
+ Classifier: Topic :: System :: Console Fonts
39
+ Classifier: Topic :: System :: Logging
40
+ Classifier: Topic :: System :: Systems Administration
41
+ Classifier: Topic :: Terminals
42
+ Classifier: Topic :: Utilities
43
+ Requires-Python: >=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*
44
+ Requires-Dist: humanfriendly (>=9.1)
45
+ Provides-Extra: cron
46
+ Requires-Dist: capturer (>=2.4) ; extra == 'cron'
47
+
48
+ coloredlogs: Colored terminal output for Python's logging module
49
+ ================================================================
50
+
51
+ .. image:: https://travis-ci.org/xolox/python-coloredlogs.svg?branch=master
52
+ :target: https://travis-ci.org/xolox/python-coloredlogs
53
+
54
+ .. image:: https://coveralls.io/repos/github/xolox/python-coloredlogs/badge.svg?branch=master
55
+ :target: https://coveralls.io/github/xolox/python-coloredlogs?branch=master
56
+
57
+ The `coloredlogs` package enables colored terminal output for Python's logging_
58
+ module. The ColoredFormatter_ class inherits from `logging.Formatter`_ and uses
59
+ `ANSI escape sequences`_ to render your logging messages in color. It uses only
60
+ standard colors so it should work on any UNIX terminal. It's currently tested
61
+ on Python 2.7, 3.5+ and PyPy (2 and 3). On Windows `coloredlogs` automatically
62
+ tries to enable native ANSI support (on up-to-date Windows 10 installations)
63
+ and falls back on using colorama_ (if installed). Here is a screen shot of the
64
+ demo that is printed when the command ``coloredlogs --demo`` is executed:
65
+
66
+ .. image:: https://coloredlogs.readthedocs.io/en/latest/_images/defaults.png
67
+
68
+ Note that the screenshot above includes custom logging levels defined by my
69
+ verboselogs_ package: if you install both `coloredlogs` and `verboselogs` it
70
+ will Just Work (`verboselogs` is of course not required to use
71
+ `coloredlogs`).
72
+
73
+ .. contents::
74
+ :local:
75
+
76
+ Installation
77
+ ------------
78
+
79
+ The `coloredlogs` package is available on PyPI_ which means installation should
80
+ be as simple as:
81
+
82
+ .. code-block:: console
83
+
84
+ $ pip install coloredlogs
85
+
86
+ There's actually a multitude of ways to install Python packages (e.g. the `per
87
+ user site-packages directory`_, `virtual environments`_ or just installing
88
+ system wide) and I have no intention of getting into that discussion here, so
89
+ if this intimidates you then read up on your options before returning to these
90
+ instructions 😉.
91
+
92
+ Optional dependencies
93
+ ~~~~~~~~~~~~~~~~~~~~~
94
+
95
+ Native ANSI support on Windows requires an up-to-date Windows 10 installation.
96
+ If this is not working for you then consider installing the colorama_ package:
97
+
98
+ .. code-block:: console
99
+
100
+ $ pip install colorama
101
+
102
+ Once colorama_ is installed it will be used automatically.
103
+
104
+ Usage
105
+ -----
106
+
107
+ Here's an example of how easy it is to get started:
108
+
109
+ .. code-block:: python
110
+
111
+ import coloredlogs, logging
112
+
113
+ # Create a logger object.
114
+ logger = logging.getLogger(__name__)
115
+
116
+ # By default the install() function installs a handler on the root logger,
117
+ # this means that log messages from your code and log messages from the
118
+ # libraries that you use will all show up on the terminal.
119
+ coloredlogs.install(level='DEBUG')
120
+
121
+ # If you don't want to see log messages from libraries, you can pass a
122
+ # specific logger object to the install() function. In this case only log
123
+ # messages originating from that logger will show up on the terminal.
124
+ coloredlogs.install(level='DEBUG', logger=logger)
125
+
126
+ # Some examples.
127
+ logger.debug("this is a debugging message")
128
+ logger.info("this is an informational message")
129
+ logger.warning("this is a warning message")
130
+ logger.error("this is an error message")
131
+ logger.critical("this is a critical message")
132
+
133
+ Format of log messages
134
+ ----------------------
135
+
136
+ The ColoredFormatter_ class supports user defined log formats so you can use
137
+ any log format you like. The default log format is as follows::
138
+
139
+ %(asctime)s %(hostname)s %(name)s[%(process)d] %(levelname)s %(message)s
140
+
141
+ This log format results in the following output::
142
+
143
+ 2015-10-23 03:32:22 peter-macbook coloredlogs.demo[30462] DEBUG message with level 'debug'
144
+ 2015-10-23 03:32:23 peter-macbook coloredlogs.demo[30462] VERBOSE message with level 'verbose'
145
+ 2015-10-23 03:32:24 peter-macbook coloredlogs.demo[30462] INFO message with level 'info'
146
+ ...
147
+
148
+ You can customize the log format and styling using environment variables as
149
+ well as programmatically, please refer to the `online documentation`_ for
150
+ details.
151
+
152
+ Enabling millisecond precision
153
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
154
+
155
+ If you're switching from `logging.basicConfig()`_ to `coloredlogs.install()`_
156
+ you may notice that timestamps no longer include milliseconds. This is because
157
+ coloredlogs doesn't output milliseconds in timestamps unless you explicitly
158
+ tell it to. There are three ways to do that:
159
+
160
+ 1. The easy way is to pass the `milliseconds` argument to `coloredlogs.install()`_::
161
+
162
+ coloredlogs.install(milliseconds=True)
163
+
164
+ This became supported in `release 7.1`_ (due to `#16`_).
165
+
166
+ 2. Alternatively you can change the log format `to include 'msecs'`_::
167
+
168
+ %(asctime)s,%(msecs)03d %(hostname)s %(name)s[%(process)d] %(levelname)s %(message)s
169
+
170
+ Here's what the call to `coloredlogs.install()`_ would then look like::
171
+
172
+ coloredlogs.install(fmt='%(asctime)s,%(msecs)03d %(hostname)s %(name)s[%(process)d] %(levelname)s %(message)s')
173
+
174
+ Customizing the log format also enables you to change the delimiter that
175
+ separates seconds from milliseconds (the comma above). This became possible
176
+ in `release 3.0`_ which added support for user defined log formats.
177
+
178
+ 3. If the use of ``%(msecs)d`` isn't flexible enough you can instead add ``%f``
179
+ to the date/time format, it will be replaced by the value of ``%(msecs)03d``.
180
+ Support for the ``%f`` directive was added to `release 9.3`_ (due to `#45`_).
181
+
182
+ Custom logging fields
183
+ ~~~~~~~~~~~~~~~~~~~~~
184
+
185
+ The following custom log format fields are supported:
186
+
187
+ - ``%(hostname)s`` provides the hostname of the local system.
188
+ - ``%(programname)s`` provides the name of the currently running program.
189
+ - ``%(username)s`` provides the username of the currently logged in user.
190
+
191
+ When `coloredlogs.install()`_ detects that any of these fields are used in the
192
+ format string the applicable logging.Filter_ subclasses are automatically
193
+ registered to populate the relevant log record fields.
194
+
195
+ Changing text styles and colors
196
+ -------------------------------
197
+
198
+ The online documentation contains `an example of customizing the text styles and
199
+ colors <https://coloredlogs.readthedocs.io/en/latest/api.html#changing-the-colors-styles>`_.
200
+
201
+ Colored output from cron
202
+ ------------------------
203
+
204
+ When `coloredlogs` is used in a cron_ job, the output that's e-mailed to you by
205
+ cron won't contain any ANSI escape sequences because `coloredlogs` realizes
206
+ that it's not attached to an interactive terminal. If you'd like to have colors
207
+ e-mailed to you by cron there are two ways to make it happen:
208
+
209
+ .. contents::
210
+ :local:
211
+
212
+ Modifying your crontab
213
+ ~~~~~~~~~~~~~~~~~~~~~~
214
+
215
+ Here's an example of a minimal crontab::
216
+
217
+ MAILTO="your-email-address@here"
218
+ CONTENT_TYPE="text/html"
219
+ * * * * * root coloredlogs --to-html your-command
220
+
221
+ The ``coloredlogs`` program is installed when you install the `coloredlogs`
222
+ Python package. When you execute ``coloredlogs --to-html your-command`` it runs
223
+ ``your-command`` under the external program ``script`` (you need to have this
224
+ installed). This makes ``your-command`` think that it's attached to an
225
+ interactive terminal which means it will output ANSI escape sequences which
226
+ will then be converted to HTML by the ``coloredlogs`` program. Yes, this is a
227
+ bit convoluted, but it works great :-)
228
+
229
+ Modifying your Python code
230
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
231
+
232
+ The ColoredCronMailer_ class provides a context manager that automatically
233
+ enables HTML output when the ``$CONTENT_TYPE`` variable has been correctly set
234
+ in the crontab.
235
+
236
+ This requires my capturer_ package which you can install using ``pip install
237
+ 'coloredlogs[cron]'``. The ``[cron]`` extra will pull in capturer_ 2.4 or newer
238
+ which is required to capture the output while silencing it - otherwise you'd
239
+ get duplicate output in the emails sent by ``cron``.
240
+
241
+ The context manager can also be used to retroactively silence output that has
242
+ already been produced, this can be useful to avoid spammy cron jobs that have
243
+ nothing useful to do but still email their output to the system administrator
244
+ every few minutes :-).
245
+
246
+ Contact
247
+ -------
248
+
249
+ The latest version of `coloredlogs` is available on PyPI_ and GitHub_. The
250
+ `online documentation`_ is available on Read The Docs and includes a
251
+ changelog_. For bug reports please create an issue on GitHub_. If you have
252
+ questions, suggestions, etc. feel free to send me an e-mail at
253
+ `peter@peterodding.com`_.
254
+
255
+ License
256
+ -------
257
+
258
+ This software is licensed under the `MIT license`_.
259
+
260
+ © 2020 Peter Odding.
261
+
262
+
263
+ .. External references:
264
+ .. _#16: https://github.com/xolox/python-coloredlogs/issues/16
265
+ .. _#45: https://github.com/xolox/python-coloredlogs/issues/45
266
+ .. _ANSI escape sequences: https://en.wikipedia.org/wiki/ANSI_escape_code#Colors
267
+ .. _capturer: https://pypi.org/project/capturer
268
+ .. _changelog: https://coloredlogs.readthedocs.org/en/latest/changelog.html
269
+ .. _colorama: https://pypi.org/project/colorama
270
+ .. _ColoredCronMailer: https://coloredlogs.readthedocs.io/en/latest/api.html#coloredlogs.converter.ColoredCronMailer
271
+ .. _ColoredFormatter: https://coloredlogs.readthedocs.io/en/latest/api.html#coloredlogs.ColoredFormatter
272
+ .. _coloredlogs.install(): https://coloredlogs.readthedocs.io/en/latest/api.html#coloredlogs.install
273
+ .. _cron: https://en.wikipedia.org/wiki/Cron
274
+ .. _GitHub: https://github.com/xolox/python-coloredlogs
275
+ .. _logging.basicConfig(): https://docs.python.org/2/library/logging.html#logging.basicConfig
276
+ .. _logging.Filter: https://docs.python.org/3/library/logging.html#filter-objects
277
+ .. _logging.Formatter: https://docs.python.org/2/library/logging.html#logging.Formatter
278
+ .. _logging: https://docs.python.org/2/library/logging.html
279
+ .. _MIT license: https://en.wikipedia.org/wiki/MIT_License
280
+ .. _online documentation: https://coloredlogs.readthedocs.io/
281
+ .. _per user site-packages directory: https://www.python.org/dev/peps/pep-0370/
282
+ .. _peter@peterodding.com: peter@peterodding.com
283
+ .. _PyPI: https://pypi.org/project/coloredlogs
284
+ .. _release 3.0: https://coloredlogs.readthedocs.io/en/latest/changelog.html#release-3-0-2015-10-23
285
+ .. _release 7.1: https://coloredlogs.readthedocs.io/en/latest/changelog.html#release-7-1-2017-07-15
286
+ .. _release 9.3: https://coloredlogs.readthedocs.io/en/latest/changelog.html#release-9-3-2018-04-29
287
+ .. _to include 'msecs': https://stackoverflow.com/questions/6290739/python-logging-use-milliseconds-in-time-format
288
+ .. _verboselogs: https://pypi.org/project/verboselogs
289
+ .. _virtual environments: http://docs.python-guide.org/en/latest/dev/virtualenvs/
290
+
291
+
python_embeded/Lib/site-packages/coloredlogs-15.0.1.dist-info/RECORD ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ../../Scripts/coloredlogs.exe,sha256=UpWqPnsJPyK7RTPZ6QR6loFv_v88xTUGg3TOwzTEVQo,108416
2
+ coloredlogs-15.0.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
3
+ coloredlogs-15.0.1.dist-info/LICENSE.txt,sha256=C-9P-xhVtlVwME8gGMbUTkurl71d-HFuzXgAAU1xcmc,1056
4
+ coloredlogs-15.0.1.dist-info/METADATA,sha256=FmO6unRvNe77JJ2UU0XYhWbMTzZDhj6zGpEljDysZ0w,12387
5
+ coloredlogs-15.0.1.dist-info/RECORD,,
6
+ coloredlogs-15.0.1.dist-info/WHEEL,sha256=kGT74LWyRUZrL4VgLh6_g12IeVl_9u9ZVhadrgXZUEY,110
7
+ coloredlogs-15.0.1.dist-info/entry_points.txt,sha256=uOmYMPjy7X6effmVh56i3U3N9S13DTRozJOAncBtZG0,54
8
+ coloredlogs-15.0.1.dist-info/top_level.txt,sha256=D3LuRvusEQ8xKUhPowPUmPWNm88FSw8ts3x2ulvCSyQ,12
9
+ coloredlogs.pth,sha256=3ag6hVmG76XNh_AkiwGZwAhusOjn_s59Z0GVnFzjlTY,147
10
+ coloredlogs/__init__.py,sha256=FxaiI1pQ0JzRYbx2K5f_Ar9Wa1meZLg5XKGWHKgPBNo,64423
11
+ coloredlogs/__pycache__/__init__.cpython-312.pyc,,
12
+ coloredlogs/__pycache__/cli.cpython-312.pyc,,
13
+ coloredlogs/__pycache__/demo.cpython-312.pyc,,
14
+ coloredlogs/__pycache__/syslog.cpython-312.pyc,,
15
+ coloredlogs/__pycache__/tests.cpython-312.pyc,,
16
+ coloredlogs/cli.py,sha256=iaHgUVeHPl5iIecKG1WJMslOJEKdhEusbxj7B4r1sHI,3493
17
+ coloredlogs/converter/__init__.py,sha256=t08e9V8-Ed9y9eNSYv3x1DH0hXgaXHJmQWp54j_a2nk,18353
18
+ coloredlogs/converter/__pycache__/__init__.cpython-312.pyc,,
19
+ coloredlogs/converter/__pycache__/colors.cpython-312.pyc,,
20
+ coloredlogs/converter/colors.py,sha256=1N2PpCa-EYMMWyC6Dw7SG2WX1gC67F9F5OteeFW52SM,5387
21
+ coloredlogs/demo.py,sha256=CaPVGOB6rCtJDyeqk0VBLi0t05jgUEniuB__VYo5kho,1825
22
+ coloredlogs/syslog.py,sha256=-XyRUzI20QKTTtVqhJAtfYc-ljw0crsjxqjWDjqrcqU,11849
23
+ coloredlogs/tests.py,sha256=oe_pWnTGfNEI7spY3_VA62fX_09ZEVFVERvr9sBMqnM,30791
python_embeded/Lib/site-packages/coloredlogs-15.0.1.dist-info/WHEEL ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.34.2)
3
+ Root-Is-Purelib: true
4
+ Tag: py2-none-any
5
+ Tag: py3-none-any
6
+
python_embeded/Lib/site-packages/coloredlogs-15.0.1.dist-info/entry_points.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ [console_scripts]
2
+ coloredlogs = coloredlogs.cli:main
3
+
python_embeded/Lib/site-packages/coloredlogs-15.0.1.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ coloredlogs
python_embeded/Lib/site-packages/coloredlogs/__init__.py ADDED
@@ -0,0 +1,1524 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Colored terminal output for Python's logging module.
2
+ #
3
+ # Author: Peter Odding <peter@peterodding.com>
4
+ # Last Change: June 11, 2021
5
+ # URL: https://coloredlogs.readthedocs.io
6
+
7
+ """
8
+ Colored terminal output for Python's :mod:`logging` module.
9
+
10
+ .. contents::
11
+ :local:
12
+
13
+ Getting started
14
+ ===============
15
+
16
+ The easiest way to get started is by importing :mod:`coloredlogs` and calling
17
+ :mod:`coloredlogs.install()` (similar to :func:`logging.basicConfig()`):
18
+
19
+ >>> import coloredlogs, logging
20
+ >>> coloredlogs.install(level='DEBUG')
21
+ >>> logger = logging.getLogger('some.module.name')
22
+ >>> logger.info("this is an informational message")
23
+ 2015-10-22 19:13:52 peter-macbook some.module.name[28036] INFO this is an informational message
24
+
25
+ The :mod:`~coloredlogs.install()` function creates a :class:`ColoredFormatter`
26
+ that injects `ANSI escape sequences`_ into the log output.
27
+
28
+ .. _ANSI escape sequences: https://en.wikipedia.org/wiki/ANSI_escape_code#Colors
29
+
30
+ Environment variables
31
+ =====================
32
+
33
+ The following environment variables can be used to configure the
34
+ :mod:`coloredlogs` module without writing any code:
35
+
36
+ ============================= ============================ ==================================
37
+ Environment variable Default value Type of value
38
+ ============================= ============================ ==================================
39
+ ``$COLOREDLOGS_AUTO_INSTALL`` 'false' a boolean that controls whether
40
+ :func:`auto_install()` is called
41
+ ``$COLOREDLOGS_LOG_LEVEL`` 'INFO' a log level name
42
+ ``$COLOREDLOGS_LOG_FORMAT`` :data:`DEFAULT_LOG_FORMAT` a log format string
43
+ ``$COLOREDLOGS_DATE_FORMAT`` :data:`DEFAULT_DATE_FORMAT` a date/time format string
44
+ ``$COLOREDLOGS_LEVEL_STYLES`` :data:`DEFAULT_LEVEL_STYLES` see :func:`parse_encoded_styles()`
45
+ ``$COLOREDLOGS_FIELD_STYLES`` :data:`DEFAULT_FIELD_STYLES` see :func:`parse_encoded_styles()`
46
+ ============================= ============================ ==================================
47
+
48
+ If the environment variable `$NO_COLOR`_ is set (the value doesn't matter, even
49
+ an empty string will do) then :func:`coloredlogs.install()` will take this as a
50
+ hint that colors should not be used (unless the ``isatty=True`` override was
51
+ passed by the caller).
52
+
53
+ .. _$NO_COLOR: https://no-color.org/
54
+
55
+ Examples of customization
56
+ =========================
57
+
58
+ Here we'll take a look at some examples of how you can customize
59
+ :mod:`coloredlogs` using environment variables.
60
+
61
+ .. contents::
62
+ :local:
63
+
64
+ About the defaults
65
+ ------------------
66
+
67
+ Here's a screen shot of the default configuration for easy comparison with the
68
+ screen shots of the following customizations (this is the same screen shot that
69
+ is shown in the introduction):
70
+
71
+ .. image:: images/defaults.png
72
+ :alt: Screen shot of colored logging with defaults.
73
+
74
+ The screen shot above was taken from ``urxvt`` which doesn't support faint text
75
+ colors, otherwise the color of green used for `debug` messages would have
76
+ differed slightly from the color of green used for `spam` messages.
77
+
78
+ Apart from the `faint` style of the `spam` level, the default configuration of
79
+ `coloredlogs` sticks to the eight color palette defined by the original ANSI
80
+ standard, in order to provide a somewhat consistent experience across terminals
81
+ and terminal emulators.
82
+
83
+ Available text styles and colors
84
+ --------------------------------
85
+
86
+ Of course you are free to customize the default configuration, in this case you
87
+ can use any text style or color that you know is supported by your terminal.
88
+ You can use the ``humanfriendly --demo`` command to try out the supported text
89
+ styles and colors:
90
+
91
+ .. image:: http://humanfriendly.readthedocs.io/en/latest/_images/ansi-demo.png
92
+ :alt: Screen shot of the 'humanfriendly --demo' command.
93
+
94
+ Changing the log format
95
+ -----------------------
96
+
97
+ The simplest customization is to change the log format, for example:
98
+
99
+ .. literalinclude:: examples/custom-log-format.txt
100
+ :language: console
101
+
102
+ Here's what that looks like in a terminal (I always work in terminals with a
103
+ black background and white text):
104
+
105
+ .. image:: images/custom-log-format.png
106
+ :alt: Screen shot of colored logging with custom log format.
107
+
108
+ Changing the date/time format
109
+ -----------------------------
110
+
111
+ You can also change the date/time format, for example you can remove the date
112
+ part and leave only the time:
113
+
114
+ .. literalinclude:: examples/custom-datetime-format.txt
115
+ :language: console
116
+
117
+ Here's what it looks like in a terminal:
118
+
119
+ .. image:: images/custom-datetime-format.png
120
+ :alt: Screen shot of colored logging with custom date/time format.
121
+
122
+ Changing the colors/styles
123
+ --------------------------
124
+
125
+ Finally you can customize the colors and text styles that are used:
126
+
127
+ .. literalinclude:: examples/custom-colors.txt
128
+ :language: console
129
+
130
+ Here's an explanation of the features used here:
131
+
132
+ - The numbers used in ``$COLOREDLOGS_LEVEL_STYLES`` demonstrate the use of 256
133
+ color mode (the numbers refer to the 256 color mode palette which is fixed).
134
+
135
+ - The `success` level demonstrates the use of a text style (bold).
136
+
137
+ - The `critical` level demonstrates the use of a background color (red).
138
+
139
+ Of course none of this can be seen in the shell transcript quoted above, but
140
+ take a look at the following screen shot:
141
+
142
+ .. image:: images/custom-colors.png
143
+ :alt: Screen shot of colored logging with custom colors.
144
+
145
+ .. _notes about log levels:
146
+
147
+ Some notes about log levels
148
+ ===========================
149
+
150
+ With regards to the handling of log levels, the :mod:`coloredlogs` package
151
+ differs from Python's :mod:`logging` module in two aspects:
152
+
153
+ 1. While the :mod:`logging` module uses the default logging level
154
+ :data:`logging.WARNING`, the :mod:`coloredlogs` package has always used
155
+ :data:`logging.INFO` as its default log level.
156
+
157
+ 2. When logging to the terminal or system log is initialized by
158
+ :func:`install()` or :func:`.enable_system_logging()` the effective
159
+ level [#]_ of the selected logger [#]_ is compared against the requested
160
+ level [#]_ and if the effective level is more restrictive than the requested
161
+ level, the logger's level will be set to the requested level (this happens
162
+ in :func:`adjust_level()`). The reason for this is to work around a
163
+ combination of design choices in Python's :mod:`logging` module that can
164
+ easily confuse people who aren't already intimately familiar with it:
165
+
166
+ - All loggers are initialized with the level :data:`logging.NOTSET`.
167
+
168
+ - When a logger's level is set to :data:`logging.NOTSET` the
169
+ :func:`~logging.Logger.getEffectiveLevel()` method will
170
+ fall back to the level of the parent logger.
171
+
172
+ - The parent of all loggers is the root logger and the root logger has its
173
+ level set to :data:`logging.WARNING` by default (after importing the
174
+ :mod:`logging` module).
175
+
176
+ Effectively all user defined loggers inherit the default log level
177
+ :data:`logging.WARNING` from the root logger, which isn't very intuitive for
178
+ those who aren't already familiar with the hierarchical nature of the
179
+ :mod:`logging` module.
180
+
181
+ By avoiding this potentially confusing behavior (see `#14`_, `#18`_, `#21`_,
182
+ `#23`_ and `#24`_), while at the same time allowing the caller to specify a
183
+ logger object, my goal and hope is to provide sane defaults that can easily
184
+ be changed when the need arises.
185
+
186
+ .. [#] Refer to :func:`logging.Logger.getEffectiveLevel()` for details.
187
+ .. [#] The logger that is passed as an argument by the caller or the root
188
+ logger which is selected as a default when no logger is provided.
189
+ .. [#] The log level that is passed as an argument by the caller or the
190
+ default log level :data:`logging.INFO` when no level is provided.
191
+
192
+ .. _#14: https://github.com/xolox/python-coloredlogs/issues/14
193
+ .. _#18: https://github.com/xolox/python-coloredlogs/issues/18
194
+ .. _#21: https://github.com/xolox/python-coloredlogs/pull/21
195
+ .. _#23: https://github.com/xolox/python-coloredlogs/pull/23
196
+ .. _#24: https://github.com/xolox/python-coloredlogs/issues/24
197
+
198
+ Classes and functions
199
+ =====================
200
+ """
201
+
202
+ # Standard library modules.
203
+ import collections
204
+ import logging
205
+ import os
206
+ import re
207
+ import socket
208
+ import sys
209
+
210
+ # External dependencies.
211
+ from humanfriendly import coerce_boolean
212
+ from humanfriendly.compat import coerce_string, is_string, on_windows
213
+ from humanfriendly.terminal import ANSI_COLOR_CODES, ansi_wrap, enable_ansi_support, terminal_supports_colors
214
+ from humanfriendly.text import format, split
215
+
216
+ # Semi-standard module versioning.
217
+ __version__ = '15.0.1'
218
+
219
+ DEFAULT_LOG_LEVEL = logging.INFO
220
+ """The default log level for :mod:`coloredlogs` (:data:`logging.INFO`)."""
221
+
222
+ DEFAULT_LOG_FORMAT = '%(asctime)s %(hostname)s %(name)s[%(process)d] %(levelname)s %(message)s'
223
+ """The default log format for :class:`ColoredFormatter` objects (a string)."""
224
+
225
+ DEFAULT_DATE_FORMAT = '%Y-%m-%d %H:%M:%S'
226
+ """The default date/time format for :class:`ColoredFormatter` objects (a string)."""
227
+
228
+ CHROOT_FILES = ['/etc/debian_chroot']
229
+ """A list of filenames that indicate a chroot and contain the name of the chroot."""
230
+
231
+ DEFAULT_FIELD_STYLES = dict(
232
+ asctime=dict(color='green'),
233
+ hostname=dict(color='magenta'),
234
+ levelname=dict(color='black', bold=True),
235
+ name=dict(color='blue'),
236
+ programname=dict(color='cyan'),
237
+ username=dict(color='yellow'),
238
+ )
239
+ """Mapping of log format names to default font styles."""
240
+
241
+ DEFAULT_LEVEL_STYLES = dict(
242
+ spam=dict(color='green', faint=True),
243
+ debug=dict(color='green'),
244
+ verbose=dict(color='blue'),
245
+ info=dict(),
246
+ notice=dict(color='magenta'),
247
+ warning=dict(color='yellow'),
248
+ success=dict(color='green', bold=True),
249
+ error=dict(color='red'),
250
+ critical=dict(color='red', bold=True),
251
+ )
252
+ """Mapping of log level names to default font styles."""
253
+
254
+ DEFAULT_FORMAT_STYLE = '%'
255
+ """The default logging format style (a single character)."""
256
+
257
+ FORMAT_STYLE_PATTERNS = {
258
+ '%': r'%\((\w+)\)[#0 +-]*\d*(?:\.\d+)?[hlL]?[diouxXeEfFgGcrs%]',
259
+ '{': r'{(\w+)[^}]*}',
260
+ '$': r'\$(\w+)|\${(\w+)}',
261
+ }
262
+ """
263
+ A dictionary that maps the `style` characters ``%``, ``{`` and ``$`` (see the
264
+ documentation of the :class:`python3:logging.Formatter` class in Python 3.2+)
265
+ to strings containing regular expression patterns that can be used to parse
266
+ format strings in the corresponding style:
267
+
268
+ ``%``
269
+ A string containing a regular expression that matches a "percent conversion
270
+ specifier" as defined in the `String Formatting Operations`_ section of the
271
+ Python documentation. Here's an example of a logging format string in this
272
+ format: ``%(levelname)s:%(name)s:%(message)s``.
273
+
274
+ ``{``
275
+ A string containing a regular expression that matches a "replacement field" as
276
+ defined in the `Format String Syntax`_ section of the Python documentation.
277
+ Here's an example of a logging format string in this format:
278
+ ``{levelname}:{name}:{message}``.
279
+
280
+ ``$``
281
+ A string containing a regular expression that matches a "substitution
282
+ placeholder" as defined in the `Template Strings`_ section of the Python
283
+ documentation. Here's an example of a logging format string in this format:
284
+ ``$levelname:$name:$message``.
285
+
286
+ These regular expressions are used by :class:`FormatStringParser` to introspect
287
+ and manipulate logging format strings.
288
+
289
+ .. _String Formatting Operations: https://docs.python.org/2/library/stdtypes.html#string-formatting
290
+ .. _Format String Syntax: https://docs.python.org/2/library/string.html#formatstrings
291
+ .. _Template Strings: https://docs.python.org/3/library/string.html#template-strings
292
+ """
293
+
294
+
295
+ def auto_install():
296
+ """
297
+ Automatically call :func:`install()` when ``$COLOREDLOGS_AUTO_INSTALL`` is set.
298
+
299
+ The `coloredlogs` package includes a `path configuration file`_ that
300
+ automatically imports the :mod:`coloredlogs` module and calls
301
+ :func:`auto_install()` when the environment variable
302
+ ``$COLOREDLOGS_AUTO_INSTALL`` is set.
303
+
304
+ This function uses :func:`~humanfriendly.coerce_boolean()` to check whether
305
+ the value of ``$COLOREDLOGS_AUTO_INSTALL`` should be considered :data:`True`.
306
+
307
+ .. _path configuration file: https://docs.python.org/2/library/site.html#module-site
308
+ """
309
+ if coerce_boolean(os.environ.get('COLOREDLOGS_AUTO_INSTALL', 'false')):
310
+ install()
311
+
312
+
313
+ def install(level=None, **kw):
314
+ """
315
+ Enable colored terminal output for Python's :mod:`logging` module.
316
+
317
+ :param level: The default logging level (an integer or a string with a
318
+ level name, defaults to :data:`DEFAULT_LOG_LEVEL`).
319
+ :param logger: The logger to which the stream handler should be attached (a
320
+ :class:`~logging.Logger` object, defaults to the root logger).
321
+ :param fmt: Set the logging format (a string like those accepted by
322
+ :class:`~logging.Formatter`, defaults to
323
+ :data:`DEFAULT_LOG_FORMAT`).
324
+ :param datefmt: Set the date/time format (a string, defaults to
325
+ :data:`DEFAULT_DATE_FORMAT`).
326
+ :param style: One of the characters ``%``, ``{`` or ``$`` (defaults to
327
+ :data:`DEFAULT_FORMAT_STYLE`). See the documentation of the
328
+ :class:`python3:logging.Formatter` class in Python 3.2+. On
329
+ older Python versions only ``%`` is supported.
330
+ :param milliseconds: :data:`True` to show milliseconds like :mod:`logging`
331
+ does by default, :data:`False` to hide milliseconds
332
+ (the default is :data:`False`, see `#16`_).
333
+ :param level_styles: A dictionary with custom level styles (defaults to
334
+ :data:`DEFAULT_LEVEL_STYLES`).
335
+ :param field_styles: A dictionary with custom field styles (defaults to
336
+ :data:`DEFAULT_FIELD_STYLES`).
337
+ :param stream: The stream where log messages should be written to (a
338
+ file-like object). This defaults to :data:`None` which
339
+ means :class:`StandardErrorHandler` is used.
340
+ :param isatty: :data:`True` to use a :class:`ColoredFormatter`,
341
+ :data:`False` to use a normal :class:`~logging.Formatter`
342
+ (defaults to auto-detection using
343
+ :func:`~humanfriendly.terminal.terminal_supports_colors()`).
344
+ :param reconfigure: If :data:`True` (the default) multiple calls to
345
+ :func:`coloredlogs.install()` will each override
346
+ the previous configuration.
347
+ :param use_chroot: Refer to :class:`HostNameFilter`.
348
+ :param programname: Refer to :class:`ProgramNameFilter`.
349
+ :param username: Refer to :class:`UserNameFilter`.
350
+ :param syslog: If :data:`True` then :func:`.enable_system_logging()` will
351
+ be called without arguments (defaults to :data:`False`). The
352
+ `syslog` argument may also be a number or string, in this
353
+ case it is assumed to be a logging level which is passed on
354
+ to :func:`.enable_system_logging()`.
355
+
356
+ The :func:`coloredlogs.install()` function is similar to
357
+ :func:`logging.basicConfig()`, both functions take a lot of optional
358
+ keyword arguments but try to do the right thing by default:
359
+
360
+ 1. If `reconfigure` is :data:`True` (it is by default) and an existing
361
+ :class:`~logging.StreamHandler` is found that is connected to either
362
+ :data:`~sys.stdout` or :data:`~sys.stderr` the handler will be removed.
363
+ This means that first calling :func:`logging.basicConfig()` and then
364
+ calling :func:`coloredlogs.install()` will replace the stream handler
365
+ instead of adding a duplicate stream handler. If `reconfigure` is
366
+ :data:`False` and an existing handler is found no further steps are
367
+ taken (to avoid installing a duplicate stream handler).
368
+
369
+ 2. A :class:`~logging.StreamHandler` is created and connected to the stream
370
+ given by the `stream` keyword argument (:data:`sys.stderr` by
371
+ default). The stream handler's level is set to the value of the `level`
372
+ keyword argument.
373
+
374
+ 3. A :class:`ColoredFormatter` is created if the `isatty` keyword argument
375
+ allows it (or auto-detection allows it), otherwise a normal
376
+ :class:`~logging.Formatter` is created. The formatter is initialized
377
+ with the `fmt` and `datefmt` keyword arguments (or their computed
378
+ defaults).
379
+
380
+ The environment variable ``$NO_COLOR`` is taken as a hint by
381
+ auto-detection that colors should not be used.
382
+
383
+ 4. :func:`HostNameFilter.install()`, :func:`ProgramNameFilter.install()`
384
+ and :func:`UserNameFilter.install()` are called to enable the use of
385
+ additional fields in the log format.
386
+
387
+ 5. If the logger's level is too restrictive it is relaxed (refer to `notes
388
+ about log levels`_ for details).
389
+
390
+ 6. The formatter is added to the handler and the handler is added to the
391
+ logger.
392
+
393
+ .. _#16: https://github.com/xolox/python-coloredlogs/issues/16
394
+ """
395
+ logger = kw.get('logger') or logging.getLogger()
396
+ reconfigure = kw.get('reconfigure', True)
397
+ stream = kw.get('stream') or sys.stderr
398
+ style = check_style(kw.get('style') or DEFAULT_FORMAT_STYLE)
399
+ # Get the log level from an argument, environment variable or default and
400
+ # convert the names of log levels to numbers to enable numeric comparison.
401
+ if level is None:
402
+ level = os.environ.get('COLOREDLOGS_LOG_LEVEL', DEFAULT_LOG_LEVEL)
403
+ level = level_to_number(level)
404
+ # Remove any existing stream handler that writes to stdout or stderr, even
405
+ # if the stream handler wasn't created by coloredlogs because multiple
406
+ # stream handlers (in the same hierarchy) writing to stdout or stderr would
407
+ # create duplicate output. `None' is a synonym for the possibly dynamic
408
+ # value of the stderr attribute of the sys module.
409
+ match_streams = ([sys.stdout, sys.stderr]
410
+ if stream in [sys.stdout, sys.stderr, None]
411
+ else [stream])
412
+ match_handler = lambda handler: match_stream_handler(handler, match_streams)
413
+ handler, logger = replace_handler(logger, match_handler, reconfigure)
414
+ # Make sure reconfiguration is allowed or not relevant.
415
+ if not (handler and not reconfigure):
416
+ # Make it easy to enable system logging.
417
+ syslog_enabled = kw.get('syslog')
418
+ # We ignore the value `None' because it means the caller didn't opt in
419
+ # to system logging and `False' because it means the caller explicitly
420
+ # opted out of system logging.
421
+ if syslog_enabled not in (None, False):
422
+ from coloredlogs.syslog import enable_system_logging
423
+ if syslog_enabled is True:
424
+ # If the caller passed syslog=True then we leave the choice of
425
+ # default log level up to the coloredlogs.syslog module.
426
+ enable_system_logging()
427
+ else:
428
+ # Values other than (None, True, False) are assumed to
429
+ # represent a logging level for system logging.
430
+ enable_system_logging(level=syslog_enabled)
431
+ # Figure out whether we can use ANSI escape sequences.
432
+ use_colors = kw.get('isatty', None)
433
+ # In the following indented block the expression (use_colors is None)
434
+ # can be read as "auto detect is enabled and no reason has yet been
435
+ # found to automatically disable color support".
436
+ if use_colors or (use_colors is None):
437
+ # Respect the user's choice not to have colors.
438
+ if use_colors is None and 'NO_COLOR' in os.environ:
439
+ # For details on this see https://no-color.org/.
440
+ use_colors = False
441
+ # Try to enable Windows native ANSI support or Colorama?
442
+ if (use_colors or use_colors is None) and on_windows():
443
+ # This can fail, in which case ANSI escape sequences would end
444
+ # up being printed to the terminal in raw form. This is very
445
+ # user hostile, so to avoid this happening we disable color
446
+ # support on failure.
447
+ use_colors = enable_ansi_support()
448
+ # When auto detection is enabled, and so far we encountered no
449
+ # reason to disable color support, then we will enable color
450
+ # support if 'stream' is connected to a terminal.
451
+ if use_colors is None:
452
+ use_colors = terminal_supports_colors(stream)
453
+ # Create a stream handler and make sure to preserve any filters
454
+ # the current handler may have (if an existing handler is found).
455
+ filters = handler.filters if handler else None
456
+ if stream is sys.stderr:
457
+ handler = StandardErrorHandler()
458
+ else:
459
+ handler = logging.StreamHandler(stream)
460
+ handler.setLevel(level)
461
+ if filters:
462
+ handler.filters = filters
463
+ # Prepare the arguments to the formatter, allowing the caller to
464
+ # customize the values of `fmt', `datefmt' and `style' as desired.
465
+ formatter_options = dict(fmt=kw.get('fmt'), datefmt=kw.get('datefmt'))
466
+ # Only pass the `style' argument to the formatter when the caller
467
+ # provided an alternative logging format style. This prevents
468
+ # TypeError exceptions on Python versions before 3.2.
469
+ if style != DEFAULT_FORMAT_STYLE:
470
+ formatter_options['style'] = style
471
+ # Come up with a default log format?
472
+ if not formatter_options['fmt']:
473
+ # Use the log format defined by the environment variable
474
+ # $COLOREDLOGS_LOG_FORMAT or fall back to the default.
475
+ formatter_options['fmt'] = os.environ.get('COLOREDLOGS_LOG_FORMAT') or DEFAULT_LOG_FORMAT
476
+ # If the caller didn't specify a date/time format we'll use the format
477
+ # defined by the environment variable $COLOREDLOGS_DATE_FORMAT (or fall
478
+ # back to the default).
479
+ if not formatter_options['datefmt']:
480
+ formatter_options['datefmt'] = os.environ.get('COLOREDLOGS_DATE_FORMAT') or DEFAULT_DATE_FORMAT
481
+ # Python's logging module shows milliseconds by default through special
482
+ # handling in the logging.Formatter.formatTime() method [1]. Because
483
+ # coloredlogs always defines a `datefmt' it bypasses this special
484
+ # handling, which is fine because ever since publishing coloredlogs
485
+ # I've never needed millisecond precision ;-). However there are users
486
+ # of coloredlogs that do want milliseconds to be shown [2] so we
487
+ # provide a shortcut to make it easy.
488
+ #
489
+ # [1] https://stackoverflow.com/questions/6290739/python-logging-use-milliseconds-in-time-format
490
+ # [2] https://github.com/xolox/python-coloredlogs/issues/16
491
+ if kw.get('milliseconds'):
492
+ parser = FormatStringParser(style=style)
493
+ if not (parser.contains_field(formatter_options['fmt'], 'msecs')
494
+ or '%f' in formatter_options['datefmt']):
495
+ pattern = parser.get_pattern('asctime')
496
+ replacements = {'%': '%(msecs)03d', '{': '{msecs:03}', '$': '${msecs}'}
497
+ formatter_options['fmt'] = pattern.sub(
498
+ r'\g<0>,' + replacements[style],
499
+ formatter_options['fmt'],
500
+ )
501
+ # Do we need to make %(hostname) available to the formatter?
502
+ HostNameFilter.install(
503
+ fmt=formatter_options['fmt'],
504
+ handler=handler,
505
+ style=style,
506
+ use_chroot=kw.get('use_chroot', True),
507
+ )
508
+ # Do we need to make %(programname) available to the formatter?
509
+ ProgramNameFilter.install(
510
+ fmt=formatter_options['fmt'],
511
+ handler=handler,
512
+ programname=kw.get('programname'),
513
+ style=style,
514
+ )
515
+ # Do we need to make %(username) available to the formatter?
516
+ UserNameFilter.install(
517
+ fmt=formatter_options['fmt'],
518
+ handler=handler,
519
+ username=kw.get('username'),
520
+ style=style,
521
+ )
522
+ # Inject additional formatter arguments specific to ColoredFormatter?
523
+ if use_colors:
524
+ for name, environment_name in (('field_styles', 'COLOREDLOGS_FIELD_STYLES'),
525
+ ('level_styles', 'COLOREDLOGS_LEVEL_STYLES')):
526
+ value = kw.get(name)
527
+ if value is None:
528
+ # If no styles have been specified we'll fall back
529
+ # to the styles defined by the environment variable.
530
+ environment_value = os.environ.get(environment_name)
531
+ if environment_value is not None:
532
+ value = parse_encoded_styles(environment_value)
533
+ if value is not None:
534
+ formatter_options[name] = value
535
+ # Create a (possibly colored) formatter.
536
+ formatter_type = ColoredFormatter if use_colors else BasicFormatter
537
+ handler.setFormatter(formatter_type(**formatter_options))
538
+ # Adjust the level of the selected logger.
539
+ adjust_level(logger, level)
540
+ # Install the stream handler.
541
+ logger.addHandler(handler)
542
+
543
+
544
+ def check_style(value):
545
+ """
546
+ Validate a logging format style.
547
+
548
+ :param value: The logging format style to validate (any value).
549
+ :returns: The logging format character (a string of one character).
550
+ :raises: :exc:`~exceptions.ValueError` when the given style isn't supported.
551
+
552
+ On Python 3.2+ this function accepts the logging format styles ``%``, ``{``
553
+ and ``$`` while on older versions only ``%`` is accepted (because older
554
+ Python versions don't support alternative logging format styles).
555
+ """
556
+ if sys.version_info[:2] >= (3, 2):
557
+ if value not in FORMAT_STYLE_PATTERNS:
558
+ msg = "Unsupported logging format style! (%r)"
559
+ raise ValueError(format(msg, value))
560
+ elif value != DEFAULT_FORMAT_STYLE:
561
+ msg = "Format string styles other than %r require Python 3.2+!"
562
+ raise ValueError(msg, DEFAULT_FORMAT_STYLE)
563
+ return value
564
+
565
+
566
+ def increase_verbosity():
567
+ """
568
+ Increase the verbosity of the root handler by one defined level.
569
+
570
+ Understands custom logging levels like defined by my ``verboselogs``
571
+ module.
572
+ """
573
+ defined_levels = sorted(set(find_defined_levels().values()))
574
+ current_index = defined_levels.index(get_level())
575
+ selected_index = max(0, current_index - 1)
576
+ set_level(defined_levels[selected_index])
577
+
578
+
579
+ def decrease_verbosity():
580
+ """
581
+ Decrease the verbosity of the root handler by one defined level.
582
+
583
+ Understands custom logging levels like defined by my ``verboselogs``
584
+ module.
585
+ """
586
+ defined_levels = sorted(set(find_defined_levels().values()))
587
+ current_index = defined_levels.index(get_level())
588
+ selected_index = min(current_index + 1, len(defined_levels) - 1)
589
+ set_level(defined_levels[selected_index])
590
+
591
+
592
+ def is_verbose():
593
+ """
594
+ Check whether the log level of the root handler is set to a verbose level.
595
+
596
+ :returns: ``True`` if the root handler is verbose, ``False`` if not.
597
+ """
598
+ return get_level() < DEFAULT_LOG_LEVEL
599
+
600
+
601
+ def get_level():
602
+ """
603
+ Get the logging level of the root handler.
604
+
605
+ :returns: The logging level of the root handler (an integer) or
606
+ :data:`DEFAULT_LOG_LEVEL` (if no root handler exists).
607
+ """
608
+ handler, logger = find_handler(logging.getLogger(), match_stream_handler)
609
+ return handler.level if handler else DEFAULT_LOG_LEVEL
610
+
611
+
612
+ def set_level(level):
613
+ """
614
+ Set the logging level of the root handler.
615
+
616
+ :param level: The logging level to filter on (an integer or string).
617
+
618
+ If no root handler exists yet this automatically calls :func:`install()`.
619
+ """
620
+ handler, logger = find_handler(logging.getLogger(), match_stream_handler)
621
+ if handler and logger:
622
+ # Change the level of the existing handler.
623
+ handler.setLevel(level_to_number(level))
624
+ # Adjust the level of the selected logger.
625
+ adjust_level(logger, level)
626
+ else:
627
+ # Create a new handler with the given level.
628
+ install(level=level)
629
+
630
+
631
+ def adjust_level(logger, level):
632
+ """
633
+ Increase a logger's verbosity up to the requested level.
634
+
635
+ :param logger: The logger to change (a :class:`~logging.Logger` object).
636
+ :param level: The log level to enable (a string or number).
637
+
638
+ This function is used by functions like :func:`install()`,
639
+ :func:`increase_verbosity()` and :func:`.enable_system_logging()` to adjust
640
+ a logger's level so that log messages up to the requested log level are
641
+ propagated to the configured output handler(s).
642
+
643
+ It uses :func:`logging.Logger.getEffectiveLevel()` to check whether
644
+ `logger` propagates or swallows log messages of the requested `level` and
645
+ sets the logger's level to the requested level if it would otherwise
646
+ swallow log messages.
647
+
648
+ Effectively this function will "widen the scope of logging" when asked to
649
+ do so but it will never "narrow the scope of logging". This is because I am
650
+ convinced that filtering of log messages should (primarily) be decided by
651
+ handlers.
652
+ """
653
+ level = level_to_number(level)
654
+ if logger.getEffectiveLevel() > level:
655
+ logger.setLevel(level)
656
+
657
+
658
+ def find_defined_levels():
659
+ """
660
+ Find the defined logging levels.
661
+
662
+ :returns: A dictionary with level names as keys and integers as values.
663
+
664
+ Here's what the result looks like by default (when
665
+ no custom levels or level names have been defined):
666
+
667
+ >>> find_defined_levels()
668
+ {'NOTSET': 0,
669
+ 'DEBUG': 10,
670
+ 'INFO': 20,
671
+ 'WARN': 30,
672
+ 'WARNING': 30,
673
+ 'ERROR': 40,
674
+ 'FATAL': 50,
675
+ 'CRITICAL': 50}
676
+ """
677
+ defined_levels = {}
678
+ for name in dir(logging):
679
+ if name.isupper():
680
+ value = getattr(logging, name)
681
+ if isinstance(value, int):
682
+ defined_levels[name] = value
683
+ return defined_levels
684
+
685
+
686
+ def level_to_number(value):
687
+ """
688
+ Coerce a logging level name to a number.
689
+
690
+ :param value: A logging level (integer or string).
691
+ :returns: The number of the log level (an integer).
692
+
693
+ This function translates log level names into their numeric values..
694
+ """
695
+ if is_string(value):
696
+ try:
697
+ defined_levels = find_defined_levels()
698
+ value = defined_levels[value.upper()]
699
+ except KeyError:
700
+ # Don't fail on unsupported log levels.
701
+ value = DEFAULT_LOG_LEVEL
702
+ return value
703
+
704
+
705
+ def find_level_aliases():
706
+ """
707
+ Find log level names which are aliases of each other.
708
+
709
+ :returns: A dictionary that maps aliases to their canonical name.
710
+
711
+ .. note:: Canonical names are chosen to be the alias with the longest
712
+ string length so that e.g. ``WARN`` is an alias for ``WARNING``
713
+ instead of the other way around.
714
+
715
+ Here's what the result looks like by default (when
716
+ no custom levels or level names have been defined):
717
+
718
+ >>> from coloredlogs import find_level_aliases
719
+ >>> find_level_aliases()
720
+ {'WARN': 'WARNING', 'FATAL': 'CRITICAL'}
721
+ """
722
+ mapping = collections.defaultdict(list)
723
+ for name, value in find_defined_levels().items():
724
+ mapping[value].append(name)
725
+ aliases = {}
726
+ for value, names in mapping.items():
727
+ if len(names) > 1:
728
+ names = sorted(names, key=lambda n: len(n))
729
+ canonical_name = names.pop()
730
+ for alias in names:
731
+ aliases[alias] = canonical_name
732
+ return aliases
733
+
734
+
735
+ def parse_encoded_styles(text, normalize_key=None):
736
+ """
737
+ Parse text styles encoded in a string into a nested data structure.
738
+
739
+ :param text: The encoded styles (a string).
740
+ :returns: A dictionary in the structure of the :data:`DEFAULT_FIELD_STYLES`
741
+ and :data:`DEFAULT_LEVEL_STYLES` dictionaries.
742
+
743
+ Here's an example of how this function works:
744
+
745
+ >>> from coloredlogs import parse_encoded_styles
746
+ >>> from pprint import pprint
747
+ >>> encoded_styles = 'debug=green;warning=yellow;error=red;critical=red,bold'
748
+ >>> pprint(parse_encoded_styles(encoded_styles))
749
+ {'debug': {'color': 'green'},
750
+ 'warning': {'color': 'yellow'},
751
+ 'error': {'color': 'red'},
752
+ 'critical': {'bold': True, 'color': 'red'}}
753
+ """
754
+ parsed_styles = {}
755
+ for assignment in split(text, ';'):
756
+ name, _, styles = assignment.partition('=')
757
+ target = parsed_styles.setdefault(name, {})
758
+ for token in split(styles, ','):
759
+ # When this code was originally written, setting background colors
760
+ # wasn't supported yet, so there was no need to disambiguate
761
+ # between the text color and background color. This explains why
762
+ # a color name or number implies setting the text color (for
763
+ # backwards compatibility).
764
+ if token.isdigit():
765
+ target['color'] = int(token)
766
+ elif token in ANSI_COLOR_CODES:
767
+ target['color'] = token
768
+ elif '=' in token:
769
+ name, _, value = token.partition('=')
770
+ if name in ('color', 'background'):
771
+ if value.isdigit():
772
+ target[name] = int(value)
773
+ elif value in ANSI_COLOR_CODES:
774
+ target[name] = value
775
+ else:
776
+ target[token] = True
777
+ return parsed_styles
778
+
779
+
780
+ def find_hostname(use_chroot=True):
781
+ """
782
+ Find the host name to include in log messages.
783
+
784
+ :param use_chroot: Use the name of the chroot when inside a chroot?
785
+ (boolean, defaults to :data:`True`)
786
+ :returns: A suitable host name (a string).
787
+
788
+ Looks for :data:`CHROOT_FILES` that have a nonempty first line (taken to be
789
+ the chroot name). If none are found then :func:`socket.gethostname()` is
790
+ used as a fall back.
791
+ """
792
+ for chroot_file in CHROOT_FILES:
793
+ try:
794
+ with open(chroot_file) as handle:
795
+ first_line = next(handle)
796
+ name = first_line.strip()
797
+ if name:
798
+ return name
799
+ except Exception:
800
+ pass
801
+ return socket.gethostname()
802
+
803
+
804
+ def find_program_name():
805
+ """
806
+ Select a suitable program name to embed in log messages.
807
+
808
+ :returns: One of the following strings (in decreasing order of preference):
809
+
810
+ 1. The base name of the currently running Python program or
811
+ script (based on the value at index zero of :data:`sys.argv`).
812
+ 2. The base name of the Python executable (based on
813
+ :data:`sys.executable`).
814
+ 3. The string 'python'.
815
+ """
816
+ # Gotcha: sys.argv[0] is '-c' if Python is started with the -c option.
817
+ return ((os.path.basename(sys.argv[0]) if sys.argv and sys.argv[0] != '-c' else '')
818
+ or (os.path.basename(sys.executable) if sys.executable else '')
819
+ or 'python')
820
+
821
+
822
+ def find_username():
823
+ """
824
+ Find the username to include in log messages.
825
+
826
+ :returns: A suitable username (a string).
827
+
828
+ On UNIX systems this uses the :mod:`pwd` module which means ``root`` will
829
+ be reported when :man:`sudo` is used (as it should). If this fails (for
830
+ example on Windows) then :func:`getpass.getuser()` is used as a fall back.
831
+ """
832
+ try:
833
+ import pwd
834
+ uid = os.getuid()
835
+ entry = pwd.getpwuid(uid)
836
+ return entry.pw_name
837
+ except Exception:
838
+ import getpass
839
+ return getpass.getuser()
840
+
841
+
842
+ def replace_handler(logger, match_handler, reconfigure):
843
+ """
844
+ Prepare to replace a handler.
845
+
846
+ :param logger: Refer to :func:`find_handler()`.
847
+ :param match_handler: Refer to :func:`find_handler()`.
848
+ :param reconfigure: :data:`True` if an existing handler should be replaced,
849
+ :data:`False` otherwise.
850
+ :returns: A tuple of two values:
851
+
852
+ 1. The matched :class:`~logging.Handler` object or :data:`None`
853
+ if no handler was matched.
854
+ 2. The :class:`~logging.Logger` to which the matched handler was
855
+ attached or the logger given to :func:`replace_handler()`.
856
+ """
857
+ handler, other_logger = find_handler(logger, match_handler)
858
+ if handler and other_logger and reconfigure:
859
+ # Remove the existing handler from the logger that its attached to
860
+ # so that we can install a new handler that behaves differently.
861
+ other_logger.removeHandler(handler)
862
+ # Switch to the logger that the existing handler was attached to so
863
+ # that reconfiguration doesn't narrow the scope of logging.
864
+ logger = other_logger
865
+ return handler, logger
866
+
867
+
868
+ def find_handler(logger, match_handler):
869
+ """
870
+ Find a (specific type of) handler in the propagation tree of a logger.
871
+
872
+ :param logger: The logger to check (a :class:`~logging.Logger` object).
873
+ :param match_handler: A callable that receives a :class:`~logging.Handler`
874
+ object and returns :data:`True` to match a handler or
875
+ :data:`False` to skip that handler and continue
876
+ searching for a match.
877
+ :returns: A tuple of two values:
878
+
879
+ 1. The matched :class:`~logging.Handler` object or :data:`None`
880
+ if no handler was matched.
881
+ 2. The :class:`~logging.Logger` object to which the handler is
882
+ attached or :data:`None` if no handler was matched.
883
+
884
+ This function finds a logging handler (of the given type) attached to a
885
+ logger or one of its parents (see :func:`walk_propagation_tree()`). It uses
886
+ the undocumented :class:`~logging.Logger.handlers` attribute to find
887
+ handlers attached to a logger, however it won't raise an exception if the
888
+ attribute isn't available. The advantages of this approach are:
889
+
890
+ - This works regardless of whether :mod:`coloredlogs` attached the handler
891
+ or other Python code attached the handler.
892
+
893
+ - This will correctly recognize the situation where the given logger has no
894
+ handlers but :attr:`~logging.Logger.propagate` is enabled and the logger
895
+ has a parent logger that does have a handler attached.
896
+ """
897
+ for logger in walk_propagation_tree(logger):
898
+ for handler in getattr(logger, 'handlers', []):
899
+ if match_handler(handler):
900
+ return handler, logger
901
+ return None, None
902
+
903
+
904
+ def match_stream_handler(handler, streams=[]):
905
+ """
906
+ Identify stream handlers writing to the given streams(s).
907
+
908
+ :param handler: The :class:`~logging.Handler` class to check.
909
+ :param streams: A sequence of streams to match (defaults to matching
910
+ :data:`~sys.stdout` and :data:`~sys.stderr`).
911
+ :returns: :data:`True` if the handler is a :class:`~logging.StreamHandler`
912
+ logging to the given stream(s), :data:`False` otherwise.
913
+
914
+ This function can be used as a callback for :func:`find_handler()`.
915
+ """
916
+ return (isinstance(handler, logging.StreamHandler)
917
+ and getattr(handler, 'stream') in (streams or (sys.stdout, sys.stderr)))
918
+
919
+
920
+ def walk_propagation_tree(logger):
921
+ """
922
+ Walk through the propagation hierarchy of the given logger.
923
+
924
+ :param logger: The logger whose hierarchy to walk (a
925
+ :class:`~logging.Logger` object).
926
+ :returns: A generator of :class:`~logging.Logger` objects.
927
+
928
+ .. note:: This uses the undocumented :class:`logging.Logger.parent`
929
+ attribute to find higher level loggers, however it won't
930
+ raise an exception if the attribute isn't available.
931
+ """
932
+ while isinstance(logger, logging.Logger):
933
+ # Yield the logger to our caller.
934
+ yield logger
935
+ # Check if the logger has propagation enabled.
936
+ if logger.propagate:
937
+ # Continue with the parent logger. We use getattr() because the
938
+ # `parent' attribute isn't documented so properly speaking we
939
+ # shouldn't break if it's not available.
940
+ logger = getattr(logger, 'parent', None)
941
+ else:
942
+ # The propagation chain stops here.
943
+ logger = None
944
+
945
+
946
+ class BasicFormatter(logging.Formatter):
947
+
948
+ """
949
+ Log :class:`~logging.Formatter` that supports ``%f`` for millisecond formatting.
950
+
951
+ This class extends :class:`~logging.Formatter` to enable the use of ``%f``
952
+ for millisecond formatting in date/time strings, to allow for the type of
953
+ flexibility requested in issue `#45`_.
954
+
955
+ .. _#45: https://github.com/xolox/python-coloredlogs/issues/45
956
+ """
957
+
958
+ def formatTime(self, record, datefmt=None):
959
+ """
960
+ Format the date/time of a log record.
961
+
962
+ :param record: A :class:`~logging.LogRecord` object.
963
+ :param datefmt: A date/time format string (defaults to :data:`DEFAULT_DATE_FORMAT`).
964
+ :returns: The formatted date/time (a string).
965
+
966
+ This method overrides :func:`~logging.Formatter.formatTime()` to set
967
+ `datefmt` to :data:`DEFAULT_DATE_FORMAT` when the caller hasn't
968
+ specified a date format.
969
+
970
+ When `datefmt` contains the token ``%f`` it will be replaced by the
971
+ value of ``%(msecs)03d`` (refer to issue `#45`_ for use cases).
972
+ """
973
+ # The default value of the following argument is defined here so
974
+ # that Sphinx doesn't embed the default value in the generated
975
+ # documentation (because the result is awkward to read).
976
+ datefmt = datefmt or DEFAULT_DATE_FORMAT
977
+ # Replace %f with the value of %(msecs)03d.
978
+ if '%f' in datefmt:
979
+ datefmt = datefmt.replace('%f', '%03d' % record.msecs)
980
+ # Delegate the actual date/time formatting to the base formatter.
981
+ return logging.Formatter.formatTime(self, record, datefmt)
982
+
983
+
984
+ class ColoredFormatter(BasicFormatter):
985
+
986
+ """
987
+ Log :class:`~logging.Formatter` that uses `ANSI escape sequences`_ to create colored logs.
988
+
989
+ :class:`ColoredFormatter` inherits from :class:`BasicFormatter` to enable
990
+ the use of ``%f`` for millisecond formatting in date/time strings.
991
+
992
+ .. note:: If you want to use :class:`ColoredFormatter` on Windows then you
993
+ need to call :func:`~humanfriendly.terminal.enable_ansi_support()`.
994
+ This is done for you when you call :func:`coloredlogs.install()`.
995
+ """
996
+
997
+ def __init__(self, fmt=None, datefmt=None, style=DEFAULT_FORMAT_STYLE, level_styles=None, field_styles=None):
998
+ """
999
+ Initialize a :class:`ColoredFormatter` object.
1000
+
1001
+ :param fmt: A log format string (defaults to :data:`DEFAULT_LOG_FORMAT`).
1002
+ :param datefmt: A date/time format string (defaults to :data:`None`,
1003
+ but see the documentation of
1004
+ :func:`BasicFormatter.formatTime()`).
1005
+ :param style: One of the characters ``%``, ``{`` or ``$`` (defaults to
1006
+ :data:`DEFAULT_FORMAT_STYLE`)
1007
+ :param level_styles: A dictionary with custom level styles
1008
+ (defaults to :data:`DEFAULT_LEVEL_STYLES`).
1009
+ :param field_styles: A dictionary with custom field styles
1010
+ (defaults to :data:`DEFAULT_FIELD_STYLES`).
1011
+ :raises: Refer to :func:`check_style()`.
1012
+
1013
+ This initializer uses :func:`colorize_format()` to inject ANSI escape
1014
+ sequences in the log format string before it is passed to the
1015
+ initializer of the base class.
1016
+ """
1017
+ self.nn = NameNormalizer()
1018
+ # The default values of the following arguments are defined here so
1019
+ # that Sphinx doesn't embed the default values in the generated
1020
+ # documentation (because the result is awkward to read).
1021
+ fmt = fmt or DEFAULT_LOG_FORMAT
1022
+ self.level_styles = self.nn.normalize_keys(DEFAULT_LEVEL_STYLES if level_styles is None else level_styles)
1023
+ self.field_styles = self.nn.normalize_keys(DEFAULT_FIELD_STYLES if field_styles is None else field_styles)
1024
+ # Rewrite the format string to inject ANSI escape sequences.
1025
+ kw = dict(fmt=self.colorize_format(fmt, style), datefmt=datefmt)
1026
+ # If we were given a non-default logging format style we pass it on
1027
+ # to our superclass. At this point check_style() will have already
1028
+ # complained that the use of alternative logging format styles
1029
+ # requires Python 3.2 or newer.
1030
+ if style != DEFAULT_FORMAT_STYLE:
1031
+ kw['style'] = style
1032
+ # Initialize the superclass with the rewritten format string.
1033
+ logging.Formatter.__init__(self, **kw)
1034
+
1035
+ def colorize_format(self, fmt, style=DEFAULT_FORMAT_STYLE):
1036
+ """
1037
+ Rewrite a logging format string to inject ANSI escape sequences.
1038
+
1039
+ :param fmt: The log format string.
1040
+ :param style: One of the characters ``%``, ``{`` or ``$`` (defaults to
1041
+ :data:`DEFAULT_FORMAT_STYLE`).
1042
+ :returns: The logging format string with ANSI escape sequences.
1043
+
1044
+ This method takes a logging format string like the ones you give to
1045
+ :class:`logging.Formatter` and processes it as follows:
1046
+
1047
+ 1. First the logging format string is separated into formatting
1048
+ directives versus surrounding text (according to the given `style`).
1049
+
1050
+ 2. Then formatting directives and surrounding text are grouped
1051
+ based on whitespace delimiters (in the surrounding text).
1052
+
1053
+ 3. For each group styling is selected as follows:
1054
+
1055
+ 1. If the group contains a single formatting directive that has
1056
+ a style defined then the whole group is styled accordingly.
1057
+
1058
+ 2. If the group contains multiple formatting directives that
1059
+ have styles defined then each formatting directive is styled
1060
+ individually and surrounding text isn't styled.
1061
+
1062
+ As an example consider the default log format (:data:`DEFAULT_LOG_FORMAT`)::
1063
+
1064
+ %(asctime)s %(hostname)s %(name)s[%(process)d] %(levelname)s %(message)s
1065
+
1066
+ The default field styles (:data:`DEFAULT_FIELD_STYLES`) define a style for the
1067
+ `name` field but not for the `process` field, however because both fields
1068
+ are part of the same whitespace delimited token they'll be highlighted
1069
+ together in the style defined for the `name` field.
1070
+ """
1071
+ result = []
1072
+ parser = FormatStringParser(style=style)
1073
+ for group in parser.get_grouped_pairs(fmt):
1074
+ applicable_styles = [self.nn.get(self.field_styles, token.name) for token in group if token.name]
1075
+ if sum(map(bool, applicable_styles)) == 1:
1076
+ # If exactly one (1) field style is available for the group of
1077
+ # tokens then all of the tokens will be styled the same way.
1078
+ # This provides a limited form of backwards compatibility with
1079
+ # the (intended) behavior of coloredlogs before the release of
1080
+ # version 10.
1081
+ result.append(ansi_wrap(
1082
+ ''.join(token.text for token in group),
1083
+ **next(s for s in applicable_styles if s)
1084
+ ))
1085
+ else:
1086
+ for token in group:
1087
+ text = token.text
1088
+ if token.name:
1089
+ field_styles = self.nn.get(self.field_styles, token.name)
1090
+ if field_styles:
1091
+ text = ansi_wrap(text, **field_styles)
1092
+ result.append(text)
1093
+ return ''.join(result)
1094
+
1095
+ def format(self, record):
1096
+ """
1097
+ Apply level-specific styling to log records.
1098
+
1099
+ :param record: A :class:`~logging.LogRecord` object.
1100
+ :returns: The result of :func:`logging.Formatter.format()`.
1101
+
1102
+ This method injects ANSI escape sequences that are specific to the
1103
+ level of each log record (because such logic cannot be expressed in the
1104
+ syntax of a log format string). It works by making a copy of the log
1105
+ record, changing the `msg` field inside the copy and passing the copy
1106
+ into the :func:`~logging.Formatter.format()` method of the base
1107
+ class.
1108
+ """
1109
+ style = self.nn.get(self.level_styles, record.levelname)
1110
+ # After the introduction of the `Empty' class it was reported in issue
1111
+ # 33 that format() can be called when `Empty' has already been garbage
1112
+ # collected. This explains the (otherwise rather out of place) `Empty
1113
+ # is not None' check in the following `if' statement. The reasoning
1114
+ # here is that it's much better to log a message without formatting
1115
+ # then to raise an exception ;-).
1116
+ #
1117
+ # For more details refer to issue 33 on GitHub:
1118
+ # https://github.com/xolox/python-coloredlogs/issues/33
1119
+ if style and Empty is not None:
1120
+ # Due to the way that Python's logging module is structured and
1121
+ # documented the only (IMHO) clean way to customize its behavior is
1122
+ # to change incoming LogRecord objects before they get to the base
1123
+ # formatter. However we don't want to break other formatters and
1124
+ # handlers, so we copy the log record.
1125
+ #
1126
+ # In the past this used copy.copy() but as reported in issue 29
1127
+ # (which is reproducible) this can cause deadlocks. The following
1128
+ # Python voodoo is intended to accomplish the same thing as
1129
+ # copy.copy() without all of the generalization and overhead that
1130
+ # we don't need for our -very limited- use case.
1131
+ #
1132
+ # For more details refer to issue 29 on GitHub:
1133
+ # https://github.com/xolox/python-coloredlogs/issues/29
1134
+ copy = Empty()
1135
+ copy.__class__ = record.__class__
1136
+ copy.__dict__.update(record.__dict__)
1137
+ copy.msg = ansi_wrap(coerce_string(record.msg), **style)
1138
+ record = copy
1139
+ # Delegate the remaining formatting to the base formatter.
1140
+ return logging.Formatter.format(self, record)
1141
+
1142
+
1143
+ class Empty(object):
1144
+ """An empty class used to copy :class:`~logging.LogRecord` objects without reinitializing them."""
1145
+
1146
+
1147
+ class HostNameFilter(logging.Filter):
1148
+
1149
+ """
1150
+ Log filter to enable the ``%(hostname)s`` format.
1151
+
1152
+ Python's :mod:`logging` module doesn't expose the system's host name while
1153
+ I consider this to be a valuable addition. Fortunately it's very easy to
1154
+ expose additional fields in format strings: :func:`filter()` simply sets
1155
+ the ``hostname`` attribute of each :class:`~logging.LogRecord` object it
1156
+ receives and this is enough to enable the use of the ``%(hostname)s``
1157
+ expression in format strings.
1158
+
1159
+ You can install this log filter as follows::
1160
+
1161
+ >>> import coloredlogs, logging
1162
+ >>> handler = logging.StreamHandler()
1163
+ >>> handler.addFilter(coloredlogs.HostNameFilter())
1164
+ >>> handler.setFormatter(logging.Formatter('[%(hostname)s] %(message)s'))
1165
+ >>> logger = logging.getLogger()
1166
+ >>> logger.addHandler(handler)
1167
+ >>> logger.setLevel(logging.INFO)
1168
+ >>> logger.info("Does it work?")
1169
+ [peter-macbook] Does it work?
1170
+
1171
+ Of course :func:`coloredlogs.install()` does all of this for you :-).
1172
+ """
1173
+
1174
+ @classmethod
1175
+ def install(cls, handler, fmt=None, use_chroot=True, style=DEFAULT_FORMAT_STYLE):
1176
+ """
1177
+ Install the :class:`HostNameFilter` on a log handler (only if needed).
1178
+
1179
+ :param fmt: The log format string to check for ``%(hostname)``.
1180
+ :param style: One of the characters ``%``, ``{`` or ``$`` (defaults to
1181
+ :data:`DEFAULT_FORMAT_STYLE`).
1182
+ :param handler: The logging handler on which to install the filter.
1183
+ :param use_chroot: Refer to :func:`find_hostname()`.
1184
+
1185
+ If `fmt` is given the filter will only be installed if `fmt` uses the
1186
+ ``hostname`` field. If `fmt` is not given the filter is installed
1187
+ unconditionally.
1188
+ """
1189
+ if fmt:
1190
+ parser = FormatStringParser(style=style)
1191
+ if not parser.contains_field(fmt, 'hostname'):
1192
+ return
1193
+ handler.addFilter(cls(use_chroot))
1194
+
1195
+ def __init__(self, use_chroot=True):
1196
+ """
1197
+ Initialize a :class:`HostNameFilter` object.
1198
+
1199
+ :param use_chroot: Refer to :func:`find_hostname()`.
1200
+ """
1201
+ self.hostname = find_hostname(use_chroot)
1202
+
1203
+ def filter(self, record):
1204
+ """Set each :class:`~logging.LogRecord`'s `hostname` field."""
1205
+ # Modify the record.
1206
+ record.hostname = self.hostname
1207
+ # Don't filter the record.
1208
+ return 1
1209
+
1210
+
1211
+ class ProgramNameFilter(logging.Filter):
1212
+
1213
+ """
1214
+ Log filter to enable the ``%(programname)s`` format.
1215
+
1216
+ Python's :mod:`logging` module doesn't expose the name of the currently
1217
+ running program while I consider this to be a useful addition. Fortunately
1218
+ it's very easy to expose additional fields in format strings:
1219
+ :func:`filter()` simply sets the ``programname`` attribute of each
1220
+ :class:`~logging.LogRecord` object it receives and this is enough to enable
1221
+ the use of the ``%(programname)s`` expression in format strings.
1222
+
1223
+ Refer to :class:`HostNameFilter` for an example of how to manually install
1224
+ these log filters.
1225
+ """
1226
+
1227
+ @classmethod
1228
+ def install(cls, handler, fmt, programname=None, style=DEFAULT_FORMAT_STYLE):
1229
+ """
1230
+ Install the :class:`ProgramNameFilter` (only if needed).
1231
+
1232
+ :param fmt: The log format string to check for ``%(programname)``.
1233
+ :param style: One of the characters ``%``, ``{`` or ``$`` (defaults to
1234
+ :data:`DEFAULT_FORMAT_STYLE`).
1235
+ :param handler: The logging handler on which to install the filter.
1236
+ :param programname: Refer to :func:`__init__()`.
1237
+
1238
+ If `fmt` is given the filter will only be installed if `fmt` uses the
1239
+ ``programname`` field. If `fmt` is not given the filter is installed
1240
+ unconditionally.
1241
+ """
1242
+ if fmt:
1243
+ parser = FormatStringParser(style=style)
1244
+ if not parser.contains_field(fmt, 'programname'):
1245
+ return
1246
+ handler.addFilter(cls(programname))
1247
+
1248
+ def __init__(self, programname=None):
1249
+ """
1250
+ Initialize a :class:`ProgramNameFilter` object.
1251
+
1252
+ :param programname: The program name to use (defaults to the result of
1253
+ :func:`find_program_name()`).
1254
+ """
1255
+ self.programname = programname or find_program_name()
1256
+
1257
+ def filter(self, record):
1258
+ """Set each :class:`~logging.LogRecord`'s `programname` field."""
1259
+ # Modify the record.
1260
+ record.programname = self.programname
1261
+ # Don't filter the record.
1262
+ return 1
1263
+
1264
+
1265
+ class UserNameFilter(logging.Filter):
1266
+
1267
+ """
1268
+ Log filter to enable the ``%(username)s`` format.
1269
+
1270
+ Python's :mod:`logging` module doesn't expose the username of the currently
1271
+ logged in user as requested in `#76`_. Given that :class:`HostNameFilter`
1272
+ and :class:`ProgramNameFilter` are already provided by `coloredlogs` it
1273
+ made sense to provide :class:`UserNameFilter` as well.
1274
+
1275
+ Refer to :class:`HostNameFilter` for an example of how to manually install
1276
+ these log filters.
1277
+
1278
+ .. _#76: https://github.com/xolox/python-coloredlogs/issues/76
1279
+ """
1280
+
1281
+ @classmethod
1282
+ def install(cls, handler, fmt, username=None, style=DEFAULT_FORMAT_STYLE):
1283
+ """
1284
+ Install the :class:`UserNameFilter` (only if needed).
1285
+
1286
+ :param fmt: The log format string to check for ``%(username)``.
1287
+ :param style: One of the characters ``%``, ``{`` or ``$`` (defaults to
1288
+ :data:`DEFAULT_FORMAT_STYLE`).
1289
+ :param handler: The logging handler on which to install the filter.
1290
+ :param username: Refer to :func:`__init__()`.
1291
+
1292
+ If `fmt` is given the filter will only be installed if `fmt` uses the
1293
+ ``username`` field. If `fmt` is not given the filter is installed
1294
+ unconditionally.
1295
+ """
1296
+ if fmt:
1297
+ parser = FormatStringParser(style=style)
1298
+ if not parser.contains_field(fmt, 'username'):
1299
+ return
1300
+ handler.addFilter(cls(username))
1301
+
1302
+ def __init__(self, username=None):
1303
+ """
1304
+ Initialize a :class:`UserNameFilter` object.
1305
+
1306
+ :param username: The username to use (defaults to the
1307
+ result of :func:`find_username()`).
1308
+ """
1309
+ self.username = username or find_username()
1310
+
1311
+ def filter(self, record):
1312
+ """Set each :class:`~logging.LogRecord`'s `username` field."""
1313
+ # Modify the record.
1314
+ record.username = self.username
1315
+ # Don't filter the record.
1316
+ return 1
1317
+
1318
+
1319
+ class StandardErrorHandler(logging.StreamHandler):
1320
+
1321
+ """
1322
+ A :class:`~logging.StreamHandler` that gets the value of :data:`sys.stderr` for each log message.
1323
+
1324
+ The :class:`StandardErrorHandler` class enables `monkey patching of
1325
+ sys.stderr <https://github.com/xolox/python-coloredlogs/pull/31>`_. It's
1326
+ basically the same as the ``logging._StderrHandler`` class present in
1327
+ Python 3 but it will be available regardless of Python version. This
1328
+ handler is used by :func:`coloredlogs.install()` to improve compatibility
1329
+ with the Python standard library.
1330
+ """
1331
+
1332
+ def __init__(self, level=logging.NOTSET):
1333
+ """Initialize a :class:`StandardErrorHandler` object."""
1334
+ logging.Handler.__init__(self, level)
1335
+
1336
+ @property
1337
+ def stream(self):
1338
+ """Get the value of :data:`sys.stderr` (a file-like object)."""
1339
+ return sys.stderr
1340
+
1341
+
1342
+ class FormatStringParser(object):
1343
+
1344
+ """
1345
+ Shallow logging format string parser.
1346
+
1347
+ This class enables introspection and manipulation of logging format strings
1348
+ in the three styles supported by the :mod:`logging` module starting from
1349
+ Python 3.2 (``%``, ``{`` and ``$``).
1350
+ """
1351
+
1352
+ def __init__(self, style=DEFAULT_FORMAT_STYLE):
1353
+ """
1354
+ Initialize a :class:`FormatStringParser` object.
1355
+
1356
+ :param style: One of the characters ``%``, ``{`` or ``$`` (defaults to
1357
+ :data:`DEFAULT_FORMAT_STYLE`).
1358
+ :raises: Refer to :func:`check_style()`.
1359
+ """
1360
+ self.style = check_style(style)
1361
+ self.capturing_pattern = FORMAT_STYLE_PATTERNS[style]
1362
+ # Remove the capture group around the mapping key / field name.
1363
+ self.raw_pattern = self.capturing_pattern.replace(r'(\w+)', r'\w+')
1364
+ # After removing the inner capture group we add an outer capture group
1365
+ # to make the pattern suitable for simple tokenization using re.split().
1366
+ self.tokenize_pattern = re.compile('(%s)' % self.raw_pattern, re.VERBOSE)
1367
+ # Compile a regular expression for finding field names.
1368
+ self.name_pattern = re.compile(self.capturing_pattern, re.VERBOSE)
1369
+
1370
+ def contains_field(self, format_string, field_name):
1371
+ """
1372
+ Get the field names referenced by a format string.
1373
+
1374
+ :param format_string: The logging format string.
1375
+ :returns: A list of strings with field names.
1376
+ """
1377
+ return field_name in self.get_field_names(format_string)
1378
+
1379
+ def get_field_names(self, format_string):
1380
+ """
1381
+ Get the field names referenced by a format string.
1382
+
1383
+ :param format_string: The logging format string.
1384
+ :returns: A list of strings with field names.
1385
+ """
1386
+ return self.name_pattern.findall(format_string)
1387
+
1388
+ def get_grouped_pairs(self, format_string):
1389
+ """
1390
+ Group the results of :func:`get_pairs()` separated by whitespace.
1391
+
1392
+ :param format_string: The logging format string.
1393
+ :returns: A list of lists of :class:`FormatStringToken` objects.
1394
+ """
1395
+ # Step 1: Split simple tokens (without a name) into
1396
+ # their whitespace parts and non-whitespace parts.
1397
+ separated = []
1398
+ pattern = re.compile(r'(\s+)')
1399
+ for token in self.get_pairs(format_string):
1400
+ if token.name:
1401
+ separated.append(token)
1402
+ else:
1403
+ separated.extend(
1404
+ FormatStringToken(name=None, text=text)
1405
+ for text in pattern.split(token.text) if text
1406
+ )
1407
+ # Step 2: Group tokens together based on whitespace.
1408
+ current_group = []
1409
+ grouped_pairs = []
1410
+ for token in separated:
1411
+ if token.text.isspace():
1412
+ if current_group:
1413
+ grouped_pairs.append(current_group)
1414
+ grouped_pairs.append([token])
1415
+ current_group = []
1416
+ else:
1417
+ current_group.append(token)
1418
+ if current_group:
1419
+ grouped_pairs.append(current_group)
1420
+ return grouped_pairs
1421
+
1422
+ def get_pairs(self, format_string):
1423
+ """
1424
+ Tokenize a logging format string and extract field names from tokens.
1425
+
1426
+ :param format_string: The logging format string.
1427
+ :returns: A generator of :class:`FormatStringToken` objects.
1428
+ """
1429
+ for token in self.get_tokens(format_string):
1430
+ match = self.name_pattern.search(token)
1431
+ name = match.group(1) if match else None
1432
+ yield FormatStringToken(name=name, text=token)
1433
+
1434
+ def get_pattern(self, field_name):
1435
+ """
1436
+ Get a regular expression to match a formatting directive that references the given field name.
1437
+
1438
+ :param field_name: The name of the field to match (a string).
1439
+ :returns: A compiled regular expression object.
1440
+ """
1441
+ return re.compile(self.raw_pattern.replace(r'\w+', field_name), re.VERBOSE)
1442
+
1443
+ def get_tokens(self, format_string):
1444
+ """
1445
+ Tokenize a logging format string.
1446
+
1447
+ :param format_string: The logging format string.
1448
+ :returns: A list of strings with formatting directives separated from surrounding text.
1449
+ """
1450
+ return [t for t in self.tokenize_pattern.split(format_string) if t]
1451
+
1452
+
1453
+ class FormatStringToken(collections.namedtuple('FormatStringToken', 'text, name')):
1454
+
1455
+ """
1456
+ A named tuple for the results of :func:`FormatStringParser.get_pairs()`.
1457
+
1458
+ .. attribute:: name
1459
+
1460
+ The field name referenced in `text` (a string). If `text` doesn't
1461
+ contain a formatting directive this will be :data:`None`.
1462
+
1463
+ .. attribute:: text
1464
+
1465
+ The text extracted from the logging format string (a string).
1466
+ """
1467
+
1468
+
1469
+ class NameNormalizer(object):
1470
+
1471
+ """Responsible for normalizing field and level names."""
1472
+
1473
+ def __init__(self):
1474
+ """Initialize a :class:`NameNormalizer` object."""
1475
+ self.aliases = {k.lower(): v.lower() for k, v in find_level_aliases().items()}
1476
+
1477
+ def normalize_name(self, name):
1478
+ """
1479
+ Normalize a field or level name.
1480
+
1481
+ :param name: The field or level name (a string).
1482
+ :returns: The normalized name (a string).
1483
+
1484
+ Transforms all strings to lowercase and resolves level name aliases
1485
+ (refer to :func:`find_level_aliases()`) to their canonical name:
1486
+
1487
+ >>> from coloredlogs import NameNormalizer
1488
+ >>> from humanfriendly import format_table
1489
+ >>> nn = NameNormalizer()
1490
+ >>> sample_names = ['DEBUG', 'INFO', 'WARN', 'WARNING', 'ERROR', 'FATAL', 'CRITICAL']
1491
+ >>> print(format_table([(n, nn.normalize_name(n)) for n in sample_names]))
1492
+ -----------------------
1493
+ | DEBUG | debug |
1494
+ | INFO | info |
1495
+ | WARN | warning |
1496
+ | WARNING | warning |
1497
+ | ERROR | error |
1498
+ | FATAL | critical |
1499
+ | CRITICAL | critical |
1500
+ -----------------------
1501
+ """
1502
+ name = name.lower()
1503
+ if name in self.aliases:
1504
+ name = self.aliases[name]
1505
+ return name
1506
+
1507
+ def normalize_keys(self, value):
1508
+ """
1509
+ Normalize the keys of a dictionary using :func:`normalize_name()`.
1510
+
1511
+ :param value: The dictionary to normalize.
1512
+ :returns: A dictionary with normalized keys.
1513
+ """
1514
+ return {self.normalize_name(k): v for k, v in value.items()}
1515
+
1516
+ def get(self, normalized_dict, name):
1517
+ """
1518
+ Get a value from a dictionary after normalizing the key.
1519
+
1520
+ :param normalized_dict: A dictionary produced by :func:`normalize_keys()`.
1521
+ :param name: A key to normalize and get from the dictionary.
1522
+ :returns: The value of the normalized key (if any).
1523
+ """
1524
+ return normalized_dict.get(self.normalize_name(name))
python_embeded/Lib/site-packages/coloredlogs/cli.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Command line interface for the coloredlogs package.
2
+ #
3
+ # Author: Peter Odding <peter@peterodding.com>
4
+ # Last Change: December 15, 2017
5
+ # URL: https://coloredlogs.readthedocs.io
6
+
7
+ """
8
+ Usage: coloredlogs [OPTIONS] [ARGS]
9
+
10
+ The coloredlogs program provides a simple command line interface for the Python
11
+ package by the same name.
12
+
13
+ Supported options:
14
+
15
+ -c, --convert, --to-html
16
+
17
+ Capture the output of an external command (given by the positional
18
+ arguments) and convert ANSI escape sequences in the output to HTML.
19
+
20
+ If the `coloredlogs' program is attached to an interactive terminal it will
21
+ write the generated HTML to a temporary file and open that file in a web
22
+ browser, otherwise the generated HTML will be written to standard output.
23
+
24
+ This requires the `script' program to fake the external command into
25
+ thinking that it's attached to an interactive terminal (in order to enable
26
+ output of ANSI escape sequences).
27
+
28
+ If the command didn't produce any output then no HTML will be produced on
29
+ standard output, this is to avoid empty emails from cron jobs.
30
+
31
+ -d, --demo
32
+
33
+ Perform a simple demonstration of the coloredlogs package to show the
34
+ colored logging on an interactive terminal.
35
+
36
+ -h, --help
37
+
38
+ Show this message and exit.
39
+ """
40
+
41
+ # Standard library modules.
42
+ import functools
43
+ import getopt
44
+ import logging
45
+ import sys
46
+ import tempfile
47
+ import webbrowser
48
+
49
+ # External dependencies.
50
+ from humanfriendly.terminal import connected_to_terminal, output, usage, warning
51
+
52
+ # Modules included in our package.
53
+ from coloredlogs.converter import capture, convert
54
+ from coloredlogs.demo import demonstrate_colored_logging
55
+
56
+ # Initialize a logger for this module.
57
+ logger = logging.getLogger(__name__)
58
+
59
+
60
+ def main():
61
+ """Command line interface for the ``coloredlogs`` program."""
62
+ actions = []
63
+ try:
64
+ # Parse the command line arguments.
65
+ options, arguments = getopt.getopt(sys.argv[1:], 'cdh', [
66
+ 'convert', 'to-html', 'demo', 'help',
67
+ ])
68
+ # Map command line options to actions.
69
+ for option, value in options:
70
+ if option in ('-c', '--convert', '--to-html'):
71
+ actions.append(functools.partial(convert_command_output, *arguments))
72
+ arguments = []
73
+ elif option in ('-d', '--demo'):
74
+ actions.append(demonstrate_colored_logging)
75
+ elif option in ('-h', '--help'):
76
+ usage(__doc__)
77
+ return
78
+ else:
79
+ assert False, "Programming error: Unhandled option!"
80
+ if not actions:
81
+ usage(__doc__)
82
+ return
83
+ except Exception as e:
84
+ warning("Error: %s", e)
85
+ sys.exit(1)
86
+ for function in actions:
87
+ function()
88
+
89
+
90
+ def convert_command_output(*command):
91
+ """
92
+ Command line interface for ``coloredlogs --to-html``.
93
+
94
+ Takes a command (and its arguments) and runs the program under ``script``
95
+ (emulating an interactive terminal), intercepts the output of the command
96
+ and converts ANSI escape sequences in the output to HTML.
97
+ """
98
+ captured_output = capture(command)
99
+ converted_output = convert(captured_output)
100
+ if connected_to_terminal():
101
+ fd, temporary_file = tempfile.mkstemp(suffix='.html')
102
+ with open(temporary_file, 'w') as handle:
103
+ handle.write(converted_output)
104
+ webbrowser.open(temporary_file)
105
+ elif captured_output and not captured_output.isspace():
106
+ output(converted_output)
python_embeded/Lib/site-packages/coloredlogs/demo.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Demonstration of the coloredlogs package.
2
+ #
3
+ # Author: Peter Odding <peter@peterodding.com>
4
+ # Last Change: January 14, 2018
5
+ # URL: https://coloredlogs.readthedocs.io
6
+
7
+ """A simple demonstration of the `coloredlogs` package."""
8
+
9
+ # Standard library modules.
10
+ import os
11
+ import time
12
+
13
+ # Modules included in our package.
14
+ import coloredlogs
15
+
16
+ # If my verbose logger is installed, we'll use that for the demo.
17
+ try:
18
+ from verboselogs import VerboseLogger as getLogger
19
+ except ImportError:
20
+ from logging import getLogger
21
+
22
+ # Initialize a logger for this module.
23
+ logger = getLogger(__name__)
24
+
25
+ DEMO_DELAY = float(os.environ.get('COLOREDLOGS_DEMO_DELAY', '1'))
26
+ """The number of seconds between each message emitted by :func:`demonstrate_colored_logging()`."""
27
+
28
+
29
+ def demonstrate_colored_logging():
30
+ """Interactively demonstrate the :mod:`coloredlogs` package."""
31
+ # Determine the available logging levels and order them by numeric value.
32
+ decorated_levels = []
33
+ defined_levels = coloredlogs.find_defined_levels()
34
+ normalizer = coloredlogs.NameNormalizer()
35
+ for name, level in defined_levels.items():
36
+ if name != 'NOTSET':
37
+ item = (level, normalizer.normalize_name(name))
38
+ if item not in decorated_levels:
39
+ decorated_levels.append(item)
40
+ ordered_levels = sorted(decorated_levels)
41
+ # Initialize colored output to the terminal, default to the most
42
+ # verbose logging level but enable the user the customize it.
43
+ coloredlogs.install(level=os.environ.get('COLOREDLOGS_LOG_LEVEL', ordered_levels[0][1]))
44
+ # Print some examples with different timestamps.
45
+ for level, name in ordered_levels:
46
+ log_method = getattr(logger, name, None)
47
+ if log_method:
48
+ log_method("message with level %s (%i)", name, level)
49
+ time.sleep(DEMO_DELAY)
python_embeded/Lib/site-packages/coloredlogs/syslog.py ADDED
@@ -0,0 +1,292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Easy to use system logging for Python's logging module.
2
+ #
3
+ # Author: Peter Odding <peter@peterodding.com>
4
+ # Last Change: December 10, 2020
5
+ # URL: https://coloredlogs.readthedocs.io
6
+
7
+ """
8
+ Easy to use UNIX system logging for Python's :mod:`logging` module.
9
+
10
+ Admittedly system logging has little to do with colored terminal output, however:
11
+
12
+ - The `coloredlogs` package is my attempt to do Python logging right and system
13
+ logging is an important part of that equation.
14
+
15
+ - I've seen a surprising number of quirks and mistakes in system logging done
16
+ in Python, for example including ``%(asctime)s`` in a format string (the
17
+ system logging daemon is responsible for adding timestamps and thus you end
18
+ up with duplicate timestamps that make the logs awful to read :-).
19
+
20
+ - The ``%(programname)s`` filter originated in my system logging code and I
21
+ wanted it in `coloredlogs` so the step to include this module wasn't that big.
22
+
23
+ - As a bonus this Python module now has a test suite and proper documentation.
24
+
25
+ So there :-P. Go take a look at :func:`enable_system_logging()`.
26
+ """
27
+
28
+ # Standard library modules.
29
+ import logging
30
+ import logging.handlers
31
+ import os
32
+ import socket
33
+ import sys
34
+
35
+ # External dependencies.
36
+ from humanfriendly import coerce_boolean
37
+ from humanfriendly.compat import on_macos, on_windows
38
+
39
+ # Modules included in our package.
40
+ from coloredlogs import (
41
+ DEFAULT_LOG_LEVEL,
42
+ ProgramNameFilter,
43
+ adjust_level,
44
+ find_program_name,
45
+ level_to_number,
46
+ replace_handler,
47
+ )
48
+
49
+ LOG_DEVICE_MACOSX = '/var/run/syslog'
50
+ """The pathname of the log device on Mac OS X (a string)."""
51
+
52
+ LOG_DEVICE_UNIX = '/dev/log'
53
+ """The pathname of the log device on Linux and most other UNIX systems (a string)."""
54
+
55
+ DEFAULT_LOG_FORMAT = '%(programname)s[%(process)d]: %(levelname)s %(message)s'
56
+ """
57
+ The default format for log messages sent to the system log (a string).
58
+
59
+ The ``%(programname)s`` format requires :class:`~coloredlogs.ProgramNameFilter`
60
+ but :func:`enable_system_logging()` takes care of this for you.
61
+
62
+ The ``name[pid]:`` construct (specifically the colon) in the format allows
63
+ rsyslogd_ to extract the ``$programname`` from each log message, which in turn
64
+ allows configuration files in ``/etc/rsyslog.d/*.conf`` to filter these log
65
+ messages to a separate log file (if the need arises).
66
+
67
+ .. _rsyslogd: https://en.wikipedia.org/wiki/Rsyslog
68
+ """
69
+
70
+ # Initialize a logger for this module.
71
+ logger = logging.getLogger(__name__)
72
+
73
+
74
+ class SystemLogging(object):
75
+
76
+ """Context manager to enable system logging."""
77
+
78
+ def __init__(self, *args, **kw):
79
+ """
80
+ Initialize a :class:`SystemLogging` object.
81
+
82
+ :param args: Positional arguments to :func:`enable_system_logging()`.
83
+ :param kw: Keyword arguments to :func:`enable_system_logging()`.
84
+ """
85
+ self.args = args
86
+ self.kw = kw
87
+ self.handler = None
88
+
89
+ def __enter__(self):
90
+ """Enable system logging when entering the context."""
91
+ if self.handler is None:
92
+ self.handler = enable_system_logging(*self.args, **self.kw)
93
+ return self.handler
94
+
95
+ def __exit__(self, exc_type=None, exc_value=None, traceback=None):
96
+ """
97
+ Disable system logging when leaving the context.
98
+
99
+ .. note:: If an exception is being handled when we leave the context a
100
+ warning message including traceback is logged *before* system
101
+ logging is disabled.
102
+ """
103
+ if self.handler is not None:
104
+ if exc_type is not None:
105
+ logger.warning("Disabling system logging due to unhandled exception!", exc_info=True)
106
+ (self.kw.get('logger') or logging.getLogger()).removeHandler(self.handler)
107
+ self.handler = None
108
+
109
+
110
+ def enable_system_logging(programname=None, fmt=None, logger=None, reconfigure=True, **kw):
111
+ """
112
+ Redirect :mod:`logging` messages to the system log (e.g. ``/var/log/syslog``).
113
+
114
+ :param programname: The program name to embed in log messages (a string, defaults
115
+ to the result of :func:`~coloredlogs.find_program_name()`).
116
+ :param fmt: The log format for system log messages (a string, defaults to
117
+ :data:`DEFAULT_LOG_FORMAT`).
118
+ :param logger: The logger to which the :class:`~logging.handlers.SysLogHandler`
119
+ should be connected (defaults to the root logger).
120
+ :param level: The logging level for the :class:`~logging.handlers.SysLogHandler`
121
+ (defaults to :data:`.DEFAULT_LOG_LEVEL`). This value is coerced
122
+ using :func:`~coloredlogs.level_to_number()`.
123
+ :param reconfigure: If :data:`True` (the default) multiple calls to
124
+ :func:`enable_system_logging()` will each override
125
+ the previous configuration.
126
+ :param kw: Refer to :func:`connect_to_syslog()`.
127
+ :returns: A :class:`~logging.handlers.SysLogHandler` object or
128
+ :data:`None`. If an existing handler is found and `reconfigure`
129
+ is :data:`False` the existing handler object is returned. If the
130
+ connection to the system logging daemon fails :data:`None` is
131
+ returned.
132
+
133
+ As of release 15.0 this function uses :func:`is_syslog_supported()` to
134
+ check whether system logging is supported and appropriate before it's
135
+ enabled.
136
+
137
+ .. note:: When the logger's effective level is too restrictive it is
138
+ relaxed (refer to `notes about log levels`_ for details).
139
+ """
140
+ # Check whether system logging is supported / appropriate.
141
+ if not is_syslog_supported():
142
+ return None
143
+ # Provide defaults for omitted arguments.
144
+ programname = programname or find_program_name()
145
+ logger = logger or logging.getLogger()
146
+ fmt = fmt or DEFAULT_LOG_FORMAT
147
+ level = level_to_number(kw.get('level', DEFAULT_LOG_LEVEL))
148
+ # Check whether system logging is already enabled.
149
+ handler, logger = replace_handler(logger, match_syslog_handler, reconfigure)
150
+ # Make sure reconfiguration is allowed or not relevant.
151
+ if not (handler and not reconfigure):
152
+ # Create a system logging handler.
153
+ handler = connect_to_syslog(**kw)
154
+ # Make sure the handler was successfully created.
155
+ if handler:
156
+ # Enable the use of %(programname)s.
157
+ ProgramNameFilter.install(handler=handler, fmt=fmt, programname=programname)
158
+ # Connect the formatter, handler and logger.
159
+ handler.setFormatter(logging.Formatter(fmt))
160
+ logger.addHandler(handler)
161
+ # Adjust the level of the selected logger.
162
+ adjust_level(logger, level)
163
+ return handler
164
+
165
+
166
+ def connect_to_syslog(address=None, facility=None, level=None):
167
+ """
168
+ Create a :class:`~logging.handlers.SysLogHandler`.
169
+
170
+ :param address: The device file or network address of the system logging
171
+ daemon (a string or tuple, defaults to the result of
172
+ :func:`find_syslog_address()`).
173
+ :param facility: Refer to :class:`~logging.handlers.SysLogHandler`.
174
+ Defaults to ``LOG_USER``.
175
+ :param level: The logging level for the :class:`~logging.handlers.SysLogHandler`
176
+ (defaults to :data:`.DEFAULT_LOG_LEVEL`). This value is coerced
177
+ using :func:`~coloredlogs.level_to_number()`.
178
+ :returns: A :class:`~logging.handlers.SysLogHandler` object or :data:`None` (if the
179
+ system logging daemon is unavailable).
180
+
181
+ The process of connecting to the system logging daemon goes as follows:
182
+
183
+ - The following two socket types are tried (in decreasing preference):
184
+
185
+ 1. :data:`~socket.SOCK_RAW` avoids truncation of log messages but may
186
+ not be supported.
187
+ 2. :data:`~socket.SOCK_STREAM` (TCP) supports longer messages than the
188
+ default (which is UDP).
189
+ """
190
+ if not address:
191
+ address = find_syslog_address()
192
+ if facility is None:
193
+ facility = logging.handlers.SysLogHandler.LOG_USER
194
+ if level is None:
195
+ level = DEFAULT_LOG_LEVEL
196
+ for socktype in socket.SOCK_RAW, socket.SOCK_STREAM, None:
197
+ kw = dict(facility=facility, address=address)
198
+ if socktype is not None:
199
+ kw['socktype'] = socktype
200
+ try:
201
+ handler = logging.handlers.SysLogHandler(**kw)
202
+ except IOError:
203
+ # IOError is a superclass of socket.error which can be raised if the system
204
+ # logging daemon is unavailable.
205
+ pass
206
+ else:
207
+ handler.setLevel(level_to_number(level))
208
+ return handler
209
+
210
+
211
+ def find_syslog_address():
212
+ """
213
+ Find the most suitable destination for system log messages.
214
+
215
+ :returns: The pathname of a log device (a string) or an address/port tuple as
216
+ supported by :class:`~logging.handlers.SysLogHandler`.
217
+
218
+ On Mac OS X this prefers :data:`LOG_DEVICE_MACOSX`, after that :data:`LOG_DEVICE_UNIX`
219
+ is checked for existence. If both of these device files don't exist the default used
220
+ by :class:`~logging.handlers.SysLogHandler` is returned.
221
+ """
222
+ if sys.platform == 'darwin' and os.path.exists(LOG_DEVICE_MACOSX):
223
+ return LOG_DEVICE_MACOSX
224
+ elif os.path.exists(LOG_DEVICE_UNIX):
225
+ return LOG_DEVICE_UNIX
226
+ else:
227
+ return 'localhost', logging.handlers.SYSLOG_UDP_PORT
228
+
229
+
230
+ def is_syslog_supported():
231
+ """
232
+ Determine whether system logging is supported.
233
+
234
+ :returns:
235
+
236
+ :data:`True` if system logging is supported and can be enabled,
237
+ :data:`False` if system logging is not supported or there are good
238
+ reasons for not enabling it.
239
+
240
+ The decision making process here is as follows:
241
+
242
+ Override
243
+ If the environment variable ``$COLOREDLOGS_SYSLOG`` is set it is evaluated
244
+ using :func:`~humanfriendly.coerce_boolean()` and the resulting value
245
+ overrides the platform detection discussed below, this allows users to
246
+ override the decision making process if they disagree / know better.
247
+
248
+ Linux / UNIX
249
+ On systems that are not Windows or MacOS (see below) we assume UNIX which
250
+ means either syslog is available or sending a bunch of UDP packets to
251
+ nowhere won't hurt anyone...
252
+
253
+ Microsoft Windows
254
+ Over the years I've had multiple reports of :pypi:`coloredlogs` spewing
255
+ extremely verbose errno 10057 warning messages to the console (once for
256
+ each log message I suppose) so I now assume it a default that
257
+ "syslog-style system logging" is not generally available on Windows.
258
+
259
+ Apple MacOS
260
+ There's cPython issue `#38780`_ which seems to result in a fatal exception
261
+ when the Python interpreter shuts down. This is (way) worse than not
262
+ having system logging enabled. The error message mentioned in `#38780`_
263
+ has actually been following me around for years now, see for example:
264
+
265
+ - https://github.com/xolox/python-rotate-backups/issues/9 mentions Docker
266
+ images implying Linux, so not strictly the same as `#38780`_.
267
+
268
+ - https://github.com/xolox/python-npm-accel/issues/4 is definitely related
269
+ to `#38780`_ and is what eventually prompted me to add the
270
+ :func:`is_syslog_supported()` logic.
271
+
272
+ .. _#38780: https://bugs.python.org/issue38780
273
+ """
274
+ override = os.environ.get("COLOREDLOGS_SYSLOG")
275
+ if override is not None:
276
+ return coerce_boolean(override)
277
+ else:
278
+ return not (on_windows() or on_macos())
279
+
280
+
281
+ def match_syslog_handler(handler):
282
+ """
283
+ Identify system logging handlers.
284
+
285
+ :param handler: The :class:`~logging.Handler` class to check.
286
+ :returns: :data:`True` if the handler is a
287
+ :class:`~logging.handlers.SysLogHandler`,
288
+ :data:`False` otherwise.
289
+
290
+ This function can be used as a callback for :func:`.find_handler()`.
291
+ """
292
+ return isinstance(handler, logging.handlers.SysLogHandler)
python_embeded/Lib/site-packages/coloredlogs/tests.py ADDED
@@ -0,0 +1,673 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Automated tests for the `coloredlogs' package.
2
+ #
3
+ # Author: Peter Odding <peter@peterodding.com>
4
+ # Last Change: June 11, 2021
5
+ # URL: https://coloredlogs.readthedocs.io
6
+
7
+ """Automated tests for the `coloredlogs` package."""
8
+
9
+ # Standard library modules.
10
+ import contextlib
11
+ import logging
12
+ import logging.handlers
13
+ import os
14
+ import re
15
+ import subprocess
16
+ import sys
17
+ import tempfile
18
+
19
+ # External dependencies.
20
+ from humanfriendly.compat import StringIO
21
+ from humanfriendly.terminal import ANSI_COLOR_CODES, ANSI_CSI, ansi_style, ansi_wrap
22
+ from humanfriendly.testing import PatchedAttribute, PatchedItem, TestCase, retry
23
+ from humanfriendly.text import format, random_string
24
+
25
+ # The module we're testing.
26
+ import coloredlogs
27
+ import coloredlogs.cli
28
+ from coloredlogs import (
29
+ CHROOT_FILES,
30
+ ColoredFormatter,
31
+ NameNormalizer,
32
+ decrease_verbosity,
33
+ find_defined_levels,
34
+ find_handler,
35
+ find_hostname,
36
+ find_program_name,
37
+ find_username,
38
+ get_level,
39
+ increase_verbosity,
40
+ install,
41
+ is_verbose,
42
+ level_to_number,
43
+ match_stream_handler,
44
+ parse_encoded_styles,
45
+ set_level,
46
+ walk_propagation_tree,
47
+ )
48
+ from coloredlogs.demo import demonstrate_colored_logging
49
+ from coloredlogs.syslog import SystemLogging, is_syslog_supported, match_syslog_handler
50
+ from coloredlogs.converter import (
51
+ ColoredCronMailer,
52
+ EIGHT_COLOR_PALETTE,
53
+ capture,
54
+ convert,
55
+ )
56
+
57
+ # External test dependencies.
58
+ from capturer import CaptureOutput
59
+ from verboselogs import VerboseLogger
60
+
61
+ # Compiled regular expression that matches a single line of output produced by
62
+ # the default log format (does not include matching of ANSI escape sequences).
63
+ PLAIN_TEXT_PATTERN = re.compile(r'''
64
+ (?P<date> \d{4}-\d{2}-\d{2} )
65
+ \s (?P<time> \d{2}:\d{2}:\d{2} )
66
+ \s (?P<hostname> \S+ )
67
+ \s (?P<logger_name> \w+ )
68
+ \[ (?P<process_id> \d+ ) \]
69
+ \s (?P<severity> [A-Z]+ )
70
+ \s (?P<message> .* )
71
+ ''', re.VERBOSE)
72
+
73
+ # Compiled regular expression that matches a single line of output produced by
74
+ # the default log format with milliseconds=True.
75
+ PATTERN_INCLUDING_MILLISECONDS = re.compile(r'''
76
+ (?P<date> \d{4}-\d{2}-\d{2} )
77
+ \s (?P<time> \d{2}:\d{2}:\d{2},\d{3} )
78
+ \s (?P<hostname> \S+ )
79
+ \s (?P<logger_name> \w+ )
80
+ \[ (?P<process_id> \d+ ) \]
81
+ \s (?P<severity> [A-Z]+ )
82
+ \s (?P<message> .* )
83
+ ''', re.VERBOSE)
84
+
85
+
86
+ def setUpModule():
87
+ """Speed up the tests by disabling the demo's artificial delay."""
88
+ os.environ['COLOREDLOGS_DEMO_DELAY'] = '0'
89
+ coloredlogs.demo.DEMO_DELAY = 0
90
+
91
+
92
+ class ColoredLogsTestCase(TestCase):
93
+
94
+ """Container for the `coloredlogs` tests."""
95
+
96
+ def find_system_log(self):
97
+ """Find the system log file or skip the current test."""
98
+ filename = ('/var/log/system.log' if sys.platform == 'darwin' else (
99
+ '/var/log/syslog' if 'linux' in sys.platform else None
100
+ ))
101
+ if not filename:
102
+ self.skipTest("Location of system log file unknown!")
103
+ elif not os.path.isfile(filename):
104
+ self.skipTest("System log file not found! (%s)" % filename)
105
+ elif not os.access(filename, os.R_OK):
106
+ self.skipTest("Insufficient permissions to read system log file! (%s)" % filename)
107
+ else:
108
+ return filename
109
+
110
+ def test_level_to_number(self):
111
+ """Make sure :func:`level_to_number()` works as intended."""
112
+ # Make sure the default levels are translated as expected.
113
+ assert level_to_number('debug') == logging.DEBUG
114
+ assert level_to_number('info') == logging.INFO
115
+ assert level_to_number('warning') == logging.WARNING
116
+ assert level_to_number('error') == logging.ERROR
117
+ assert level_to_number('fatal') == logging.FATAL
118
+ # Make sure bogus level names don't blow up.
119
+ assert level_to_number('bogus-level') == logging.INFO
120
+
121
+ def test_find_hostname(self):
122
+ """Make sure :func:`~find_hostname()` works correctly."""
123
+ assert find_hostname()
124
+ # Create a temporary file as a placeholder for e.g. /etc/debian_chroot.
125
+ fd, temporary_file = tempfile.mkstemp()
126
+ try:
127
+ with open(temporary_file, 'w') as handle:
128
+ handle.write('first line\n')
129
+ handle.write('second line\n')
130
+ CHROOT_FILES.insert(0, temporary_file)
131
+ # Make sure the chroot file is being read.
132
+ assert find_hostname() == 'first line'
133
+ finally:
134
+ # Clean up.
135
+ CHROOT_FILES.pop(0)
136
+ os.unlink(temporary_file)
137
+ # Test that unreadable chroot files don't break coloredlogs.
138
+ try:
139
+ CHROOT_FILES.insert(0, temporary_file)
140
+ # Make sure that a usable value is still produced.
141
+ assert find_hostname()
142
+ finally:
143
+ # Clean up.
144
+ CHROOT_FILES.pop(0)
145
+
146
+ def test_host_name_filter(self):
147
+ """Make sure :func:`install()` integrates with :class:`~coloredlogs.HostNameFilter()`."""
148
+ install(fmt='%(hostname)s')
149
+ with CaptureOutput() as capturer:
150
+ logging.info("A truly insignificant message ..")
151
+ output = capturer.get_text()
152
+ assert find_hostname() in output
153
+
154
+ def test_program_name_filter(self):
155
+ """Make sure :func:`install()` integrates with :class:`~coloredlogs.ProgramNameFilter()`."""
156
+ install(fmt='%(programname)s')
157
+ with CaptureOutput() as capturer:
158
+ logging.info("A truly insignificant message ..")
159
+ output = capturer.get_text()
160
+ assert find_program_name() in output
161
+
162
+ def test_username_filter(self):
163
+ """Make sure :func:`install()` integrates with :class:`~coloredlogs.UserNameFilter()`."""
164
+ install(fmt='%(username)s')
165
+ with CaptureOutput() as capturer:
166
+ logging.info("A truly insignificant message ..")
167
+ output = capturer.get_text()
168
+ assert find_username() in output
169
+
170
+ def test_system_logging(self):
171
+ """Make sure the :class:`coloredlogs.syslog.SystemLogging` context manager works."""
172
+ system_log_file = self.find_system_log()
173
+ expected_message = random_string(50)
174
+ with SystemLogging(programname='coloredlogs-test-suite') as syslog:
175
+ if not syslog:
176
+ return self.skipTest("couldn't connect to syslog daemon")
177
+ # When I tried out the system logging support on macOS 10.13.1 on
178
+ # 2018-01-05 I found that while WARNING and ERROR messages show up
179
+ # in the system log DEBUG and INFO messages don't. This explains
180
+ # the importance of the level of the log message below.
181
+ logging.error("%s", expected_message)
182
+ # Retry the following assertion (for up to 60 seconds) to give the
183
+ # logging daemon time to write our log message to disk. This
184
+ # appears to be needed on MacOS workers on Travis CI, see:
185
+ # https://travis-ci.org/xolox/python-coloredlogs/jobs/325245853
186
+ retry(lambda: check_contents(system_log_file, expected_message, True))
187
+
188
+ def test_system_logging_override(self):
189
+ """Make sure the :class:`coloredlogs.syslog.is_syslog_supported` respects the override."""
190
+ with PatchedItem(os.environ, 'COLOREDLOGS_SYSLOG', 'true'):
191
+ assert is_syslog_supported() is True
192
+ with PatchedItem(os.environ, 'COLOREDLOGS_SYSLOG', 'false'):
193
+ assert is_syslog_supported() is False
194
+
195
+ def test_syslog_shortcut_simple(self):
196
+ """Make sure that ``coloredlogs.install(syslog=True)`` works."""
197
+ system_log_file = self.find_system_log()
198
+ expected_message = random_string(50)
199
+ with cleanup_handlers():
200
+ # See test_system_logging() for the importance of this log level.
201
+ coloredlogs.install(syslog=True)
202
+ logging.error("%s", expected_message)
203
+ # See the comments in test_system_logging() on why this is retried.
204
+ retry(lambda: check_contents(system_log_file, expected_message, True))
205
+
206
+ def test_syslog_shortcut_enhanced(self):
207
+ """Make sure that ``coloredlogs.install(syslog='warning')`` works."""
208
+ system_log_file = self.find_system_log()
209
+ the_expected_message = random_string(50)
210
+ not_an_expected_message = random_string(50)
211
+ with cleanup_handlers():
212
+ # See test_system_logging() for the importance of these log levels.
213
+ coloredlogs.install(syslog='error')
214
+ logging.warning("%s", not_an_expected_message)
215
+ logging.error("%s", the_expected_message)
216
+ # See the comments in test_system_logging() on why this is retried.
217
+ retry(lambda: check_contents(system_log_file, the_expected_message, True))
218
+ retry(lambda: check_contents(system_log_file, not_an_expected_message, False))
219
+
220
+ def test_name_normalization(self):
221
+ """Make sure :class:`~coloredlogs.NameNormalizer` works as intended."""
222
+ nn = NameNormalizer()
223
+ for canonical_name in ['debug', 'info', 'warning', 'error', 'critical']:
224
+ assert nn.normalize_name(canonical_name) == canonical_name
225
+ assert nn.normalize_name(canonical_name.upper()) == canonical_name
226
+ assert nn.normalize_name('warn') == 'warning'
227
+ assert nn.normalize_name('fatal') == 'critical'
228
+
229
+ def test_style_parsing(self):
230
+ """Make sure :func:`~coloredlogs.parse_encoded_styles()` works as intended."""
231
+ encoded_styles = 'debug=green;warning=yellow;error=red;critical=red,bold'
232
+ decoded_styles = parse_encoded_styles(encoded_styles, normalize_key=lambda k: k.upper())
233
+ assert sorted(decoded_styles.keys()) == sorted(['debug', 'warning', 'error', 'critical'])
234
+ assert decoded_styles['debug']['color'] == 'green'
235
+ assert decoded_styles['warning']['color'] == 'yellow'
236
+ assert decoded_styles['error']['color'] == 'red'
237
+ assert decoded_styles['critical']['color'] == 'red'
238
+ assert decoded_styles['critical']['bold'] is True
239
+
240
+ def test_is_verbose(self):
241
+ """Make sure is_verbose() does what it should :-)."""
242
+ set_level(logging.INFO)
243
+ assert not is_verbose()
244
+ set_level(logging.DEBUG)
245
+ assert is_verbose()
246
+ set_level(logging.VERBOSE)
247
+ assert is_verbose()
248
+
249
+ def test_increase_verbosity(self):
250
+ """Make sure increase_verbosity() respects default and custom levels."""
251
+ # Start from a known state.
252
+ set_level(logging.INFO)
253
+ assert get_level() == logging.INFO
254
+ # INFO -> VERBOSE.
255
+ increase_verbosity()
256
+ assert get_level() == logging.VERBOSE
257
+ # VERBOSE -> DEBUG.
258
+ increase_verbosity()
259
+ assert get_level() == logging.DEBUG
260
+ # DEBUG -> SPAM.
261
+ increase_verbosity()
262
+ assert get_level() == logging.SPAM
263
+ # SPAM -> NOTSET.
264
+ increase_verbosity()
265
+ assert get_level() == logging.NOTSET
266
+ # NOTSET -> NOTSET.
267
+ increase_verbosity()
268
+ assert get_level() == logging.NOTSET
269
+
270
+ def test_decrease_verbosity(self):
271
+ """Make sure decrease_verbosity() respects default and custom levels."""
272
+ # Start from a known state.
273
+ set_level(logging.INFO)
274
+ assert get_level() == logging.INFO
275
+ # INFO -> NOTICE.
276
+ decrease_verbosity()
277
+ assert get_level() == logging.NOTICE
278
+ # NOTICE -> WARNING.
279
+ decrease_verbosity()
280
+ assert get_level() == logging.WARNING
281
+ # WARNING -> SUCCESS.
282
+ decrease_verbosity()
283
+ assert get_level() == logging.SUCCESS
284
+ # SUCCESS -> ERROR.
285
+ decrease_verbosity()
286
+ assert get_level() == logging.ERROR
287
+ # ERROR -> CRITICAL.
288
+ decrease_verbosity()
289
+ assert get_level() == logging.CRITICAL
290
+ # CRITICAL -> CRITICAL.
291
+ decrease_verbosity()
292
+ assert get_level() == logging.CRITICAL
293
+
294
+ def test_level_discovery(self):
295
+ """Make sure find_defined_levels() always reports the levels defined in Python's standard library."""
296
+ defined_levels = find_defined_levels()
297
+ level_values = defined_levels.values()
298
+ for number in (0, 10, 20, 30, 40, 50):
299
+ assert number in level_values
300
+
301
+ def test_walk_propagation_tree(self):
302
+ """Make sure walk_propagation_tree() properly walks the tree of loggers."""
303
+ root, parent, child, grand_child = self.get_logger_tree()
304
+ # Check the default mode of operation.
305
+ loggers = list(walk_propagation_tree(grand_child))
306
+ assert loggers == [grand_child, child, parent, root]
307
+ # Now change the propagation (non-default mode of operation).
308
+ child.propagate = False
309
+ loggers = list(walk_propagation_tree(grand_child))
310
+ assert loggers == [grand_child, child]
311
+
312
+ def test_find_handler(self):
313
+ """Make sure find_handler() works as intended."""
314
+ root, parent, child, grand_child = self.get_logger_tree()
315
+ # Add some handlers to the tree.
316
+ stream_handler = logging.StreamHandler()
317
+ syslog_handler = logging.handlers.SysLogHandler()
318
+ child.addHandler(stream_handler)
319
+ parent.addHandler(syslog_handler)
320
+ # Make sure the first matching handler is returned.
321
+ matched_handler, matched_logger = find_handler(grand_child, lambda h: isinstance(h, logging.Handler))
322
+ assert matched_handler is stream_handler
323
+ # Make sure the first matching handler of the given type is returned.
324
+ matched_handler, matched_logger = find_handler(child, lambda h: isinstance(h, logging.handlers.SysLogHandler))
325
+ assert matched_handler is syslog_handler
326
+
327
+ def get_logger_tree(self):
328
+ """Create and return a tree of loggers."""
329
+ # Get the root logger.
330
+ root = logging.getLogger()
331
+ # Create a top level logger for ourselves.
332
+ parent_name = random_string()
333
+ parent = logging.getLogger(parent_name)
334
+ # Create a child logger.
335
+ child_name = '%s.%s' % (parent_name, random_string())
336
+ child = logging.getLogger(child_name)
337
+ # Create a grand child logger.
338
+ grand_child_name = '%s.%s' % (child_name, random_string())
339
+ grand_child = logging.getLogger(grand_child_name)
340
+ return root, parent, child, grand_child
341
+
342
+ def test_support_for_milliseconds(self):
343
+ """Make sure milliseconds are hidden by default but can be easily enabled."""
344
+ # Check that the default log format doesn't include milliseconds.
345
+ stream = StringIO()
346
+ install(reconfigure=True, stream=stream)
347
+ logging.info("This should not include milliseconds.")
348
+ assert all(map(PLAIN_TEXT_PATTERN.match, stream.getvalue().splitlines()))
349
+ # Check that milliseconds can be enabled via a shortcut.
350
+ stream = StringIO()
351
+ install(milliseconds=True, reconfigure=True, stream=stream)
352
+ logging.info("This should include milliseconds.")
353
+ assert all(map(PATTERN_INCLUDING_MILLISECONDS.match, stream.getvalue().splitlines()))
354
+
355
+ def test_support_for_milliseconds_directive(self):
356
+ """Make sure milliseconds using the ``%f`` directive are supported."""
357
+ stream = StringIO()
358
+ install(reconfigure=True, stream=stream, datefmt='%Y-%m-%dT%H:%M:%S.%f%z')
359
+ logging.info("This should be timestamped according to #45.")
360
+ assert re.match(r'^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}[+-]\d{4}\s', stream.getvalue())
361
+
362
+ def test_plain_text_output_format(self):
363
+ """Inspect the plain text output of coloredlogs."""
364
+ logger = VerboseLogger(random_string(25))
365
+ stream = StringIO()
366
+ install(level=logging.NOTSET, logger=logger, stream=stream)
367
+ # Test that filtering on severity works.
368
+ logger.setLevel(logging.INFO)
369
+ logger.debug("No one should see this message.")
370
+ assert len(stream.getvalue().strip()) == 0
371
+ # Test that the default output format looks okay in plain text.
372
+ logger.setLevel(logging.NOTSET)
373
+ for method, severity in ((logger.debug, 'DEBUG'),
374
+ (logger.info, 'INFO'),
375
+ (logger.verbose, 'VERBOSE'),
376
+ (logger.warning, 'WARNING'),
377
+ (logger.error, 'ERROR'),
378
+ (logger.critical, 'CRITICAL')):
379
+ # XXX Workaround for a regression in Python 3.7 caused by the
380
+ # Logger.isEnabledFor() method using stale cache entries. If we
381
+ # don't clear the cache then logger.isEnabledFor(logging.DEBUG)
382
+ # returns False and no DEBUG message is emitted.
383
+ try:
384
+ logger._cache.clear()
385
+ except AttributeError:
386
+ pass
387
+ # Prepare the text.
388
+ text = "This is a message with severity %r." % severity.lower()
389
+ # Log the message with the given severity.
390
+ method(text)
391
+ # Get the line of output generated by the handler.
392
+ output = stream.getvalue()
393
+ lines = output.splitlines()
394
+ last_line = lines[-1]
395
+ assert text in last_line
396
+ assert severity in last_line
397
+ assert PLAIN_TEXT_PATTERN.match(last_line)
398
+
399
+ def test_dynamic_stderr_lookup(self):
400
+ """Make sure coloredlogs.install() uses StandardErrorHandler when possible."""
401
+ coloredlogs.install()
402
+ # Redirect sys.stderr to a temporary buffer.
403
+ initial_stream = StringIO()
404
+ initial_text = "Which stream will receive this text?"
405
+ with PatchedAttribute(sys, 'stderr', initial_stream):
406
+ logging.info(initial_text)
407
+ assert initial_text in initial_stream.getvalue()
408
+ # Redirect sys.stderr again, to a different destination.
409
+ subsequent_stream = StringIO()
410
+ subsequent_text = "And which stream will receive this other text?"
411
+ with PatchedAttribute(sys, 'stderr', subsequent_stream):
412
+ logging.info(subsequent_text)
413
+ assert subsequent_text in subsequent_stream.getvalue()
414
+
415
+ def test_force_enable(self):
416
+ """Make sure ANSI escape sequences can be forced (bypassing auto-detection)."""
417
+ interpreter = subprocess.Popen([
418
+ sys.executable, "-c", ";".join([
419
+ "import coloredlogs, logging",
420
+ "coloredlogs.install(isatty=True)",
421
+ "logging.info('Hello world')",
422
+ ]),
423
+ ], stderr=subprocess.PIPE)
424
+ stdout, stderr = interpreter.communicate()
425
+ assert ANSI_CSI in stderr.decode('UTF-8')
426
+
427
+ def test_auto_disable(self):
428
+ """
429
+ Make sure ANSI escape sequences are not emitted when logging output is being redirected.
430
+
431
+ This is a regression test for https://github.com/xolox/python-coloredlogs/issues/100.
432
+
433
+ It works as follows:
434
+
435
+ 1. We mock an interactive terminal using 'capturer' to ensure that this
436
+ test works inside test drivers that capture output (like pytest).
437
+
438
+ 2. We launch a subprocess (to ensure a clean process state) where
439
+ stderr is captured but stdout is not, emulating issue #100.
440
+
441
+ 3. The output captured on stderr contained ANSI escape sequences after
442
+ this test was written and before the issue was fixed, so now this
443
+ serves as a regression test for issue #100.
444
+ """
445
+ with CaptureOutput():
446
+ interpreter = subprocess.Popen([
447
+ sys.executable, "-c", ";".join([
448
+ "import coloredlogs, logging",
449
+ "coloredlogs.install()",
450
+ "logging.info('Hello world')",
451
+ ]),
452
+ ], stderr=subprocess.PIPE)
453
+ stdout, stderr = interpreter.communicate()
454
+ assert ANSI_CSI not in stderr.decode('UTF-8')
455
+
456
+ def test_env_disable(self):
457
+ """Make sure ANSI escape sequences can be disabled using ``$NO_COLOR``."""
458
+ with PatchedItem(os.environ, 'NO_COLOR', 'I like monochrome'):
459
+ with CaptureOutput() as capturer:
460
+ subprocess.check_call([
461
+ sys.executable, "-c", ";".join([
462
+ "import coloredlogs, logging",
463
+ "coloredlogs.install()",
464
+ "logging.info('Hello world')",
465
+ ]),
466
+ ])
467
+ output = capturer.get_text()
468
+ assert ANSI_CSI not in output
469
+
470
+ def test_html_conversion(self):
471
+ """Check the conversion from ANSI escape sequences to HTML."""
472
+ # Check conversion of colored text.
473
+ for color_name, ansi_code in ANSI_COLOR_CODES.items():
474
+ ansi_encoded_text = 'plain text followed by %s text' % ansi_wrap(color_name, color=color_name)
475
+ expected_html = format(
476
+ '<code>plain text followed by <span style="color:{css}">{name}</span> text</code>',
477
+ css=EIGHT_COLOR_PALETTE[ansi_code], name=color_name,
478
+ )
479
+ self.assertEqual(expected_html, convert(ansi_encoded_text))
480
+ # Check conversion of bright colored text.
481
+ expected_html = '<code><span style="color:#FF0">bright yellow</span></code>'
482
+ self.assertEqual(expected_html, convert(ansi_wrap('bright yellow', color='yellow', bright=True)))
483
+ # Check conversion of text with a background color.
484
+ expected_html = '<code><span style="background-color:#DE382B">red background</span></code>'
485
+ self.assertEqual(expected_html, convert(ansi_wrap('red background', background='red')))
486
+ # Check conversion of text with a bright background color.
487
+ expected_html = '<code><span style="background-color:#F00">bright red background</span></code>'
488
+ self.assertEqual(expected_html, convert(ansi_wrap('bright red background', background='red', bright=True)))
489
+ # Check conversion of text that uses the 256 color mode palette as a foreground color.
490
+ expected_html = '<code><span style="color:#FFAF00">256 color mode foreground</span></code>'
491
+ self.assertEqual(expected_html, convert(ansi_wrap('256 color mode foreground', color=214)))
492
+ # Check conversion of text that uses the 256 color mode palette as a background color.
493
+ expected_html = '<code><span style="background-color:#AF0000">256 color mode background</span></code>'
494
+ self.assertEqual(expected_html, convert(ansi_wrap('256 color mode background', background=124)))
495
+ # Check that invalid 256 color mode indexes don't raise exceptions.
496
+ expected_html = '<code>plain text expected</code>'
497
+ self.assertEqual(expected_html, convert('\x1b[38;5;256mplain text expected\x1b[0m'))
498
+ # Check conversion of bold text.
499
+ expected_html = '<code><span style="font-weight:bold">bold text</span></code>'
500
+ self.assertEqual(expected_html, convert(ansi_wrap('bold text', bold=True)))
501
+ # Check conversion of underlined text.
502
+ expected_html = '<code><span style="text-decoration:underline">underlined text</span></code>'
503
+ self.assertEqual(expected_html, convert(ansi_wrap('underlined text', underline=True)))
504
+ # Check conversion of strike-through text.
505
+ expected_html = '<code><span style="text-decoration:line-through">strike-through text</span></code>'
506
+ self.assertEqual(expected_html, convert(ansi_wrap('strike-through text', strike_through=True)))
507
+ # Check conversion of inverse text.
508
+ expected_html = '<code><span style="background-color:#FFC706;color:#000">inverse</span></code>'
509
+ self.assertEqual(expected_html, convert(ansi_wrap('inverse', color='yellow', inverse=True)))
510
+ # Check conversion of URLs.
511
+ for sample_text in 'www.python.org', 'http://coloredlogs.rtfd.org', 'https://coloredlogs.rtfd.org':
512
+ sample_url = sample_text if '://' in sample_text else ('http://' + sample_text)
513
+ expected_html = '<code><a href="%s" style="color:inherit">%s</a></code>' % (sample_url, sample_text)
514
+ self.assertEqual(expected_html, convert(sample_text))
515
+ # Check that the capture pattern for URLs doesn't match ANSI escape
516
+ # sequences and also check that the short hand for the 0 reset code is
517
+ # supported. These are tests for regressions of bugs found in
518
+ # coloredlogs <= 8.0.
519
+ reset_short_hand = '\x1b[0m'
520
+ blue_underlined = ansi_style(color='blue', underline=True)
521
+ ansi_encoded_text = '<%shttps://coloredlogs.readthedocs.io%s>' % (blue_underlined, reset_short_hand)
522
+ expected_html = (
523
+ '<code>&lt;<span style="color:#006FB8;text-decoration:underline">'
524
+ '<a href="https://coloredlogs.readthedocs.io" style="color:inherit">'
525
+ 'https://coloredlogs.readthedocs.io'
526
+ '</a></span>&gt;</code>'
527
+ )
528
+ self.assertEqual(expected_html, convert(ansi_encoded_text))
529
+
530
+ def test_output_interception(self):
531
+ """Test capturing of output from external commands."""
532
+ expected_output = 'testing, 1, 2, 3 ..'
533
+ actual_output = capture(['echo', expected_output])
534
+ assert actual_output.strip() == expected_output.strip()
535
+
536
+ def test_enable_colored_cron_mailer(self):
537
+ """Test that automatic ANSI to HTML conversion when running under ``cron`` can be enabled."""
538
+ with PatchedItem(os.environ, 'CONTENT_TYPE', 'text/html'):
539
+ with ColoredCronMailer() as mailer:
540
+ assert mailer.is_enabled
541
+
542
+ def test_disable_colored_cron_mailer(self):
543
+ """Test that automatic ANSI to HTML conversion when running under ``cron`` can be disabled."""
544
+ with PatchedItem(os.environ, 'CONTENT_TYPE', 'text/plain'):
545
+ with ColoredCronMailer() as mailer:
546
+ assert not mailer.is_enabled
547
+
548
+ def test_auto_install(self):
549
+ """Test :func:`coloredlogs.auto_install()`."""
550
+ needle = random_string()
551
+ command_line = [sys.executable, '-c', 'import logging; logging.info(%r)' % needle]
552
+ # Sanity check that log messages aren't enabled by default.
553
+ with CaptureOutput() as capturer:
554
+ os.environ['COLOREDLOGS_AUTO_INSTALL'] = 'false'
555
+ subprocess.check_call(command_line)
556
+ output = capturer.get_text()
557
+ assert needle not in output
558
+ # Test that the $COLOREDLOGS_AUTO_INSTALL environment variable can be
559
+ # used to automatically call coloredlogs.install() during initialization.
560
+ with CaptureOutput() as capturer:
561
+ os.environ['COLOREDLOGS_AUTO_INSTALL'] = 'true'
562
+ subprocess.check_call(command_line)
563
+ output = capturer.get_text()
564
+ assert needle in output
565
+
566
+ def test_cli_demo(self):
567
+ """Test the command line colored logging demonstration."""
568
+ with CaptureOutput() as capturer:
569
+ main('coloredlogs', '--demo')
570
+ output = capturer.get_text()
571
+ # Make sure the output contains all of the expected logging level names.
572
+ for name in 'debug', 'info', 'warning', 'error', 'critical':
573
+ assert name.upper() in output
574
+
575
+ def test_cli_conversion(self):
576
+ """Test the command line HTML conversion."""
577
+ output = main('coloredlogs', '--convert', 'coloredlogs', '--demo', capture=True)
578
+ # Make sure the output is encoded as HTML.
579
+ assert '<span' in output
580
+
581
+ def test_empty_conversion(self):
582
+ """
583
+ Test that conversion of empty output produces no HTML.
584
+
585
+ This test was added because I found that ``coloredlogs --convert`` when
586
+ used in a cron job could cause cron to send out what appeared to be
587
+ empty emails. On more careful inspection the body of those emails was
588
+ ``<code></code>``. By not emitting the wrapper element when no other
589
+ HTML is generated, cron will not send out an email.
590
+ """
591
+ output = main('coloredlogs', '--convert', 'true', capture=True)
592
+ assert not output.strip()
593
+
594
+ def test_implicit_usage_message(self):
595
+ """Test that the usage message is shown when no actions are given."""
596
+ assert 'Usage:' in main('coloredlogs', capture=True)
597
+
598
+ def test_explicit_usage_message(self):
599
+ """Test that the usage message is shown when ``--help`` is given."""
600
+ assert 'Usage:' in main('coloredlogs', '--help', capture=True)
601
+
602
+ def test_custom_record_factory(self):
603
+ """
604
+ Test that custom LogRecord factories are supported.
605
+
606
+ This test is a bit convoluted because the logging module suppresses
607
+ exceptions. We monkey patch the method suspected of encountering
608
+ exceptions so that we can tell after it was called whether any
609
+ exceptions occurred (despite the exceptions not propagating).
610
+ """
611
+ if not hasattr(logging, 'getLogRecordFactory'):
612
+ return self.skipTest("this test requires Python >= 3.2")
613
+
614
+ exceptions = []
615
+ original_method = ColoredFormatter.format
616
+ original_factory = logging.getLogRecordFactory()
617
+
618
+ def custom_factory(*args, **kwargs):
619
+ record = original_factory(*args, **kwargs)
620
+ record.custom_attribute = 0xdecafbad
621
+ return record
622
+
623
+ def custom_method(*args, **kw):
624
+ try:
625
+ return original_method(*args, **kw)
626
+ except Exception as e:
627
+ exceptions.append(e)
628
+ raise
629
+
630
+ with PatchedAttribute(ColoredFormatter, 'format', custom_method):
631
+ logging.setLogRecordFactory(custom_factory)
632
+ try:
633
+ demonstrate_colored_logging()
634
+ finally:
635
+ logging.setLogRecordFactory(original_factory)
636
+
637
+ # Ensure that no exceptions were triggered.
638
+ assert not exceptions
639
+
640
+
641
+ def check_contents(filename, contents, match):
642
+ """Check if a line in a file contains an expected string."""
643
+ with open(filename) as handle:
644
+ assert any(contents in line for line in handle) == match
645
+
646
+
647
+ def main(*arguments, **options):
648
+ """Wrap the command line interface to make it easier to test."""
649
+ capture = options.get('capture', False)
650
+ saved_argv = sys.argv
651
+ saved_stdout = sys.stdout
652
+ try:
653
+ sys.argv = arguments
654
+ if capture:
655
+ sys.stdout = StringIO()
656
+ coloredlogs.cli.main()
657
+ if capture:
658
+ return sys.stdout.getvalue()
659
+ finally:
660
+ sys.argv = saved_argv
661
+ sys.stdout = saved_stdout
662
+
663
+
664
+ @contextlib.contextmanager
665
+ def cleanup_handlers():
666
+ """Context manager to cleanup output handlers."""
667
+ # There's nothing to set up so we immediately yield control.
668
+ yield
669
+ # After the with block ends we cleanup any output handlers.
670
+ for match_func in match_stream_handler, match_syslog_handler:
671
+ handler, logger = find_handler(logging.getLogger(), match_func)
672
+ if handler and logger:
673
+ logger.removeHandler(handler)
python_embeded/Lib/site-packages/colour/py.typed ADDED
File without changes
python_embeded/Lib/site-packages/colour_science-0.4.6.dist-info/METADATA ADDED
@@ -0,0 +1,2062 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.3
2
+ Name: colour-science
3
+ Version: 0.4.6
4
+ Summary: Colour Science for Python
5
+ Project-URL: Homepage, https://www.colour-science.org
6
+ Project-URL: Documentation, https://colour.readthedocs.org
7
+ Project-URL: Repository, https://github.com/colour-science/colour
8
+ Project-URL: Issues, https://github.com/colour-science/colour/issues
9
+ Project-URL: Changelog, https://github.com/colour-science/colour/releases
10
+ Author-email: Colour Developers <colour-developers@colour-science.org>
11
+ Maintainer-email: Colour Developers <colour-developers@colour-science.org>
12
+ License: BSD-3-Clause
13
+ License-File: LICENSE
14
+ Keywords: color,color-science,color-space,color-spaces,colorspace,colorspaces,colour,colour-science,colour-space,colour-spaces,colourspace,colourspaces,data,dataset,datasets,python,spectral-data,spectral-dataset,spectral-datasets
15
+ Classifier: Development Status :: 3 - Alpha
16
+ Classifier: Environment :: Console
17
+ Classifier: Intended Audience :: Developers
18
+ Classifier: Intended Audience :: Science/Research
19
+ Classifier: License :: OSI Approved
20
+ Classifier: Natural Language :: English
21
+ Classifier: Operating System :: OS Independent
22
+ Classifier: Programming Language :: Python :: 3
23
+ Classifier: Topic :: Scientific/Engineering
24
+ Classifier: Topic :: Software Development
25
+ Requires-Python: <3.14,>=3.10
26
+ Requires-Dist: imageio<3,>=2
27
+ Requires-Dist: numpy<3,>=1.24
28
+ Requires-Dist: scipy<2,>=1.10
29
+ Requires-Dist: typing-extensions<5,>=4
30
+ Provides-Extra: docs
31
+ Requires-Dist: biblib-simple; extra == 'docs'
32
+ Requires-Dist: pydata-sphinx-theme; extra == 'docs'
33
+ Requires-Dist: restructuredtext-lint; extra == 'docs'
34
+ Requires-Dist: sphinx; extra == 'docs'
35
+ Requires-Dist: sphinxcontrib-bibtex; extra == 'docs'
36
+ Provides-Extra: meshing
37
+ Requires-Dist: trimesh<5,>=4; extra == 'meshing'
38
+ Provides-Extra: optional
39
+ Requires-Dist: matplotlib>=3.7; extra == 'optional'
40
+ Requires-Dist: networkx<4,>=3; extra == 'optional'
41
+ Requires-Dist: opencolorio<3,>=2; extra == 'optional'
42
+ Requires-Dist: pandas<3,>=2; extra == 'optional'
43
+ Requires-Dist: pydot<4,>=3; extra == 'optional'
44
+ Requires-Dist: tqdm<5,>=4; extra == 'optional'
45
+ Requires-Dist: xxhash<4,>=3; extra == 'optional'
46
+ Description-Content-Type: text/x-rst
47
+
48
+ .. image:: https://raw.githubusercontent.com/colour-science/colour-branding/master/images/Colour_Logo_001.png
49
+
50
+
51
+ |
52
+
53
+ .. start-badges
54
+
55
+ |NumFOCUS| |actions| |coveralls| |codacy| |version| |zenodo|
56
+
57
+ .. |NumFOCUS| image:: https://img.shields.io/badge/powered%20by-NumFOCUS-orange.svg?style=flat-square&colorA=E1523D&colorB=007D8A
58
+ :target: http://numfocus.org
59
+ :alt: Powered by NumFOCUS
60
+ .. |actions| image:: https://img.shields.io/github/actions/workflow/status/colour-science/colour/.github/workflows/continuous-integration-quality-unit-tests.yml?branch=develop&style=flat-square
61
+ :target: https://github.com/colour-science/colour/actions
62
+ :alt: Develop Build Status
63
+ .. |coveralls| image:: http://img.shields.io/coveralls/colour-science/colour/develop.svg?style=flat-square
64
+ :target: https://coveralls.io/r/colour-science/colour
65
+ :alt: Coverage Status
66
+ .. |codacy| image:: https://img.shields.io/codacy/grade/1f3b8d3bba7440ba9ebc1170589628b1/develop.svg?style=flat-square
67
+ :target: https://app.codacy.com/gh/colour-science/colour
68
+ :alt: Code Grade
69
+ .. |version| image:: https://img.shields.io/pypi/v/colour-science.svg?style=flat-square
70
+ :target: https://pypi.org/project/colour-science
71
+ :alt: Package Version
72
+ .. |zenodo| image:: https://img.shields.io/badge/DOI-10.5281/zenodo.13917514-blue.svg?style=flat-square
73
+ :target: https://dx.doi.org/10.5281/zenodo.13917514
74
+ :alt: DOI
75
+
76
+ .. end-badges
77
+
78
+ `Colour <https://github.com/colour-science/colour>`__ is an open-source
79
+ `Python <https://www.python.org>`__ package providing a comprehensive number
80
+ of algorithms and datasets for colour science.
81
+
82
+ It is freely available under the
83
+ `BSD-3-Clause <https://opensource.org/licenses/BSD-3-Clause>`__ terms.
84
+
85
+ **Colour** is an affiliated project of `NumFOCUS <https://numfocus.org>`__, a
86
+ 501(c)(3) nonprofit in the United States.
87
+
88
+ .. contents:: **Table of Contents**
89
+ :backlinks: none
90
+ :depth: 2
91
+
92
+ .. sectnum::
93
+
94
+ Draft Release Notes
95
+ -------------------
96
+
97
+ The draft release notes of the
98
+ `develop <https://github.com/colour-science/colour/tree/develop>`__
99
+ branch are available at this
100
+ `url <https://gist.github.com/KelSolaar/4a6ebe9ec3d389f0934b154fec8df51d>`__.
101
+
102
+ Sponsors
103
+ --------
104
+
105
+ We are grateful 💖 for the support of our
106
+ `sponsors <https://github.com/colour-science/colour/blob/develop/SPONSORS.rst>`__.
107
+ If you'd like to join them, please consider
108
+ `becoming a sponsor on OpenCollective <https://opencollective.com/colour-science>`__.
109
+
110
+
111
+
112
+ Features
113
+ --------
114
+
115
+ Most of the objects are available from the ``colour`` namespace:
116
+
117
+ .. code-block:: python
118
+
119
+ import colour
120
+
121
+ Automatic Colour Conversion Graph - ``colour.graph``
122
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
123
+
124
+ Starting with version *0.3.14*, **Colour** implements an automatic colour
125
+ conversion graph enabling easier colour conversions.
126
+
127
+ .. image:: https://colour.readthedocs.io/en/develop/_static/Examples_Colour_Automatic_Conversion_Graph.png
128
+
129
+ .. code-block:: python
130
+
131
+ sd = colour.SDS_COLOURCHECKERS["ColorChecker N Ohta"]["dark skin"]
132
+ colour.convert(sd, "Spectral Distribution", "sRGB", verbose={"mode": "Short"})
133
+
134
+ .. code-block:: text
135
+
136
+ ===============================================================================
137
+ * *
138
+ * [ Conversion Path ] *
139
+ * *
140
+ * "sd_to_XYZ" --> "XYZ_to_sRGB" *
141
+ * *
142
+ ===============================================================================
143
+ array([ 0.45675795, 0.30986982, 0.24861924])
144
+
145
+ .. code-block:: python
146
+
147
+ illuminant = colour.SDS_ILLUMINANTS["FL2"]
148
+ colour.convert(
149
+ sd,
150
+ "Spectral Distribution",
151
+ "sRGB",
152
+ sd_to_XYZ={"illuminant": illuminant},
153
+ )
154
+
155
+ .. code-block:: text
156
+
157
+ array([ 0.47924575, 0.31676968, 0.17362725])
158
+
159
+ Chromatic Adaptation - ``colour.adaptation``
160
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
161
+
162
+ .. code-block:: python
163
+
164
+ XYZ = [0.20654008, 0.12197225, 0.05136952]
165
+ D65 = colour.CCS_ILLUMINANTS["CIE 1931 2 Degree Standard Observer"]["D65"]
166
+ A = colour.CCS_ILLUMINANTS["CIE 1931 2 Degree Standard Observer"]["A"]
167
+ colour.chromatic_adaptation(XYZ, colour.xy_to_XYZ(D65), colour.xy_to_XYZ(A))
168
+
169
+ .. code-block:: text
170
+
171
+ array([ 0.2533053 , 0.13765138, 0.01543307])
172
+
173
+
174
+ .. code-block:: python
175
+
176
+ sorted(colour.CHROMATIC_ADAPTATION_METHODS)
177
+
178
+ .. code-block:: text
179
+
180
+ ['CIE 1994', 'CMCCAT2000', 'Fairchild 1990', 'Von Kries', 'Zhai 2018', 'vK20']
181
+
182
+ Algebra - ``colour.algebra``
183
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
184
+
185
+ Kernel Interpolation
186
+ ********************
187
+
188
+ .. code-block:: python
189
+
190
+ y = [5.9200, 9.3700, 10.8135, 4.5100, 69.5900, 27.8007, 86.0500]
191
+ x = range(len(y))
192
+ colour.KernelInterpolator(x, y)([0.25, 0.75, 5.50])
193
+
194
+ .. code-block:: text
195
+
196
+ array([ 6.18062083, 8.08238488, 57.85783403])
197
+
198
+ Sprague (1880) Interpolation
199
+ ****************************
200
+
201
+ .. code-block:: python
202
+
203
+ y = [5.9200, 9.3700, 10.8135, 4.5100, 69.5900, 27.8007, 86.0500]
204
+ x = range(len(y))
205
+ colour.SpragueInterpolator(x, y)([0.25, 0.75, 5.50])
206
+
207
+ .. code-block:: text
208
+
209
+ array([ 6.72951612, 7.81406251, 43.77379185])
210
+
211
+ Colour Appearance Models - ``colour.appearance``
212
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
213
+
214
+ .. code-block:: python
215
+
216
+ XYZ = [0.20654008 * 100, 0.12197225 * 100, 0.05136952 * 100]
217
+ XYZ_w = [95.05, 100.00, 108.88]
218
+ L_A = 318.31
219
+ Y_b = 20.0
220
+ colour.XYZ_to_CIECAM02(XYZ, XYZ_w, L_A, Y_b)
221
+
222
+ .. code-block:: text
223
+
224
+ CAM_Specification_CIECAM02(J=34.434525727858997, C=67.365010921125943, h=22.279164147957065, s=62.81485585332716, Q=177.47124941102123, M=70.024939419291414, H=2.6896085344238898, HC=None)
225
+
226
+ .. code-block:: python
227
+
228
+ colour.XYZ_to_CIECAM16(XYZ, XYZ_w, L_A, Y_b)
229
+
230
+ .. code-block:: text
231
+
232
+ CAM_Specification_CIECAM16(J=34.434525727858997, C=67.365010921125943, h=22.279164147957065, s=62.81485585332716, Q=177.47124941102123, M=70.024939419291414, H=2.6896085344238898, HC=None)
233
+
234
+ .. code-block:: python
235
+
236
+ colour.XYZ_to_CAM16(XYZ, XYZ_w, L_A, Y_b)
237
+
238
+ .. code-block:: text
239
+
240
+ CAM_Specification_CAM16(J=33.880368498111686, C=69.444353357408033, h=19.510887327451748, s=64.03612114840314, Q=176.03752758512178, M=72.18638534116765, H=399.52975599115319, HC=None)
241
+
242
+ .. code-block:: python
243
+
244
+ colour.XYZ_to_Hellwig2022(XYZ, XYZ_w, L_A)
245
+
246
+ .. code-block:: text
247
+
248
+ CAM_Specification_Hellwig2022(J=33.880368498111686, C=40.347043294550311, h=19.510887327451748, s=117.38555017188679, Q=45.34489577734751, M=53.228355383108031, H=399.52975599115319, HC=None)
249
+
250
+ .. code-block:: python
251
+
252
+ colour.XYZ_to_Kim2009(XYZ, XYZ_w, L_A)
253
+
254
+ .. code-block:: text
255
+
256
+ CAM_Specification_Kim2009(J=19.879918542450902, C=55.839055250876946, h=22.013388165090046, s=112.97979354939129, Q=36.309026130161449, M=46.346415858227864, H=2.3543198369639931, HC=None)
257
+
258
+ .. code-block:: python
259
+
260
+ colour.XYZ_to_ZCAM(XYZ, XYZ_w, L_A, Y_b)
261
+
262
+ .. code-block:: text
263
+
264
+ CAM_Specification_ZCAM(J=38.347186278956357, C=21.12138989208518, h=33.711578931095197, s=81.444585609489536, Q=76.986725284523772, M=42.403805833900506, H=0.45779200212219573, HC=None, V=43.623590687423544, K=43.20894953152817, W=34.829588380192149)
265
+
266
+ Colour Blindness - ``colour.blindness``
267
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
268
+
269
+ .. code-block:: python
270
+
271
+ import numpy as np
272
+
273
+ cmfs = colour.LMS_CMFS["Stockman & Sharpe 2 Degree Cone Fundamentals"]
274
+ colour.msds_cmfs_anomalous_trichromacy_Machado2009(cmfs, np.array([15, 0, 0]))[450]
275
+
276
+ .. code-block:: text
277
+
278
+ array([ 0.08912884, 0.0870524 , 0.955393 ])
279
+
280
+ .. code-block:: python
281
+
282
+ primaries = colour.MSDS_DISPLAY_PRIMARIES["Apple Studio Display"]
283
+ d_LMS = (15, 0, 0)
284
+ colour.matrix_anomalous_trichromacy_Machado2009(cmfs, primaries, d_LMS)
285
+
286
+ .. code-block:: text
287
+
288
+ array([[-0.27774652, 2.65150084, -1.37375432],
289
+ [ 0.27189369, 0.20047862, 0.52762768],
290
+ [ 0.00644047, 0.25921579, 0.73434374]])
291
+
292
+ Colour Correction - ``colour characterisation``
293
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
294
+
295
+ .. code-block:: python
296
+
297
+ import numpy as np
298
+
299
+ RGB = [0.17224810, 0.09170660, 0.06416938]
300
+ M_T = np.random.random((24, 3))
301
+ M_R = M_T + (np.random.random((24, 3)) - 0.5) * 0.5
302
+ colour.colour_correction(RGB, M_T, M_R)
303
+
304
+ .. code-block:: text
305
+
306
+ array([ 0.1806237 , 0.07234791, 0.07848845])
307
+
308
+ .. code-block:: python
309
+
310
+ sorted(colour.COLOUR_CORRECTION_METHODS)
311
+
312
+ .. code-block:: text
313
+
314
+ ['Cheung 2004', 'Finlayson 2015', 'Vandermonde']
315
+
316
+ ACES Input Transform - ``colour characterisation``
317
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
318
+
319
+ .. code-block:: python
320
+
321
+ sensitivities = colour.MSDS_CAMERA_SENSITIVITIES["Nikon 5100 (NPL)"]
322
+ illuminant = colour.SDS_ILLUMINANTS["D55"]
323
+ colour.matrix_idt(sensitivities, illuminant)
324
+
325
+ .. code-block:: text
326
+
327
+ (array([[ 0.59368175, 0.30418371, 0.10213454],
328
+ [ 0.00457979, 1.14946003, -0.15403982],
329
+ [ 0.03552213, -0.16312291, 1.12760077]]), array([ 1.58214188, 1. , 1.28910346]))
330
+
331
+ Colorimetry - ``colour.colorimetry``
332
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
333
+
334
+ Spectral Computations
335
+ *********************
336
+
337
+ .. code-block:: python
338
+
339
+ colour.sd_to_XYZ(colour.SDS_LIGHT_SOURCES["Neodimium Incandescent"])
340
+
341
+ .. code-block:: text
342
+
343
+ array([ 36.94726204, 32.62076174, 13.0143849 ])
344
+
345
+ .. code-block:: python
346
+
347
+ sorted(colour.SPECTRAL_TO_XYZ_METHODS)
348
+
349
+ .. code-block:: text
350
+
351
+ ['ASTM E308', 'Integration', 'astm2015']
352
+
353
+
354
+ Multi-Spectral Computations
355
+ ***************************
356
+
357
+ .. code-block:: python
358
+
359
+ msds = np.array(
360
+ [
361
+ [
362
+ [
363
+ 0.01367208,
364
+ 0.09127947,
365
+ 0.01524376,
366
+ 0.02810712,
367
+ 0.19176012,
368
+ 0.04299992,
369
+ ],
370
+ [
371
+ 0.00959792,
372
+ 0.25822842,
373
+ 0.41388571,
374
+ 0.22275120,
375
+ 0.00407416,
376
+ 0.37439537,
377
+ ],
378
+ [
379
+ 0.01791409,
380
+ 0.29707789,
381
+ 0.56295109,
382
+ 0.23752193,
383
+ 0.00236515,
384
+ 0.58190280,
385
+ ],
386
+ ],
387
+ [
388
+ [
389
+ 0.01492332,
390
+ 0.10421912,
391
+ 0.02240025,
392
+ 0.03735409,
393
+ 0.57663846,
394
+ 0.32416266,
395
+ ],
396
+ [
397
+ 0.04180972,
398
+ 0.26402685,
399
+ 0.03572137,
400
+ 0.00413520,
401
+ 0.41808194,
402
+ 0.24696727,
403
+ ],
404
+ [
405
+ 0.00628672,
406
+ 0.11454948,
407
+ 0.02198825,
408
+ 0.39906919,
409
+ 0.63640803,
410
+ 0.01139849,
411
+ ],
412
+ ],
413
+ [
414
+ [
415
+ 0.04325933,
416
+ 0.26825359,
417
+ 0.23732357,
418
+ 0.05175860,
419
+ 0.01181048,
420
+ 0.08233768,
421
+ ],
422
+ [
423
+ 0.02484169,
424
+ 0.12027161,
425
+ 0.00541695,
426
+ 0.00654612,
427
+ 0.18603799,
428
+ 0.36247808,
429
+ ],
430
+ [
431
+ 0.03102159,
432
+ 0.16815442,
433
+ 0.37186235,
434
+ 0.08610666,
435
+ 0.00413520,
436
+ 0.78492409,
437
+ ],
438
+ ],
439
+ [
440
+ [
441
+ 0.11682307,
442
+ 0.78883040,
443
+ 0.74468607,
444
+ 0.83375293,
445
+ 0.90571451,
446
+ 0.70054168,
447
+ ],
448
+ [
449
+ 0.06321812,
450
+ 0.41898224,
451
+ 0.15190357,
452
+ 0.24591440,
453
+ 0.55301750,
454
+ 0.00657664,
455
+ ],
456
+ [
457
+ 0.00305180,
458
+ 0.11288624,
459
+ 0.11357290,
460
+ 0.12924391,
461
+ 0.00195315,
462
+ 0.21771573,
463
+ ],
464
+ ],
465
+ ]
466
+ )
467
+ colour.msds_to_XYZ(
468
+ msds,
469
+ method="Integration",
470
+ shape=colour.SpectralShape(400, 700, 60),
471
+ )
472
+
473
+ .. code-block:: text
474
+
475
+ array([[[ 7.68544647, 4.09414317, 8.49324254],
476
+ [ 17.12567298, 27.77681821, 25.52573685],
477
+ [ 19.10280411, 34.45851476, 29.76319628]],
478
+ [[ 18.03375827, 8.62340812, 9.71702574],
479
+ [ 15.03110867, 6.54001068, 24.53208465],
480
+ [ 37.68269495, 26.4411103 , 10.66361816]],
481
+ [[ 8.09532373, 12.75333339, 25.79613956],
482
+ [ 7.09620297, 2.79257389, 11.15039854],
483
+ [ 8.933163 , 19.39985815, 17.14915636]],
484
+ [[ 80.00969553, 80.39810464, 76.08184429],
485
+ [ 33.27611427, 24.38947838, 39.34919287],
486
+ [ 8.89425686, 11.05185138, 10.86767594]]])
487
+
488
+ .. code-block:: python
489
+
490
+ sorted(colour.MSDS_TO_XYZ_METHODS)
491
+
492
+ .. code-block:: text
493
+
494
+ ['ASTM E308', 'Integration', 'astm2015']
495
+
496
+ Blackbody Spectral Radiance Computation
497
+ ***************************************
498
+
499
+ .. code-block:: python
500
+
501
+ colour.sd_blackbody(5000)
502
+
503
+ .. code-block:: text
504
+
505
+ SpectralDistribution([[ 3.60000000e+02, 6.65427827e+12],
506
+ [ 3.61000000e+02, 6.70960528e+12],
507
+ [ 3.62000000e+02, 6.76482512e+12],
508
+ ...
509
+ [ 7.78000000e+02, 1.06068004e+13],
510
+ [ 7.79000000e+02, 1.05903327e+13],
511
+ [ 7.80000000e+02, 1.05738520e+13]],
512
+ interpolator=SpragueInterpolator,
513
+ interpolator_args={},
514
+ extrapolator=Extrapolator,
515
+ extrapolator_args={'right': None, 'method': 'Constant', 'left': None})
516
+
517
+ Dominant, Complementary Wavelength & Colour Purity Computation
518
+ **************************************************************
519
+
520
+ .. code-block:: python
521
+
522
+ xy = [0.54369557, 0.32107944]
523
+ xy_n = [0.31270000, 0.32900000]
524
+ colour.dominant_wavelength(xy, xy_n)
525
+
526
+ .. code-block:: text
527
+
528
+ (array(616.0),
529
+ array([ 0.68354746, 0.31628409]),
530
+ array([ 0.68354746, 0.31628409]))
531
+
532
+ Lightness Computation
533
+ *********************
534
+
535
+ .. code-block:: python
536
+
537
+ colour.lightness(12.19722535)
538
+
539
+ .. code-block:: text
540
+
541
+ 41.527875844653451
542
+
543
+ .. code-block:: python
544
+
545
+ sorted(colour.LIGHTNESS_METHODS)
546
+
547
+ .. code-block:: text
548
+
549
+ ['Abebe 2017',
550
+ 'CIE 1976',
551
+ 'Fairchild 2010',
552
+ 'Fairchild 2011',
553
+ 'Glasser 1958',
554
+ 'Lstar1976',
555
+ 'Wyszecki 1963']
556
+
557
+ Luminance Computation
558
+ *********************
559
+
560
+ .. code-block:: python
561
+
562
+ colour.luminance(41.52787585)
563
+
564
+ .. code-block:: text
565
+
566
+ 12.197225353400775
567
+
568
+ .. code-block:: python
569
+
570
+ sorted(colour.LUMINANCE_METHODS)
571
+
572
+ .. code-block:: text
573
+
574
+ ['ASTM D1535',
575
+ 'CIE 1976',
576
+ 'Fairchild 2010',
577
+ 'Fairchild 2011',
578
+ 'Newhall 1943',
579
+ 'astm2008',
580
+ 'cie1976']
581
+
582
+ Whiteness Computation
583
+ *********************
584
+
585
+ .. code-block:: python
586
+
587
+ XYZ = [95.00000000, 100.00000000, 105.00000000]
588
+ XYZ_0 = [94.80966767, 100.00000000, 107.30513595]
589
+ colour.whiteness(XYZ, XYZ_0)
590
+
591
+ .. code-block:: text
592
+
593
+ array([ 93.756 , -1.33000001])
594
+
595
+ .. code-block:: python
596
+
597
+ sorted(colour.WHITENESS_METHODS)
598
+
599
+ .. code-block:: text
600
+
601
+ ['ASTM E313',
602
+ 'Berger 1959',
603
+ 'CIE 2004',
604
+ 'Ganz 1979',
605
+ 'Stensby 1968',
606
+ 'Taube 1960',
607
+ 'cie2004']
608
+
609
+ Yellowness Computation
610
+ **********************
611
+
612
+ .. code-block:: python
613
+
614
+ XYZ = [95.00000000, 100.00000000, 105.00000000]
615
+ colour.yellowness(XYZ)
616
+
617
+ .. code-block:: text
618
+
619
+ 4.3400000000000034
620
+
621
+ .. code-block:: python
622
+
623
+ sorted(colour.YELLOWNESS_METHODS)
624
+
625
+ .. code-block:: text
626
+
627
+ ['ASTM D1925', 'ASTM E313', 'ASTM E313 Alternative']
628
+
629
+ Luminous Flux, Efficiency & Efficacy Computation
630
+ ************************************************
631
+
632
+ .. code-block:: python
633
+
634
+ sd = colour.SDS_LIGHT_SOURCES["Neodimium Incandescent"]
635
+ colour.luminous_flux(sd)
636
+
637
+ .. code-block:: text
638
+
639
+ 23807.655527367202
640
+
641
+ .. code-block:: python
642
+
643
+ sd = colour.SDS_LIGHT_SOURCES["Neodimium Incandescent"]
644
+ colour.luminous_efficiency(sd)
645
+
646
+ .. code-block:: text
647
+
648
+ 0.19943935624521045
649
+
650
+ .. code-block:: python
651
+
652
+ sd = colour.SDS_LIGHT_SOURCES["Neodimium Incandescent"]
653
+ colour.luminous_efficacy(sd)
654
+
655
+ .. code-block:: text
656
+
657
+ 136.21708031547874
658
+
659
+ Contrast Sensitivity Function - ``colour.contrast``
660
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
661
+
662
+ .. code-block:: python
663
+
664
+ colour.contrast_sensitivity_function(u=4, X_0=60, E=65)
665
+
666
+ .. code-block:: text
667
+
668
+ 358.51180789884984
669
+
670
+ .. code-block:: python
671
+
672
+ sorted(colour.CONTRAST_SENSITIVITY_METHODS)
673
+
674
+ .. code-block:: text
675
+
676
+ ['Barten 1999']
677
+
678
+ Colour Difference - ``colour.difference``
679
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
680
+
681
+ .. code-block:: python
682
+
683
+ Lab_1 = [100.00000000, 21.57210357, 272.22819350]
684
+ Lab_2 = [100.00000000, 426.67945353, 72.39590835]
685
+ colour.delta_E(Lab_1, Lab_2)
686
+
687
+ .. code-block:: text
688
+
689
+ 94.035649026659485
690
+
691
+ .. code-block:: python
692
+
693
+ sorted(colour.DELTA_E_METHODS)
694
+
695
+ .. code-block:: text
696
+
697
+ ['CAM02-LCD',
698
+ 'CAM02-SCD',
699
+ 'CAM02-UCS',
700
+ 'CAM16-LCD',
701
+ 'CAM16-SCD',
702
+ 'CAM16-UCS',
703
+ 'CIE 1976',
704
+ 'CIE 1994',
705
+ 'CIE 2000',
706
+ 'CMC',
707
+ 'DIN99',
708
+ 'ITP',
709
+ 'cie1976',
710
+ 'cie1994',
711
+ 'cie2000']
712
+
713
+ IO - ``colour.io``
714
+ ~~~~~~~~~~~~~~~~~~
715
+
716
+ Images
717
+ ******
718
+
719
+ .. code-block:: python
720
+
721
+ RGB = colour.read_image("Ishihara_Colour_Blindness_Test_Plate_3.png")
722
+ RGB.shape
723
+
724
+ .. code-block:: text
725
+
726
+ (276, 281, 3)
727
+
728
+ Spectral Images - Fichet et al. (2021)
729
+ **************************************
730
+
731
+ .. code-block:: python
732
+
733
+ components = colour.read_spectral_image_Fichet2021("Polarised.exr")
734
+ list(components.keys())
735
+
736
+ .. code-block:: text
737
+
738
+ ['S0', 'S1', 'S2', 'S3']
739
+
740
+ Look Up Table (LUT) Data
741
+ ************************
742
+
743
+ .. code-block:: python
744
+
745
+ LUT = colour.read_LUT("ACES_Proxy_10_to_ACES.cube")
746
+ print(LUT)
747
+
748
+ .. code-block:: text
749
+
750
+ LUT3x1D - ACES Proxy 10 to ACES
751
+ -------------------------------
752
+ Dimensions : 2
753
+ Domain : [[0 0 0]
754
+ [1 1 1]]
755
+ Size : (32, 3)
756
+
757
+ .. code-block:: python
758
+
759
+ RGB = [0.17224810, 0.09170660, 0.06416938]
760
+ LUT.apply(RGB)
761
+
762
+ .. code-block:: text
763
+
764
+ array([ 0.00575674, 0.00181493, 0.00121419])
765
+
766
+ Colour Models - ``colour.models``
767
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
768
+
769
+ CIE xyY Colourspace
770
+ *******************
771
+
772
+ .. code-block:: python
773
+
774
+ colour.XYZ_to_xyY([0.20654008, 0.12197225, 0.05136952])
775
+
776
+ .. code-block:: text
777
+
778
+ array([ 0.54369557, 0.32107944, 0.12197225])
779
+
780
+ CIE L*a*b* Colourspace
781
+ **********************
782
+
783
+ .. code-block:: python
784
+
785
+ colour.XYZ_to_Lab([0.20654008, 0.12197225, 0.05136952])
786
+
787
+ .. code-block:: text
788
+
789
+ array([ 41.52787529, 52.63858304, 26.92317922])
790
+
791
+ CIE L*u*v* Colourspace
792
+ **********************
793
+
794
+ .. code-block:: python
795
+
796
+ colour.XYZ_to_Luv([0.20654008, 0.12197225, 0.05136952])
797
+
798
+ .. code-block:: text
799
+
800
+ array([ 41.52787529, 96.83626054, 17.75210149])
801
+
802
+ CIE 1960 UCS Colourspace
803
+ ************************
804
+
805
+ .. code-block:: python
806
+
807
+ colour.XYZ_to_UCS([0.20654008, 0.12197225, 0.05136952])
808
+
809
+ .. code-block:: text
810
+
811
+ array([ 0.13769339, 0.12197225, 0.1053731 ])
812
+
813
+ CIE 1964 U*V*W* Colourspace
814
+ ***************************
815
+
816
+ .. code-block:: python
817
+
818
+ XYZ = [0.20654008 * 100, 0.12197225 * 100, 0.05136952 * 100]
819
+ colour.XYZ_to_UVW(XYZ)
820
+
821
+ .. code-block:: text
822
+
823
+ array([ 94.55035725, 11.55536523, 40.54757405])
824
+
825
+ CAM02-LCD, CAM02-SCD, and CAM02-UCS Colourspaces - Luo, Cui and Li (2006)
826
+ *************************************************************************
827
+
828
+ .. code-block:: python
829
+
830
+ XYZ = [0.20654008 * 100, 0.12197225 * 100, 0.05136952 * 100]
831
+ XYZ_w = [95.05, 100.00, 108.88]
832
+ L_A = 318.31
833
+ Y_b = 20.0
834
+ surround = colour.VIEWING_CONDITIONS_CIECAM02["Average"]
835
+ specification = colour.XYZ_to_CIECAM02(XYZ, XYZ_w, L_A, Y_b, surround)
836
+ JMh = (specification.J, specification.M, specification.h)
837
+ colour.JMh_CIECAM02_to_CAM02UCS(JMh)
838
+
839
+ .. code-block:: text
840
+
841
+ array([ 47.16899898, 38.72623785, 15.8663383 ])
842
+
843
+ .. code-block:: python
844
+
845
+ XYZ = [0.20654008, 0.12197225, 0.05136952]
846
+ XYZ_w = [95.05 / 100, 100.00 / 100, 108.88 / 100]
847
+ colour.XYZ_to_CAM02UCS(XYZ, XYZ_w=XYZ_w, L_A=L_A, Y_b=Y_b)
848
+
849
+ .. code-block:: text
850
+
851
+ array([ 47.16899898, 38.72623785, 15.8663383 ])
852
+
853
+ CAM16-LCD, CAM16-SCD, and CAM16-UCS Colourspaces - Li et al. (2017)
854
+ *******************************************************************
855
+
856
+ .. code-block:: python
857
+
858
+ XYZ = [0.20654008 * 100, 0.12197225 * 100, 0.05136952 * 100]
859
+ XYZ_w = [95.05, 100.00, 108.88]
860
+ L_A = 318.31
861
+ Y_b = 20.0
862
+ surround = colour.VIEWING_CONDITIONS_CAM16["Average"]
863
+ specification = colour.XYZ_to_CAM16(XYZ, XYZ_w, L_A, Y_b, surround)
864
+ JMh = (specification.J, specification.M, specification.h)
865
+ colour.JMh_CAM16_to_CAM16UCS(JMh)
866
+
867
+ .. code-block:: text
868
+
869
+ array([ 46.55542238, 40.22460974, 14.25288392])
870
+
871
+ .. code-block:: python
872
+
873
+ XYZ = [0.20654008, 0.12197225, 0.05136952]
874
+ XYZ_w = [95.05 / 100, 100.00 / 100, 108.88 / 100]
875
+ colour.XYZ_to_CAM16UCS(XYZ, XYZ_w=XYZ_w, L_A=L_A, Y_b=Y_b)
876
+
877
+ .. code-block:: text
878
+
879
+ array([ 46.55542238, 40.22460974, 14.25288392])
880
+
881
+ DIN99 Colourspace and DIN99b, DIN99c, DIN99d Refined Formulas
882
+ *************************************************************
883
+
884
+ .. code-block:: python
885
+
886
+ Lab = [41.52787529, 52.63858304, 26.92317922]
887
+ colour.Lab_to_DIN99(Lab)
888
+
889
+ .. code-block:: text
890
+
891
+ array([ 53.22821988, 28.41634656, 3.89839552])
892
+
893
+ ICaCb Colourspace
894
+ ******************
895
+
896
+ .. code-block:: python
897
+
898
+ XYZ_to_ICaCb(np.array([0.20654008, 0.12197225, 0.05136952]))
899
+
900
+ .. code-block:: text
901
+
902
+ array([ 0.06875297, 0.05753352, 0.02081548])
903
+
904
+ IgPgTg Colourspace
905
+ ******************
906
+
907
+ .. code-block:: python
908
+
909
+ colour.XYZ_to_IgPgTg([0.20654008, 0.12197225, 0.05136952])
910
+
911
+ .. code-block:: text
912
+
913
+ array([ 0.42421258, 0.18632491, 0.10689223])
914
+
915
+ IPT Colourspace
916
+ ***************
917
+
918
+ .. code-block:: python
919
+
920
+ colour.XYZ_to_IPT([0.20654008, 0.12197225, 0.05136952])
921
+
922
+ .. code-block:: text
923
+
924
+ array([ 0.38426191, 0.38487306, 0.18886838])
925
+
926
+ Jzazbz Colourspace
927
+ ******************
928
+
929
+ .. code-block:: python
930
+
931
+ colour.XYZ_to_Jzazbz([0.20654008, 0.12197225, 0.05136952])
932
+
933
+ .. code-block:: text
934
+
935
+ array([ 0.00535048, 0.00924302, 0.00526007])
936
+
937
+ hdr-CIELAB Colourspace
938
+ **********************
939
+
940
+ .. code-block:: python
941
+
942
+ colour.XYZ_to_hdr_CIELab([0.20654008, 0.12197225, 0.05136952])
943
+
944
+ .. code-block:: text
945
+
946
+ array([ 51.87002062, 60.4763385 , 32.14551912])
947
+
948
+ hdr-IPT Colourspace
949
+ *******************
950
+
951
+ .. code-block:: python
952
+
953
+ colour.XYZ_to_hdr_IPT([0.20654008, 0.12197225, 0.05136952])
954
+
955
+ .. code-block:: text
956
+
957
+ array([ 25.18261761, -22.62111297, 3.18511729])
958
+
959
+ Hunter L,a,b Colour Scale
960
+ *************************
961
+
962
+ .. code-block:: python
963
+
964
+ XYZ = [0.20654008 * 100, 0.12197225 * 100, 0.05136952 * 100]
965
+ colour.XYZ_to_Hunter_Lab(XYZ)
966
+
967
+ .. code-block:: text
968
+
969
+ array([ 34.92452577, 47.06189858, 14.38615107])
970
+
971
+ Hunter Rd,a,b Colour Scale
972
+ **************************
973
+
974
+ .. code-block:: python
975
+
976
+ XYZ = [0.20654008 * 100, 0.12197225 * 100, 0.05136952 * 100]
977
+ colour.XYZ_to_Hunter_Rdab(XYZ)
978
+
979
+ .. code-block:: text
980
+
981
+ array([ 12.197225 , 57.12537874, 17.46241341])
982
+
983
+ Oklab Colourspace
984
+ *****************
985
+
986
+ .. code-block:: python
987
+
988
+ colour.XYZ_to_Oklab([0.20654008, 0.12197225, 0.05136952])
989
+
990
+ .. code-block:: text
991
+
992
+ array([ 0.51634019, 0.154695 , 0.06289579])
993
+
994
+ OSA UCS Colourspace
995
+ *******************
996
+
997
+ .. code-block:: python
998
+
999
+ XYZ = [0.20654008 * 100, 0.12197225 * 100, 0.05136952 * 100]
1000
+ colour.XYZ_to_OSA_UCS(XYZ)
1001
+
1002
+ .. code-block:: text
1003
+
1004
+ array([-3.0049979 , 2.99713697, -9.66784231])
1005
+
1006
+ ProLab Colourspace
1007
+ ******************
1008
+
1009
+ .. code-block:: python
1010
+
1011
+ colour.XYZ_to_ProLab([0.51634019, 0.15469500, 0.06289579])
1012
+
1013
+ .. code-block:: text
1014
+
1015
+ array([1.24610688, 2.39525236, 0.41902126])
1016
+
1017
+ Ragoo and Farup (2021) Optimised IPT Colourspace
1018
+ ************************************************
1019
+
1020
+ .. code-block:: python
1021
+
1022
+ colour.XYZ_to_IPT_Ragoo2021([0.20654008, 0.12197225, 0.05136952])
1023
+
1024
+ .. code-block:: text
1025
+
1026
+ array([ 0.42248243, 0.2910514 , 0.20410663])
1027
+
1028
+ Yrg Colourspace - Kirk (2019)
1029
+ *****************************
1030
+
1031
+ .. code-block:: python
1032
+
1033
+ colour.XYZ_to_Yrg([0.20654008, 0.12197225, 0.05136952])
1034
+
1035
+ .. code-block:: text
1036
+
1037
+ array([ 0.13137801, 0.49037645, 0.37777388])
1038
+
1039
+ Y'CbCr Colour Encoding
1040
+ **********************
1041
+
1042
+ .. code-block:: python
1043
+
1044
+ colour.RGB_to_YCbCr([1.0, 1.0, 1.0])
1045
+
1046
+ .. code-block:: text
1047
+
1048
+ array([ 0.92156863, 0.50196078, 0.50196078])
1049
+
1050
+ YCoCg Colour Encoding
1051
+ *********************
1052
+
1053
+ .. code-block:: python
1054
+
1055
+ colour.RGB_to_YCoCg([0.75, 0.75, 0.0])
1056
+
1057
+ .. code-block:: text
1058
+
1059
+ array([ 0.5625, 0.375 , 0.1875])
1060
+
1061
+ ICtCp Colour Encoding
1062
+ *********************
1063
+
1064
+ .. code-block:: python
1065
+
1066
+ colour.RGB_to_ICtCp([0.45620519, 0.03081071, 0.04091952])
1067
+
1068
+ .. code-block:: text
1069
+
1070
+ array([ 0.07351364, 0.00475253, 0.09351596])
1071
+
1072
+ HSV Colourspace
1073
+ ***************
1074
+
1075
+ .. code-block:: python
1076
+
1077
+ colour.RGB_to_HSV([0.45620519, 0.03081071, 0.04091952])
1078
+
1079
+ .. code-block:: text
1080
+
1081
+ array([ 0.99603944, 0.93246304, 0.45620519])
1082
+
1083
+ IHLS Colourspace
1084
+ ****************
1085
+
1086
+ .. code-block:: python
1087
+
1088
+ colour.RGB_to_IHLS([0.45620519, 0.03081071, 0.04091952])
1089
+
1090
+ .. code-block:: text
1091
+
1092
+ array([ 6.26236117, 0.12197943, 0.42539448])
1093
+
1094
+ Prismatic Colourspace
1095
+ *********************
1096
+
1097
+ .. code-block:: python
1098
+
1099
+ colour.RGB_to_Prismatic([0.25, 0.50, 0.75])
1100
+
1101
+ .. code-block:: text
1102
+
1103
+ array([ 0.75 , 0.16666667, 0.33333333, 0.5 ])
1104
+
1105
+ RGB Colourspace and Transformations
1106
+ ***********************************
1107
+
1108
+ .. code-block:: python
1109
+
1110
+ XYZ = [0.21638819, 0.12570000, 0.03847493]
1111
+ illuminant_XYZ = [0.34570, 0.35850]
1112
+ illuminant_RGB = [0.31270, 0.32900]
1113
+ chromatic_adaptation_transform = "Bradford"
1114
+ matrix_XYZ_to_RGB = [
1115
+ [3.24062548, -1.53720797, -0.49862860],
1116
+ [-0.96893071, 1.87575606, 0.04151752],
1117
+ [0.05571012, -0.20402105, 1.05699594],
1118
+ ]
1119
+ colour.XYZ_to_RGB(
1120
+ XYZ,
1121
+ illuminant_XYZ,
1122
+ illuminant_RGB,
1123
+ matrix_XYZ_to_RGB,
1124
+ chromatic_adaptation_transform,
1125
+ )
1126
+
1127
+ .. code-block:: text
1128
+
1129
+ array([ 0.45595571, 0.03039702, 0.04087245])
1130
+
1131
+ RGB Colourspace Derivation
1132
+ **************************
1133
+
1134
+ .. code-block:: python
1135
+
1136
+ p = [0.73470, 0.26530, 0.00000, 1.00000, 0.00010, -0.07700]
1137
+ w = [0.32168, 0.33767]
1138
+ colour.normalised_primary_matrix(p, w)
1139
+
1140
+ .. code-block:: text
1141
+
1142
+ array([[ 9.52552396e-01, 0.00000000e+00, 9.36786317e-05],
1143
+ [ 3.43966450e-01, 7.28166097e-01, -7.21325464e-02],
1144
+ [ 0.00000000e+00, 0.00000000e+00, 1.00882518e+00]])
1145
+
1146
+ RGB Colourspaces
1147
+ ****************
1148
+
1149
+ .. code-block:: python
1150
+
1151
+ sorted(colour.RGB_COLOURSPACES)
1152
+
1153
+ .. code-block:: text
1154
+
1155
+ ['ACES2065-1',
1156
+ 'ACEScc',
1157
+ 'ACEScct',
1158
+ 'ACEScg',
1159
+ 'ACESproxy',
1160
+ 'ARRI Wide Gamut 3',
1161
+ 'ARRI Wide Gamut 4',
1162
+ 'Adobe RGB (1998)',
1163
+ 'Adobe Wide Gamut RGB',
1164
+ 'Apple RGB',
1165
+ 'Best RGB',
1166
+ 'Beta RGB',
1167
+ 'Blackmagic Wide Gamut',
1168
+ 'CIE RGB',
1169
+ 'Cinema Gamut',
1170
+ 'ColorMatch RGB',
1171
+ 'DCDM XYZ',
1172
+ 'DCI-P3',
1173
+ 'DCI-P3-P',
1174
+ 'DJI D-Gamut',
1175
+ 'DRAGONcolor',
1176
+ 'DRAGONcolor2',
1177
+ 'DaVinci Wide Gamut',
1178
+ 'Display P3',
1179
+ 'Don RGB 4',
1180
+ 'EBU Tech. 3213-E',
1181
+ 'ECI RGB v2',
1182
+ 'ERIMM RGB',
1183
+ 'Ekta Space PS 5',
1184
+ 'F-Gamut',
1185
+ 'FilmLight E-Gamut',
1186
+ 'ITU-R BT.2020',
1187
+ 'ITU-R BT.470 - 525',
1188
+ 'ITU-R BT.470 - 625',
1189
+ 'ITU-R BT.709',
1190
+ 'ITU-T H.273 - 22 Unspecified',
1191
+ 'ITU-T H.273 - Generic Film',
1192
+ 'Max RGB',
1193
+ 'N-Gamut',
1194
+ 'NTSC (1953)',
1195
+ 'NTSC (1987)',
1196
+ 'P3-D65',
1197
+ 'PLASA ANSI E1.54',
1198
+ 'Pal/Secam',
1199
+ 'ProPhoto RGB',
1200
+ 'Protune Native',
1201
+ 'REDWideGamutRGB',
1202
+ 'REDcolor',
1203
+ 'REDcolor2',
1204
+ 'REDcolor3',
1205
+ 'REDcolor4',
1206
+ 'RIMM RGB',
1207
+ 'ROMM RGB',
1208
+ 'Russell RGB',
1209
+ 'S-Gamut',
1210
+ 'S-Gamut3',
1211
+ 'S-Gamut3.Cine',
1212
+ 'SMPTE 240M',
1213
+ 'SMPTE C',
1214
+ 'Sharp RGB',
1215
+ 'V-Gamut',
1216
+ 'Venice S-Gamut3',
1217
+ 'Venice S-Gamut3.Cine',
1218
+ 'Xtreme RGB',
1219
+ 'aces',
1220
+ 'adobe1998',
1221
+ 'prophoto',
1222
+ 'sRGB']
1223
+
1224
+
1225
+ OETFs
1226
+ *****
1227
+
1228
+ .. code-block:: python
1229
+
1230
+ sorted(colour.OETFS)
1231
+
1232
+ .. code-block:: text
1233
+
1234
+ ['ARIB STD-B67',
1235
+ 'Blackmagic Film Generation 5',
1236
+ 'DaVinci Intermediate',
1237
+ 'ITU-R BT.2020',
1238
+ 'ITU-R BT.2100 HLG',
1239
+ 'ITU-R BT.2100 PQ',
1240
+ 'ITU-R BT.601',
1241
+ 'ITU-R BT.709',
1242
+ 'ITU-T H.273 IEC 61966-2',
1243
+ 'ITU-T H.273 Log',
1244
+ 'ITU-T H.273 Log Sqrt',
1245
+ 'SMPTE 240M']
1246
+
1247
+
1248
+ EOTFs
1249
+ *****
1250
+
1251
+ .. code-block:: python
1252
+
1253
+ sorted(colour.EOTFS)
1254
+
1255
+ .. code-block:: text
1256
+
1257
+ ['DCDM',
1258
+ 'DICOM GSDF',
1259
+ 'ITU-R BT.1886',
1260
+ 'ITU-R BT.2100 HLG',
1261
+ 'ITU-R BT.2100 PQ',
1262
+ 'ITU-T H.273 ST.428-1',
1263
+ 'SMPTE 240M',
1264
+ 'ST 2084',
1265
+ 'sRGB']
1266
+
1267
+ OOTFs
1268
+ *****
1269
+
1270
+ .. code-block:: python
1271
+
1272
+ sorted(colour.OOTFS)
1273
+
1274
+ .. code-block:: text
1275
+
1276
+ ['ITU-R BT.2100 HLG', 'ITU-R BT.2100 PQ']
1277
+
1278
+
1279
+ Log Encoding / Decoding
1280
+ ***********************
1281
+
1282
+ .. code-block:: python
1283
+
1284
+ sorted(colour.LOG_ENCODINGS)
1285
+
1286
+ .. code-block:: text
1287
+
1288
+ ['ACEScc',
1289
+ 'ACEScct',
1290
+ 'ACESproxy',
1291
+ 'Apple Log Profile',
1292
+ 'ARRI LogC3',
1293
+ 'ARRI LogC4',
1294
+ 'Canon Log',
1295
+ 'Canon Log 2',
1296
+ 'Canon Log 3',
1297
+ 'Cineon',
1298
+ 'D-Log',
1299
+ 'ERIMM RGB',
1300
+ 'F-Log',
1301
+ 'F-Log2',
1302
+ 'Filmic Pro 6',
1303
+ 'L-Log',
1304
+ 'Log2',
1305
+ 'Log3G10',
1306
+ 'Log3G12',
1307
+ 'N-Log',
1308
+ 'PLog',
1309
+ 'Panalog',
1310
+ 'Protune',
1311
+ 'REDLog',
1312
+ 'REDLogFilm',
1313
+ 'S-Log',
1314
+ 'S-Log2',
1315
+ 'S-Log3',
1316
+ 'T-Log',
1317
+ 'V-Log',
1318
+ 'ViperLog']
1319
+
1320
+ CCTFs Encoding / Decoding
1321
+ *************************
1322
+
1323
+ .. code-block:: python
1324
+
1325
+ sorted(colour.CCTF_ENCODINGS)
1326
+
1327
+ .. code-block:: text
1328
+
1329
+ ['ACEScc',
1330
+ 'ACEScct',
1331
+ 'ACESproxy',
1332
+ 'Apple Log Profile',
1333
+ 'ARRI LogC3',
1334
+ 'ARRI LogC4',
1335
+ 'ARIB STD-B67',
1336
+ 'Canon Log',
1337
+ 'Canon Log 2',
1338
+ 'Canon Log 3',
1339
+ 'Cineon',
1340
+ 'D-Log',
1341
+ 'DCDM',
1342
+ 'DICOM GSDF',
1343
+ 'ERIMM RGB',
1344
+ 'F-Log',
1345
+ 'F-Log2',
1346
+ 'Filmic Pro 6',
1347
+ 'Gamma 2.2',
1348
+ 'Gamma 2.4',
1349
+ 'Gamma 2.6',
1350
+ 'ITU-R BT.1886',
1351
+ 'ITU-R BT.2020',
1352
+ 'ITU-R BT.2100 HLG',
1353
+ 'ITU-R BT.2100 PQ',
1354
+ 'ITU-R BT.601',
1355
+ 'ITU-R BT.709',
1356
+ 'Log2',
1357
+ 'Log3G10',
1358
+ 'Log3G12',
1359
+ 'PLog',
1360
+ 'Panalog',
1361
+ 'ProPhoto RGB',
1362
+ 'Protune',
1363
+ 'REDLog',
1364
+ 'REDLogFilm',
1365
+ 'RIMM RGB',
1366
+ 'ROMM RGB',
1367
+ 'S-Log',
1368
+ 'S-Log2',
1369
+ 'S-Log3',
1370
+ 'SMPTE 240M',
1371
+ 'ST 2084',
1372
+ 'T-Log',
1373
+ 'V-Log',
1374
+ 'ViperLog',
1375
+ 'sRGB']
1376
+
1377
+ Recommendation ITU-T H.273 Code points for Video Signal Type Identification
1378
+ ***************************************************************************
1379
+
1380
+ .. code-block:: python
1381
+
1382
+ colour.COLOUR_PRIMARIES_ITUTH273.keys()
1383
+
1384
+ .. code-block:: text
1385
+
1386
+ dict_keys([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 22, 23])
1387
+
1388
+ .. code-block:: python
1389
+
1390
+ colour.models.describe_video_signal_colour_primaries(1)
1391
+
1392
+ .. code-block:: text
1393
+
1394
+ ===============================================================================
1395
+ * *
1396
+ * Colour Primaries: 1 *
1397
+ * ------------------- *
1398
+ * *
1399
+ * Primaries : [[ 0.64 0.33] *
1400
+ * [ 0.3 0.6 ] *
1401
+ * [ 0.15 0.06]] *
1402
+ * Whitepoint : [ 0.3127 0.329 ] *
1403
+ * Whitepoint Name : D65 *
1404
+ * NPM : [[ 0.4123908 0.35758434 0.18048079] *
1405
+ * [ 0.21263901 0.71516868 0.07219232] *
1406
+ * [ 0.01933082 0.11919478 0.95053215]] *
1407
+ * NPM -1 : [[ 3.24096994 -1.53738318 -0.49861076] *
1408
+ * [-0.96924364 1.8759675 0.04155506] *
1409
+ * [ 0.05563008 -0.20397696 1.05697151]] *
1410
+ * FFmpeg Constants : ['AVCOL_PRI_BT709', 'BT709'] *
1411
+ * *
1412
+ ===============================================================================
1413
+
1414
+ .. code-block:: python
1415
+
1416
+ colour.TRANSFER_CHARACTERISTICS_ITUTH273.keys()
1417
+
1418
+ .. code-block:: text
1419
+
1420
+ dict_keys([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19])
1421
+
1422
+ .. code-block:: python
1423
+
1424
+ colour.models.describe_video_signal_transfer_characteristics(1)
1425
+
1426
+ .. code-block:: text
1427
+
1428
+ ===============================================================================
1429
+ * *
1430
+ * Transfer Characteristics: 1 *
1431
+ * --------------------------- *
1432
+ * *
1433
+ * Function : <function oetf_BT709 at 0x165bb3550> *
1434
+ * FFmpeg Constants : ['AVCOL_TRC_BT709', 'BT709'] *
1435
+ * *
1436
+ ===============================================================================
1437
+
1438
+ .. code-block:: python
1439
+
1440
+ colour.MATRIX_COEFFICIENTS_ITUTH273.keys()
1441
+
1442
+ .. code-block:: text
1443
+
1444
+ dict_keys([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])
1445
+
1446
+ .. code-block:: python
1447
+
1448
+ colour.models.describe_video_signal_matrix_coefficients(1)
1449
+
1450
+ .. code-block:: text
1451
+
1452
+ ===============================================================================
1453
+ * *
1454
+ * Matrix Coefficients: 1 *
1455
+ * ---------------------- *
1456
+ * *
1457
+ * Matrix Coefficients : [ 0.2126 0.0722] *
1458
+ * FFmpeg Constants : ['AVCOL_SPC_BT709', 'BT709'] *
1459
+ * *
1460
+ ===============================================================================
1461
+
1462
+ Colour Notation Systems - ``colour.notation``
1463
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1464
+
1465
+ Munsell Value
1466
+ *************
1467
+
1468
+ .. code-block:: python
1469
+
1470
+ colour.munsell_value(12.23634268)
1471
+
1472
+ .. code-block:: text
1473
+
1474
+ 4.0824437076525664
1475
+
1476
+ .. code-block:: python
1477
+
1478
+ sorted(colour.MUNSELL_VALUE_METHODS)
1479
+
1480
+ .. code-block:: text
1481
+
1482
+ ['ASTM D1535',
1483
+ 'Ladd 1955',
1484
+ 'McCamy 1987',
1485
+ 'Moon 1943',
1486
+ 'Munsell 1933',
1487
+ 'Priest 1920',
1488
+ 'Saunderson 1944',
1489
+ 'astm2008']
1490
+
1491
+ Munsell Colour
1492
+ **************
1493
+
1494
+ .. code-block:: python
1495
+
1496
+ colour.xyY_to_munsell_colour([0.38736945, 0.35751656, 0.59362000])
1497
+
1498
+ .. code-block:: text
1499
+
1500
+ '4.2YR 8.1/5.3'
1501
+
1502
+ .. code-block:: python
1503
+
1504
+ colour.munsell_colour_to_xyY("4.2YR 8.1/5.3")
1505
+
1506
+ .. code-block:: text
1507
+
1508
+ array([ 0.38736945, 0.35751656, 0.59362 ])
1509
+
1510
+ Optical Phenomena - ``colour.phenomena``
1511
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1512
+
1513
+ .. code-block:: python
1514
+
1515
+ colour.rayleigh_scattering_sd()
1516
+
1517
+ .. code-block:: text
1518
+
1519
+ SpectralDistribution([[ 3.60000000e+02, 5.99101337e-01],
1520
+ [ 3.61000000e+02, 5.92170690e-01],
1521
+ [ 3.62000000e+02, 5.85341006e-01],
1522
+ ...
1523
+ [ 7.78000000e+02, 2.55208377e-02],
1524
+ [ 7.79000000e+02, 2.53887969e-02],
1525
+ [ 7.80000000e+02, 2.52576106e-02]],
1526
+ interpolator=SpragueInterpolator,
1527
+ interpolator_args={},
1528
+ extrapolator=Extrapolator,
1529
+ extrapolator_args={'right': None, 'method': 'Constant', 'left': None})
1530
+
1531
+ Light Quality - ``colour.quality``
1532
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1533
+
1534
+ Colour Fidelity Index
1535
+ *********************
1536
+
1537
+ .. code-block:: python
1538
+
1539
+ colour.colour_fidelity_index(colour.SDS_ILLUMINANTS["FL2"])
1540
+
1541
+ .. code-block:: text
1542
+
1543
+ 70.120825477833037
1544
+
1545
+ .. code-block:: python
1546
+
1547
+ sorted(colour.COLOUR_FIDELITY_INDEX_METHODS)
1548
+
1549
+ .. code-block:: text
1550
+
1551
+ ['ANSI/IES TM-30-18', 'CIE 2017']
1552
+
1553
+ Colour Quality Scale
1554
+ ********************
1555
+
1556
+ .. code-block:: python
1557
+
1558
+ colour.colour_quality_scale(colour.SDS_ILLUMINANTS["FL2"])
1559
+
1560
+ .. code-block:: text
1561
+
1562
+ 64.111703163816699
1563
+
1564
+ .. code-block:: python
1565
+
1566
+ sorted(colour.COLOUR_QUALITY_SCALE_METHODS)
1567
+
1568
+ .. code-block:: text
1569
+
1570
+ ['NIST CQS 7.4', 'NIST CQS 9.0']
1571
+
1572
+ Colour Rendering Index
1573
+ **********************
1574
+
1575
+ .. code-block:: python
1576
+
1577
+ colour.colour_rendering_index(colour.SDS_ILLUMINANTS["FL2"])
1578
+
1579
+ .. code-block:: text
1580
+
1581
+ 64.233724121664807
1582
+
1583
+ Academy Spectral Similarity Index (SSI)
1584
+ ***************************************
1585
+
1586
+ .. code-block:: python
1587
+
1588
+ colour.spectral_similarity_index(
1589
+ colour.SDS_ILLUMINANTS["C"], colour.SDS_ILLUMINANTS["D65"]
1590
+ )
1591
+
1592
+ .. code-block:: text
1593
+
1594
+ 94.0
1595
+
1596
+ Spectral Up-Sampling & Recovery - ``colour.recovery``
1597
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1598
+
1599
+ Reflectance Recovery
1600
+ ********************
1601
+
1602
+ .. code-block:: python
1603
+
1604
+ colour.XYZ_to_sd([0.20654008, 0.12197225, 0.05136952])
1605
+
1606
+ .. code-block:: text
1607
+
1608
+ SpectralDistribution([[ 3.60000000e+02, 8.40144095e-02],
1609
+ [ 3.65000000e+02, 8.41264236e-02],
1610
+ [ 3.70000000e+02, 8.40057597e-02],
1611
+ ...
1612
+ [ 7.70000000e+02, 4.46743012e-01],
1613
+ [ 7.75000000e+02, 4.46817187e-01],
1614
+ [ 7.80000000e+02, 4.46857696e-01]],
1615
+ SpragueInterpolator,
1616
+ {},
1617
+ Extrapolator,
1618
+ {'method': 'Constant', 'left': None, 'right': None})
1619
+
1620
+ .. code-block:: python
1621
+
1622
+ sorted(colour.REFLECTANCE_RECOVERY_METHODS)
1623
+
1624
+ .. code-block:: text
1625
+
1626
+ ['Jakob 2019', 'Mallett 2019', 'Meng 2015', 'Otsu 2018', 'Smits 1999']
1627
+
1628
+ Camera RGB Sensitivities Recovery
1629
+ *********************************
1630
+
1631
+ .. code-block:: python
1632
+
1633
+ illuminant = colour.colorimetry.SDS_ILLUMINANTS["D65"]
1634
+ sensitivities = colour.characterisation.MSDS_CAMERA_SENSITIVITIES["Nikon 5100 (NPL)"]
1635
+ reflectances = [
1636
+ sd.copy().align(colour.recovery.SPECTRAL_SHAPE_BASIS_FUNCTIONS_DYER2017)
1637
+ for sd in colour.characterisation.SDS_COLOURCHECKERS["BabelColor Average"].values()
1638
+ ]
1639
+ reflectances = colour.colorimetry.sds_and_msds_to_msds(reflectances)
1640
+ RGB = colour.colorimetry.msds_to_XYZ(
1641
+ reflectances,
1642
+ method="Integration",
1643
+ cmfs=sensitivities,
1644
+ illuminant=illuminant,
1645
+ k=0.01,
1646
+ shape=colour.recovery.SPECTRAL_SHAPE_BASIS_FUNCTIONS_DYER2017,
1647
+ )
1648
+ colour.recovery.RGB_to_msds_camera_sensitivities_Jiang2013(
1649
+ RGB,
1650
+ illuminant,
1651
+ reflectances,
1652
+ colour.recovery.BASIS_FUNCTIONS_DYER2017,
1653
+ colour.recovery.SPECTRAL_SHAPE_BASIS_FUNCTIONS_DYER2017,
1654
+ )
1655
+
1656
+ .. code-block:: text
1657
+
1658
+ RGB_CameraSensitivities([[ 4.00000000e+02, 7.22815777e-03, 9.22506480e-03,
1659
+ -9.88368972e-03],
1660
+ [ 4.10000000e+02, -8.50457609e-03, 1.12777480e-02,
1661
+ 3.86248655e-03],
1662
+ [ 4.20000000e+02, 4.58191132e-02, 7.15520948e-02,
1663
+ 4.04068293e-01],
1664
+ ...
1665
+ [ 6.80000000e+02, 4.08276173e-02, 5.55290476e-03,
1666
+ 1.39907862e-03],
1667
+ [ 6.90000000e+02, -3.71437574e-03, 2.50935640e-03,
1668
+ 3.97652622e-04],
1669
+ [ 7.00000000e+02, -5.62256563e-03, 1.56433970e-03,
1670
+ 5.84726936e-04]],
1671
+ ['red', 'green', 'blue'],
1672
+ SpragueInterpolator,
1673
+ {},
1674
+ Extrapolator,
1675
+ {'method': 'Constant', 'left': None, 'right': None})
1676
+
1677
+ Correlated Colour Temperature Computation Methods - ``colour.temperature``
1678
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1679
+
1680
+ .. code-block:: python
1681
+
1682
+ colour.uv_to_CCT([0.1978, 0.3122])
1683
+
1684
+ .. code-block:: text
1685
+
1686
+ array([ 6.50751282e+03, 3.22335875e-03])
1687
+
1688
+ .. code-block:: python
1689
+
1690
+ sorted(colour.UV_TO_CCT_METHODS)
1691
+
1692
+ .. code-block:: text
1693
+
1694
+ ['Krystek 1985', 'Ohno 2013', 'Planck 1900', 'Robertson 1968', 'ohno2013', 'robertson1968']
1695
+
1696
+ .. code-block:: python
1697
+
1698
+ sorted(colour.XY_TO_CCT_METHODS)
1699
+
1700
+ .. code-block:: text
1701
+
1702
+ ['CIE Illuminant D Series',
1703
+ 'Hernandez 1999',
1704
+ 'Kang 2002',
1705
+ 'McCamy 1992',
1706
+ 'daylight',
1707
+ 'hernandez1999',
1708
+ 'kang2002',
1709
+ 'mccamy1992']
1710
+
1711
+ Colour Volume - ``colour.volume``
1712
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1713
+
1714
+ .. code-block:: python
1715
+
1716
+ colour.RGB_colourspace_volume_MonteCarlo(colour.RGB_COLOURSPACE_RGB["sRGB"])
1717
+
1718
+ .. code-block:: text
1719
+
1720
+ 821958.30000000005
1721
+
1722
+ Geometry Primitives Generation - ``colour.geometry``
1723
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1724
+
1725
+ .. code-block:: python
1726
+
1727
+ colour.primitive("Grid")
1728
+
1729
+ .. code-block:: text
1730
+
1731
+ (array([ ([-0.5, 0.5, 0. ], [ 0., 1.], [ 0., 0., 1.], [ 0., 1., 0., 1.]),
1732
+ ([ 0.5, 0.5, 0. ], [ 1., 1.], [ 0., 0., 1.], [ 1., 1., 0., 1.]),
1733
+ ([-0.5, -0.5, 0. ], [ 0., 0.], [ 0., 0., 1.], [ 0., 0., 0., 1.]),
1734
+ ([ 0.5, -0.5, 0. ], [ 1., 0.], [ 0., 0., 1.], [ 1., 0., 0., 1.])],
1735
+ dtype=[('position', '<f4', (3,)), ('uv', '<f4', (2,)), ('normal', '<f4', (3,)), ('colour', '<f4', (4,))]), array([[0, 2, 1],
1736
+ [2, 3, 1]], dtype=uint32), array([[0, 2],
1737
+ [2, 3],
1738
+ [3, 1],
1739
+ [1, 0]], dtype=uint32))
1740
+
1741
+ .. code-block:: python
1742
+
1743
+ sorted(colour.PRIMITIVE_METHODS)
1744
+
1745
+ .. code-block:: text
1746
+
1747
+ ['Cube', 'Grid']
1748
+
1749
+ .. code-block:: python
1750
+
1751
+ colour.primitive_vertices("Quad MPL")
1752
+
1753
+ .. code-block:: text
1754
+
1755
+ array([[ 0., 0., 0.],
1756
+ [ 1., 0., 0.],
1757
+ [ 1., 1., 0.],
1758
+ [ 0., 1., 0.]])
1759
+ sorted(colour.PRIMITIVE_VERTICES_METHODS)
1760
+ ['Cube MPL', 'Grid MPL', 'Quad MPL', 'Sphere']
1761
+
1762
+ Plotting - ``colour.plotting``
1763
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1764
+
1765
+ Most of the objects are available from the ``colour.plotting`` namespace:
1766
+
1767
+ .. code-block:: python
1768
+
1769
+ from colour.plotting import *
1770
+
1771
+ colour_style()
1772
+
1773
+ Visible Spectrum
1774
+ ****************
1775
+
1776
+ .. code-block:: python
1777
+
1778
+ plot_visible_spectrum("CIE 1931 2 Degree Standard Observer")
1779
+
1780
+ .. image:: https://colour.readthedocs.io/en/develop/_static/Examples_Plotting_Visible_Spectrum.png
1781
+
1782
+ Spectral Distribution
1783
+ *********************
1784
+
1785
+ .. code-block:: python
1786
+
1787
+ plot_single_illuminant_sd("FL1")
1788
+
1789
+ .. image:: https://colour.readthedocs.io/en/develop/_static/Examples_Plotting_Illuminant_F1_SD.png
1790
+
1791
+ Blackbody
1792
+ *********
1793
+
1794
+ .. code-block:: python
1795
+
1796
+ blackbody_sds = [
1797
+ colour.sd_blackbody(i, colour.SpectralShape(0, 10000, 10))
1798
+ for i in range(1000, 15000, 1000)
1799
+ ]
1800
+ plot_multi_sds(
1801
+ blackbody_sds,
1802
+ y_label="W / (sr m$^2$) / m",
1803
+ plot_kwargs={"use_sd_colours": True, "normalise_sd_colours": True},
1804
+ legend_location="upper right",
1805
+ bounding_box=(0, 1250, 0, 2.5e6),
1806
+ )
1807
+
1808
+ .. image:: https://colour.readthedocs.io/en/develop/_static/Examples_Plotting_Blackbodies.png
1809
+
1810
+ Colour Matching Functions
1811
+ *************************
1812
+
1813
+ .. code-block:: python
1814
+
1815
+ plot_single_cmfs(
1816
+ "Stockman & Sharpe 2 Degree Cone Fundamentals",
1817
+ y_label="Sensitivity",
1818
+ bounding_box=(390, 870, 0, 1.1),
1819
+ )
1820
+
1821
+ .. image:: https://colour.readthedocs.io/en/develop/_static/Examples_Plotting_Cone_Fundamentals.png
1822
+
1823
+ Luminous Efficiency
1824
+ *******************
1825
+
1826
+ .. code-block:: python
1827
+
1828
+ sd_mesopic_luminous_efficiency_function = (
1829
+ colour.sd_mesopic_luminous_efficiency_function(0.2)
1830
+ )
1831
+ plot_multi_sds(
1832
+ (
1833
+ sd_mesopic_luminous_efficiency_function,
1834
+ colour.PHOTOPIC_LEFS["CIE 1924 Photopic Standard Observer"],
1835
+ colour.SCOTOPIC_LEFS["CIE 1951 Scotopic Standard Observer"],
1836
+ ),
1837
+ y_label="Luminous Efficiency",
1838
+ legend_location="upper right",
1839
+ y_tighten=True,
1840
+ margins=(0, 0, 0, 0.1),
1841
+ )
1842
+
1843
+ .. image:: https://colour.readthedocs.io/en/develop/_static/Examples_Plotting_Luminous_Efficiency.png
1844
+
1845
+ Colour Checker
1846
+ **************
1847
+
1848
+ .. code-block:: python
1849
+
1850
+ from colour.characterisation.dataset.colour_checkers.sds import (
1851
+ COLOURCHECKER_INDEXES_TO_NAMES_MAPPING,
1852
+ )
1853
+
1854
+ plot_multi_sds(
1855
+ [
1856
+ colour.SDS_COLOURCHECKERS["BabelColor Average"][value]
1857
+ for key, value in sorted(COLOURCHECKER_INDEXES_TO_NAMES_MAPPING.items())
1858
+ ],
1859
+ plot_kwargs={
1860
+ "use_sd_colours": True,
1861
+ },
1862
+ title=("BabelColor Average - " "Spectral Distributions"),
1863
+ )
1864
+
1865
+ .. image:: https://colour.readthedocs.io/en/develop/_static/Examples_Plotting_BabelColor_Average.png
1866
+
1867
+ .. code-block:: python
1868
+
1869
+ plot_single_colour_checker("ColorChecker 2005", text_kwargs={"visible": False})
1870
+
1871
+ .. image:: https://colour.readthedocs.io/en/develop/_static/Examples_Plotting_ColorChecker_2005.png
1872
+
1873
+ Chromaticities Prediction
1874
+ *************************
1875
+
1876
+ .. code-block:: python
1877
+
1878
+ plot_corresponding_chromaticities_prediction(2, "Von Kries", "Bianco 2010")
1879
+
1880
+ .. image:: https://colour.readthedocs.io/en/develop/_static/Examples_Plotting_Chromaticities_Prediction.png
1881
+
1882
+ Chromaticities
1883
+ **************
1884
+
1885
+ .. code-block:: python
1886
+
1887
+ import numpy as np
1888
+
1889
+ RGB = np.random.random((32, 32, 3))
1890
+ plot_RGB_chromaticities_in_chromaticity_diagram_CIE1931(
1891
+ RGB,
1892
+ "ITU-R BT.709",
1893
+ colourspaces=["ACEScg", "S-Gamut", "Pointer Gamut"],
1894
+ )
1895
+
1896
+ .. image:: https://colour.readthedocs.io/en/develop/_static/Examples_Plotting_Chromaticities_CIE_1931_Chromaticity_Diagram.png
1897
+
1898
+ Colour Rendering Index Bars
1899
+ ***************************
1900
+
1901
+ .. code-block:: python
1902
+
1903
+ plot_single_sd_colour_rendering_index_bars(colour.SDS_ILLUMINANTS["FL2"])
1904
+
1905
+ .. image:: https://colour.readthedocs.io/en/develop/_static/Examples_Plotting_CRI.png
1906
+
1907
+ ANSI/IES TM-30-18 Colour Rendition Report
1908
+ *****************************************
1909
+
1910
+ .. code-block:: python
1911
+
1912
+ plot_single_sd_colour_rendition_report(colour.SDS_ILLUMINANTS["FL2"])
1913
+
1914
+ .. image:: https://colour.readthedocs.io/en/develop/_static/Examples_Plotting_Colour_Rendition_Report.png
1915
+
1916
+ Gamut Section
1917
+ *************
1918
+
1919
+ .. code-block:: python
1920
+
1921
+ plot_visible_spectrum_section(section_colours="RGB", section_opacity=0.15)
1922
+
1923
+ .. image:: https://colour.readthedocs.io/en/develop/_static/Examples_Plotting_Plot_Visible_Spectrum_Section.png
1924
+
1925
+ .. code-block:: python
1926
+
1927
+ plot_RGB_colourspace_section("sRGB", section_colours="RGB", section_opacity=0.15)
1928
+
1929
+ .. image:: https://colour.readthedocs.io/en/develop/_static/Examples_Plotting_Plot_RGB_Colourspace_Section.png
1930
+
1931
+ Colour Temperature
1932
+ ******************
1933
+
1934
+ .. code-block:: python
1935
+
1936
+ plot_planckian_locus_in_chromaticity_diagram_CIE1960UCS(["A", "B", "C"])
1937
+
1938
+ .. image:: https://colour.readthedocs.io/en/develop/_static/Examples_Plotting_CCT_CIE_1960_UCS_Chromaticity_Diagram.png
1939
+
1940
+ User Guide
1941
+ ----------
1942
+
1943
+ Installation
1944
+ ~~~~~~~~~~~~
1945
+
1946
+ **Colour** and its primary dependencies can be easily installed from the
1947
+ `Python Package Index <https://pypi.org/project/colour-science>`__
1948
+ by issuing this command in a shell:
1949
+
1950
+ .. code-block:: bash
1951
+
1952
+ $ pip install --user colour-science
1953
+
1954
+ The detailed installation procedure for the secondary dependencies is
1955
+ described in the `Installation Guide <https://www.colour-science.org/installation-guide>`__.
1956
+
1957
+ **Colour** is also available for `Anaconda <https://www.anaconda.com/download>`__
1958
+ from *Continuum Analytics* via `conda-forge <https://conda-forge.org>`__:
1959
+
1960
+ .. code-block:: bash
1961
+
1962
+ $ conda install -c conda-forge colour-science
1963
+
1964
+ Tutorial
1965
+ ~~~~~~~~
1966
+
1967
+ The `static tutorial <https://colour.readthedocs.io/en/develop/tutorial.html>`__
1968
+ provides an introduction to **Colour**. An interactive version is available via
1969
+ `Google Colab <https://colab.research.google.com/notebook#fileId=1Im9J7or9qyClQCv5sPHmKdyiQbG4898K&offline=true&sandboxMode=true>`__.
1970
+
1971
+ How-To
1972
+ ~~~~~~
1973
+
1974
+ The `Google Colab How-To <https://colab.research.google.com/notebook#fileId=1NRcdXSCshivkwoU2nieCvC3y14fx1X4X&offline=true&sandboxMode=true>`__
1975
+ guide for **Colour** shows various techniques to solve specific problems and
1976
+ highlights some interesting use cases.
1977
+
1978
+ Contributing
1979
+ ~~~~~~~~~~~~
1980
+
1981
+ If you would like to contribute to **Colour**, please refer to the following
1982
+ `Contributing <https://www.colour-science.org/contributing>`__ guide.
1983
+
1984
+ Changes
1985
+ ~~~~~~~
1986
+
1987
+ The changes are viewable on the `Releases <https://github.com/colour-science/colour/releases>`__ page.
1988
+
1989
+ Bibliography
1990
+ ~~~~~~~~~~~~
1991
+
1992
+ The bibliography is available on the `Bibliography <https://www.colour-science.org/bibliography>`__ page.
1993
+
1994
+ It is also viewable directly from the repository in
1995
+ `BibTeX <https://github.com/colour-science/colour/blob/develop/BIBLIOGRAPHY.bib>`__
1996
+ format.
1997
+
1998
+ API Reference
1999
+ -------------
2000
+
2001
+ The main technical reference for **Colour** is the *API Reference*:
2002
+
2003
+ - `Release <https://colour.readthedocs.io/en/master/reference.html>`__
2004
+ - `Develop <https://colour.readthedocs.io/en/latest/reference.html>`__
2005
+
2006
+ See Also
2007
+ --------
2008
+
2009
+ Software
2010
+ ~~~~~~~~
2011
+
2012
+ **Python**
2013
+
2014
+ - `ColorAide <https://facelessuser.github.io/coloraide>`__ by Muse, I.
2015
+ - `ColorPy <http://markkness.net/colorpy/ColorPy.html>`__ by Kness, M.
2016
+ - `Colorspacious <https://colorspacious.readthedocs.io>`__ by Smith, N. J., et al.
2017
+ - `python-colormath <https://python-colormath.readthedocs.io>`__ by Taylor, G., et al.
2018
+
2019
+ **Go**
2020
+
2021
+ - `go-colorful <https://github.com/lucasb-eyer/go-colorful>`__ by Beyer, L., et al.
2022
+
2023
+ **.NET**
2024
+
2025
+ - `Colourful <https://github.com/tompazourek/Colourful>`__ by Pažourek, T., et al.
2026
+
2027
+ **Julia**
2028
+
2029
+ - `Colors.jl <https://github.com/JuliaGraphics/Colors.jl>`__ by Holy, T., et al.
2030
+
2031
+ **Matlab & Octave**
2032
+
2033
+ - `COLORLAB <https://www.uv.es/vista/vistavalencia/software/colorlab.html>`__ by Malo, J., et al.
2034
+ - `Psychtoolbox <http://psychtoolbox.org>`__ by Brainard, D., et al.
2035
+ - `The Munsell and Kubelka-Munk Toolbox <http://www.munsellcolourscienceforpainters.com/MunsellAndKubelkaMunkToolbox/MunsellAndKubelkaMunkToolbox.html>`__ by Centore, P.
2036
+
2037
+ Code of Conduct
2038
+ ---------------
2039
+
2040
+ The *Code of Conduct*, adapted from the `Contributor Covenant 1.4 <https://www.contributor-covenant.org/version/1/4/code-of-conduct.html>`__,
2041
+ is available on the `Code of Conduct <https://www.colour-science.org/code-of-conduct>`__ page.
2042
+
2043
+ Contact & Social
2044
+ ----------------
2045
+
2046
+ The *Colour Developers* can be reached via different means:
2047
+
2048
+ - `Email <mailto:colour-developers@colour-science.org>`__
2049
+ - `Facebook <https://www.facebook.com/python.colour.science>`__
2050
+ - `Github Discussions <https://github.com/colour-science/colour/discussions>`__
2051
+ - `Gitter <https://gitter.im/colour-science/colour>`__
2052
+ - `Twitter <https://twitter.com/colour_science>`__
2053
+
2054
+
2055
+
2056
+ About
2057
+ -----
2058
+
2059
+ | **Colour** by Colour Developers
2060
+ | Copyright 2013 Colour Developers – `colour-developers@colour-science.org <colour-developers@colour-science.org>`__
2061
+ | This software is released under terms of BSD-3-Clause: https://opensource.org/licenses/BSD-3-Clause
2062
+ | `https://github.com/colour-science/colour <https://github.com/colour-science/colour>`__
python_embeded/Lib/site-packages/colour_science-0.4.6.dist-info/REQUESTED ADDED
File without changes
python_embeded/Lib/site-packages/diffusers-0.34.0.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
python_embeded/Lib/site-packages/diffusers-0.34.0.dist-info/LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
python_embeded/Lib/site-packages/diffusers-0.34.0.dist-info/METADATA ADDED
@@ -0,0 +1,372 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.2
2
+ Name: diffusers
3
+ Version: 0.34.0
4
+ Summary: State-of-the-art diffusion in PyTorch and JAX.
5
+ Home-page: https://github.com/huggingface/diffusers
6
+ Author: The Hugging Face team (past and future) with the help of all our contributors (https://github.com/huggingface/diffusers/graphs/contributors)
7
+ Author-email: diffusers@huggingface.co
8
+ License: Apache 2.0 License
9
+ Keywords: deep learning diffusion jax pytorch stable diffusion audioldm
10
+ Classifier: Development Status :: 5 - Production/Stable
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Intended Audience :: Education
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.8
19
+ Classifier: Programming Language :: Python :: 3.9
20
+ Classifier: Programming Language :: Python :: 3.10
21
+ Requires-Python: >=3.8.0
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: importlib_metadata
25
+ Requires-Dist: filelock
26
+ Requires-Dist: huggingface-hub>=0.27.0
27
+ Requires-Dist: numpy
28
+ Requires-Dist: regex!=2019.12.17
29
+ Requires-Dist: requests
30
+ Requires-Dist: safetensors>=0.3.1
31
+ Requires-Dist: Pillow
32
+ Provides-Extra: quality
33
+ Requires-Dist: urllib3<=2.0.0; extra == "quality"
34
+ Requires-Dist: isort>=5.5.4; extra == "quality"
35
+ Requires-Dist: ruff==0.9.10; extra == "quality"
36
+ Requires-Dist: hf-doc-builder>=0.3.0; extra == "quality"
37
+ Provides-Extra: docs
38
+ Requires-Dist: hf-doc-builder>=0.3.0; extra == "docs"
39
+ Provides-Extra: training
40
+ Requires-Dist: accelerate>=0.31.0; extra == "training"
41
+ Requires-Dist: datasets; extra == "training"
42
+ Requires-Dist: protobuf<4,>=3.20.3; extra == "training"
43
+ Requires-Dist: tensorboard; extra == "training"
44
+ Requires-Dist: Jinja2; extra == "training"
45
+ Requires-Dist: peft>=0.15.0; extra == "training"
46
+ Provides-Extra: test
47
+ Requires-Dist: compel==0.1.8; extra == "test"
48
+ Requires-Dist: GitPython<3.1.19; extra == "test"
49
+ Requires-Dist: datasets; extra == "test"
50
+ Requires-Dist: Jinja2; extra == "test"
51
+ Requires-Dist: invisible-watermark>=0.2.0; extra == "test"
52
+ Requires-Dist: k-diffusion>=0.0.12; extra == "test"
53
+ Requires-Dist: librosa; extra == "test"
54
+ Requires-Dist: parameterized; extra == "test"
55
+ Requires-Dist: pytest; extra == "test"
56
+ Requires-Dist: pytest-timeout; extra == "test"
57
+ Requires-Dist: pytest-xdist; extra == "test"
58
+ Requires-Dist: requests-mock==1.10.0; extra == "test"
59
+ Requires-Dist: safetensors>=0.3.1; extra == "test"
60
+ Requires-Dist: sentencepiece!=0.1.92,>=0.1.91; extra == "test"
61
+ Requires-Dist: scipy; extra == "test"
62
+ Requires-Dist: tiktoken>=0.7.0; extra == "test"
63
+ Requires-Dist: torchvision; extra == "test"
64
+ Requires-Dist: transformers>=4.41.2; extra == "test"
65
+ Requires-Dist: phonemizer; extra == "test"
66
+ Provides-Extra: torch
67
+ Requires-Dist: torch>=1.4; extra == "torch"
68
+ Requires-Dist: accelerate>=0.31.0; extra == "torch"
69
+ Provides-Extra: bitsandbytes
70
+ Requires-Dist: bitsandbytes>=0.43.3; extra == "bitsandbytes"
71
+ Requires-Dist: accelerate>=0.31.0; extra == "bitsandbytes"
72
+ Provides-Extra: gguf
73
+ Requires-Dist: gguf>=0.10.0; extra == "gguf"
74
+ Requires-Dist: accelerate>=0.31.0; extra == "gguf"
75
+ Provides-Extra: optimum-quanto
76
+ Requires-Dist: optimum_quanto>=0.2.6; extra == "optimum-quanto"
77
+ Requires-Dist: accelerate>=0.31.0; extra == "optimum-quanto"
78
+ Provides-Extra: torchao
79
+ Requires-Dist: torchao>=0.7.0; extra == "torchao"
80
+ Requires-Dist: accelerate>=0.31.0; extra == "torchao"
81
+ Provides-Extra: flax
82
+ Requires-Dist: jax>=0.4.1; extra == "flax"
83
+ Requires-Dist: jaxlib>=0.4.1; extra == "flax"
84
+ Requires-Dist: flax>=0.4.1; extra == "flax"
85
+ Provides-Extra: dev
86
+ Requires-Dist: urllib3<=2.0.0; extra == "dev"
87
+ Requires-Dist: isort>=5.5.4; extra == "dev"
88
+ Requires-Dist: ruff==0.9.10; extra == "dev"
89
+ Requires-Dist: hf-doc-builder>=0.3.0; extra == "dev"
90
+ Requires-Dist: compel==0.1.8; extra == "dev"
91
+ Requires-Dist: GitPython<3.1.19; extra == "dev"
92
+ Requires-Dist: datasets; extra == "dev"
93
+ Requires-Dist: Jinja2; extra == "dev"
94
+ Requires-Dist: invisible-watermark>=0.2.0; extra == "dev"
95
+ Requires-Dist: k-diffusion>=0.0.12; extra == "dev"
96
+ Requires-Dist: librosa; extra == "dev"
97
+ Requires-Dist: parameterized; extra == "dev"
98
+ Requires-Dist: pytest; extra == "dev"
99
+ Requires-Dist: pytest-timeout; extra == "dev"
100
+ Requires-Dist: pytest-xdist; extra == "dev"
101
+ Requires-Dist: requests-mock==1.10.0; extra == "dev"
102
+ Requires-Dist: safetensors>=0.3.1; extra == "dev"
103
+ Requires-Dist: sentencepiece!=0.1.92,>=0.1.91; extra == "dev"
104
+ Requires-Dist: scipy; extra == "dev"
105
+ Requires-Dist: tiktoken>=0.7.0; extra == "dev"
106
+ Requires-Dist: torchvision; extra == "dev"
107
+ Requires-Dist: transformers>=4.41.2; extra == "dev"
108
+ Requires-Dist: phonemizer; extra == "dev"
109
+ Requires-Dist: accelerate>=0.31.0; extra == "dev"
110
+ Requires-Dist: datasets; extra == "dev"
111
+ Requires-Dist: protobuf<4,>=3.20.3; extra == "dev"
112
+ Requires-Dist: tensorboard; extra == "dev"
113
+ Requires-Dist: Jinja2; extra == "dev"
114
+ Requires-Dist: peft>=0.15.0; extra == "dev"
115
+ Requires-Dist: hf-doc-builder>=0.3.0; extra == "dev"
116
+ Requires-Dist: torch>=1.4; extra == "dev"
117
+ Requires-Dist: accelerate>=0.31.0; extra == "dev"
118
+ Requires-Dist: jax>=0.4.1; extra == "dev"
119
+ Requires-Dist: jaxlib>=0.4.1; extra == "dev"
120
+ Requires-Dist: flax>=0.4.1; extra == "dev"
121
+ Dynamic: author
122
+ Dynamic: author-email
123
+ Dynamic: classifier
124
+ Dynamic: description
125
+ Dynamic: description-content-type
126
+ Dynamic: home-page
127
+ Dynamic: keywords
128
+ Dynamic: license
129
+ Dynamic: provides-extra
130
+ Dynamic: requires-dist
131
+ Dynamic: requires-python
132
+ Dynamic: summary
133
+
134
+ <!---
135
+ Copyright 2022 - The HuggingFace Team. All rights reserved.
136
+
137
+ Licensed under the Apache License, Version 2.0 (the "License");
138
+ you may not use this file except in compliance with the License.
139
+ You may obtain a copy of the License at
140
+
141
+ http://www.apache.org/licenses/LICENSE-2.0
142
+
143
+ Unless required by applicable law or agreed to in writing, software
144
+ distributed under the License is distributed on an "AS IS" BASIS,
145
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
146
+ See the License for the specific language governing permissions and
147
+ limitations under the License.
148
+ -->
149
+
150
+ <p align="center">
151
+ <br>
152
+ <img src="https://raw.githubusercontent.com/huggingface/diffusers/main/docs/source/en/imgs/diffusers_library.jpg" width="400"/>
153
+ <br>
154
+ <p>
155
+ <p align="center">
156
+ <a href="https://github.com/huggingface/diffusers/blob/main/LICENSE"><img alt="GitHub" src="https://img.shields.io/github/license/huggingface/datasets.svg?color=blue"></a>
157
+ <a href="https://github.com/huggingface/diffusers/releases"><img alt="GitHub release" src="https://img.shields.io/github/release/huggingface/diffusers.svg"></a>
158
+ <a href="https://pepy.tech/project/diffusers"><img alt="GitHub release" src="https://static.pepy.tech/badge/diffusers/month"></a>
159
+ <a href="CODE_OF_CONDUCT.md"><img alt="Contributor Covenant" src="https://img.shields.io/badge/Contributor%20Covenant-2.1-4baaaa.svg"></a>
160
+ <a href="https://twitter.com/diffuserslib"><img alt="X account" src="https://img.shields.io/twitter/url/https/twitter.com/diffuserslib.svg?style=social&label=Follow%20%40diffuserslib"></a>
161
+ </p>
162
+
163
+ 🤗 Diffusers is the go-to library for state-of-the-art pretrained diffusion models for generating images, audio, and even 3D structures of molecules. Whether you're looking for a simple inference solution or training your own diffusion models, 🤗 Diffusers is a modular toolbox that supports both. Our library is designed with a focus on [usability over performance](https://huggingface.co/docs/diffusers/conceptual/philosophy#usability-over-performance), [simple over easy](https://huggingface.co/docs/diffusers/conceptual/philosophy#simple-over-easy), and [customizability over abstractions](https://huggingface.co/docs/diffusers/conceptual/philosophy#tweakable-contributorfriendly-over-abstraction).
164
+
165
+ 🤗 Diffusers offers three core components:
166
+
167
+ - State-of-the-art [diffusion pipelines](https://huggingface.co/docs/diffusers/api/pipelines/overview) that can be run in inference with just a few lines of code.
168
+ - Interchangeable noise [schedulers](https://huggingface.co/docs/diffusers/api/schedulers/overview) for different diffusion speeds and output quality.
169
+ - Pretrained [models](https://huggingface.co/docs/diffusers/api/models/overview) that can be used as building blocks, and combined with schedulers, for creating your own end-to-end diffusion systems.
170
+
171
+ ## Installation
172
+
173
+ We recommend installing 🤗 Diffusers in a virtual environment from PyPI or Conda. For more details about installing [PyTorch](https://pytorch.org/get-started/locally/) and [Flax](https://flax.readthedocs.io/en/latest/#installation), please refer to their official documentation.
174
+
175
+ ### PyTorch
176
+
177
+ With `pip` (official package):
178
+
179
+ ```bash
180
+ pip install --upgrade diffusers[torch]
181
+ ```
182
+
183
+ With `conda` (maintained by the community):
184
+
185
+ ```sh
186
+ conda install -c conda-forge diffusers
187
+ ```
188
+
189
+ ### Flax
190
+
191
+ With `pip` (official package):
192
+
193
+ ```bash
194
+ pip install --upgrade diffusers[flax]
195
+ ```
196
+
197
+ ### Apple Silicon (M1/M2) support
198
+
199
+ Please refer to the [How to use Stable Diffusion in Apple Silicon](https://huggingface.co/docs/diffusers/optimization/mps) guide.
200
+
201
+ ## Quickstart
202
+
203
+ Generating outputs is super easy with 🤗 Diffusers. To generate an image from text, use the `from_pretrained` method to load any pretrained diffusion model (browse the [Hub](https://huggingface.co/models?library=diffusers&sort=downloads) for 30,000+ checkpoints):
204
+
205
+ ```python
206
+ from diffusers import DiffusionPipeline
207
+ import torch
208
+
209
+ pipeline = DiffusionPipeline.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16)
210
+ pipeline.to("cuda")
211
+ pipeline("An image of a squirrel in Picasso style").images[0]
212
+ ```
213
+
214
+ You can also dig into the models and schedulers toolbox to build your own diffusion system:
215
+
216
+ ```python
217
+ from diffusers import DDPMScheduler, UNet2DModel
218
+ from PIL import Image
219
+ import torch
220
+
221
+ scheduler = DDPMScheduler.from_pretrained("google/ddpm-cat-256")
222
+ model = UNet2DModel.from_pretrained("google/ddpm-cat-256").to("cuda")
223
+ scheduler.set_timesteps(50)
224
+
225
+ sample_size = model.config.sample_size
226
+ noise = torch.randn((1, 3, sample_size, sample_size), device="cuda")
227
+ input = noise
228
+
229
+ for t in scheduler.timesteps:
230
+ with torch.no_grad():
231
+ noisy_residual = model(input, t).sample
232
+ prev_noisy_sample = scheduler.step(noisy_residual, t, input).prev_sample
233
+ input = prev_noisy_sample
234
+
235
+ image = (input / 2 + 0.5).clamp(0, 1)
236
+ image = image.cpu().permute(0, 2, 3, 1).numpy()[0]
237
+ image = Image.fromarray((image * 255).round().astype("uint8"))
238
+ image
239
+ ```
240
+
241
+ Check out the [Quickstart](https://huggingface.co/docs/diffusers/quicktour) to launch your diffusion journey today!
242
+
243
+ ## How to navigate the documentation
244
+
245
+ | **Documentation** | **What can I learn?** |
246
+ |---------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
247
+ | [Tutorial](https://huggingface.co/docs/diffusers/tutorials/tutorial_overview) | A basic crash course for learning how to use the library's most important features like using models and schedulers to build your own diffusion system, and training your own diffusion model. |
248
+ | [Loading](https://huggingface.co/docs/diffusers/using-diffusers/loading) | Guides for how to load and configure all the components (pipelines, models, and schedulers) of the library, as well as how to use different schedulers. |
249
+ | [Pipelines for inference](https://huggingface.co/docs/diffusers/using-diffusers/overview_techniques) | Guides for how to use pipelines for different inference tasks, batched generation, controlling generated outputs and randomness, and how to contribute a pipeline to the library. |
250
+ | [Optimization](https://huggingface.co/docs/diffusers/optimization/fp16) | Guides for how to optimize your diffusion model to run faster and consume less memory. |
251
+ | [Training](https://huggingface.co/docs/diffusers/training/overview) | Guides for how to train a diffusion model for different tasks with different training techniques. |
252
+ ## Contribution
253
+
254
+ We ❤️ contributions from the open-source community!
255
+ If you want to contribute to this library, please check out our [Contribution guide](https://github.com/huggingface/diffusers/blob/main/CONTRIBUTING.md).
256
+ You can look out for [issues](https://github.com/huggingface/diffusers/issues) you'd like to tackle to contribute to the library.
257
+ - See [Good first issues](https://github.com/huggingface/diffusers/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22) for general opportunities to contribute
258
+ - See [New model/pipeline](https://github.com/huggingface/diffusers/issues?q=is%3Aopen+is%3Aissue+label%3A%22New+pipeline%2Fmodel%22) to contribute exciting new diffusion models / diffusion pipelines
259
+ - See [New scheduler](https://github.com/huggingface/diffusers/issues?q=is%3Aopen+is%3Aissue+label%3A%22New+scheduler%22)
260
+
261
+ Also, say 👋 in our public Discord channel <a href="https://discord.gg/G7tWnz98XR"><img alt="Join us on Discord" src="https://img.shields.io/discord/823813159592001537?color=5865F2&logo=discord&logoColor=white"></a>. We discuss the hottest trends about diffusion models, help each other with contributions, personal projects or just hang out ☕.
262
+
263
+
264
+ ## Popular Tasks & Pipelines
265
+
266
+ <table>
267
+ <tr>
268
+ <th>Task</th>
269
+ <th>Pipeline</th>
270
+ <th>🤗 Hub</th>
271
+ </tr>
272
+ <tr style="border-top: 2px solid black">
273
+ <td>Unconditional Image Generation</td>
274
+ <td><a href="https://huggingface.co/docs/diffusers/api/pipelines/ddpm"> DDPM </a></td>
275
+ <td><a href="https://huggingface.co/google/ddpm-ema-church-256"> google/ddpm-ema-church-256 </a></td>
276
+ </tr>
277
+ <tr style="border-top: 2px solid black">
278
+ <td>Text-to-Image</td>
279
+ <td><a href="https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/text2img">Stable Diffusion Text-to-Image</a></td>
280
+ <td><a href="https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5"> stable-diffusion-v1-5/stable-diffusion-v1-5 </a></td>
281
+ </tr>
282
+ <tr>
283
+ <td>Text-to-Image</td>
284
+ <td><a href="https://huggingface.co/docs/diffusers/api/pipelines/unclip">unCLIP</a></td>
285
+ <td><a href="https://huggingface.co/kakaobrain/karlo-v1-alpha"> kakaobrain/karlo-v1-alpha </a></td>
286
+ </tr>
287
+ <tr>
288
+ <td>Text-to-Image</td>
289
+ <td><a href="https://huggingface.co/docs/diffusers/api/pipelines/deepfloyd_if">DeepFloyd IF</a></td>
290
+ <td><a href="https://huggingface.co/DeepFloyd/IF-I-XL-v1.0"> DeepFloyd/IF-I-XL-v1.0 </a></td>
291
+ </tr>
292
+ <tr>
293
+ <td>Text-to-Image</td>
294
+ <td><a href="https://huggingface.co/docs/diffusers/api/pipelines/kandinsky">Kandinsky</a></td>
295
+ <td><a href="https://huggingface.co/kandinsky-community/kandinsky-2-2-decoder"> kandinsky-community/kandinsky-2-2-decoder </a></td>
296
+ </tr>
297
+ <tr style="border-top: 2px solid black">
298
+ <td>Text-guided Image-to-Image</td>
299
+ <td><a href="https://huggingface.co/docs/diffusers/api/pipelines/controlnet">ControlNet</a></td>
300
+ <td><a href="https://huggingface.co/lllyasviel/sd-controlnet-canny"> lllyasviel/sd-controlnet-canny </a></td>
301
+ </tr>
302
+ <tr>
303
+ <td>Text-guided Image-to-Image</td>
304
+ <td><a href="https://huggingface.co/docs/diffusers/api/pipelines/pix2pix">InstructPix2Pix</a></td>
305
+ <td><a href="https://huggingface.co/timbrooks/instruct-pix2pix"> timbrooks/instruct-pix2pix </a></td>
306
+ </tr>
307
+ <tr>
308
+ <td>Text-guided Image-to-Image</td>
309
+ <td><a href="https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/img2img">Stable Diffusion Image-to-Image</a></td>
310
+ <td><a href="https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5"> stable-diffusion-v1-5/stable-diffusion-v1-5 </a></td>
311
+ </tr>
312
+ <tr style="border-top: 2px solid black">
313
+ <td>Text-guided Image Inpainting</td>
314
+ <td><a href="https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/inpaint">Stable Diffusion Inpainting</a></td>
315
+ <td><a href="https://huggingface.co/runwayml/stable-diffusion-inpainting"> runwayml/stable-diffusion-inpainting </a></td>
316
+ </tr>
317
+ <tr style="border-top: 2px solid black">
318
+ <td>Image Variation</td>
319
+ <td><a href="https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/image_variation">Stable Diffusion Image Variation</a></td>
320
+ <td><a href="https://huggingface.co/lambdalabs/sd-image-variations-diffusers"> lambdalabs/sd-image-variations-diffusers </a></td>
321
+ </tr>
322
+ <tr style="border-top: 2px solid black">
323
+ <td>Super Resolution</td>
324
+ <td><a href="https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/upscale">Stable Diffusion Upscale</a></td>
325
+ <td><a href="https://huggingface.co/stabilityai/stable-diffusion-x4-upscaler"> stabilityai/stable-diffusion-x4-upscaler </a></td>
326
+ </tr>
327
+ <tr>
328
+ <td>Super Resolution</td>
329
+ <td><a href="https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/latent_upscale">Stable Diffusion Latent Upscale</a></td>
330
+ <td><a href="https://huggingface.co/stabilityai/sd-x2-latent-upscaler"> stabilityai/sd-x2-latent-upscaler </a></td>
331
+ </tr>
332
+ </table>
333
+
334
+ ## Popular libraries using 🧨 Diffusers
335
+
336
+ - https://github.com/microsoft/TaskMatrix
337
+ - https://github.com/invoke-ai/InvokeAI
338
+ - https://github.com/InstantID/InstantID
339
+ - https://github.com/apple/ml-stable-diffusion
340
+ - https://github.com/Sanster/lama-cleaner
341
+ - https://github.com/IDEA-Research/Grounded-Segment-Anything
342
+ - https://github.com/ashawkey/stable-dreamfusion
343
+ - https://github.com/deep-floyd/IF
344
+ - https://github.com/bentoml/BentoML
345
+ - https://github.com/bmaltais/kohya_ss
346
+ - +14,000 other amazing GitHub repositories 💪
347
+
348
+ Thank you for using us ❤️.
349
+
350
+ ## Credits
351
+
352
+ This library concretizes previous work by many different authors and would not have been possible without their great research and implementations. We'd like to thank, in particular, the following implementations which have helped us in our development and without which the API could not have been as polished today:
353
+
354
+ - @CompVis' latent diffusion models library, available [here](https://github.com/CompVis/latent-diffusion)
355
+ - @hojonathanho original DDPM implementation, available [here](https://github.com/hojonathanho/diffusion) as well as the extremely useful translation into PyTorch by @pesser, available [here](https://github.com/pesser/pytorch_diffusion)
356
+ - @ermongroup's DDIM implementation, available [here](https://github.com/ermongroup/ddim)
357
+ - @yang-song's Score-VE and Score-VP implementations, available [here](https://github.com/yang-song/score_sde_pytorch)
358
+
359
+ We also want to thank @heejkoo for the very helpful overview of papers, code and resources on diffusion models, available [here](https://github.com/heejkoo/Awesome-Diffusion-Models) as well as @crowsonkb and @rromb for useful discussions and insights.
360
+
361
+ ## Citation
362
+
363
+ ```bibtex
364
+ @misc{von-platen-etal-2022-diffusers,
365
+ author = {Patrick von Platen and Suraj Patil and Anton Lozhkov and Pedro Cuenca and Nathan Lambert and Kashif Rasul and Mishig Davaadorj and Dhruv Nair and Sayak Paul and William Berman and Yiyi Xu and Steven Liu and Thomas Wolf},
366
+ title = {Diffusers: State-of-the-art diffusion models},
367
+ year = {2022},
368
+ publisher = {GitHub},
369
+ journal = {GitHub repository},
370
+ howpublished = {\url{https://github.com/huggingface/diffusers}}
371
+ }
372
+ ```
python_embeded/Lib/site-packages/diffusers-0.34.0.dist-info/RECORD ADDED
The diff for this file is too large to render. See raw diff
 
python_embeded/Lib/site-packages/diffusers-0.34.0.dist-info/REQUESTED ADDED
File without changes