emeeran commited on
Commit
52df484
1 Parent(s): c4465af

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .env +1 -0
  2. .gitattributes +16 -0
  3. .venv/Lib/site-packages/MarkupSafe-2.1.5.dist-info/INSTALLER +1 -0
  4. .venv/Lib/site-packages/MarkupSafe-2.1.5.dist-info/LICENSE.rst +28 -0
  5. .venv/Lib/site-packages/MarkupSafe-2.1.5.dist-info/METADATA +93 -0
  6. .venv/Lib/site-packages/MarkupSafe-2.1.5.dist-info/RECORD +14 -0
  7. .venv/Lib/site-packages/MarkupSafe-2.1.5.dist-info/WHEEL +5 -0
  8. .venv/Lib/site-packages/MarkupSafe-2.1.5.dist-info/top_level.txt +1 -0
  9. .venv/Lib/site-packages/PIL/BdfFontFile.py +133 -0
  10. .venv/Lib/site-packages/PIL/BlpImagePlugin.py +476 -0
  11. .venv/Lib/site-packages/PIL/BmpImagePlugin.py +472 -0
  12. .venv/Lib/site-packages/PIL/BufrStubImagePlugin.py +74 -0
  13. .venv/Lib/site-packages/PIL/ContainerIO.py +121 -0
  14. .venv/Lib/site-packages/PIL/CurImagePlugin.py +75 -0
  15. .venv/Lib/site-packages/PIL/DcxImagePlugin.py +80 -0
  16. .venv/Lib/site-packages/PIL/DdsImagePlugin.py +572 -0
  17. .venv/Lib/site-packages/PIL/EpsImagePlugin.py +474 -0
  18. .venv/Lib/site-packages/PIL/ExifTags.py +381 -0
  19. .venv/Lib/site-packages/PIL/FitsImagePlugin.py +148 -0
  20. .venv/Lib/site-packages/PIL/FliImagePlugin.py +174 -0
  21. .venv/Lib/site-packages/PIL/FontFile.py +134 -0
  22. .venv/Lib/site-packages/PIL/FpxImagePlugin.py +255 -0
  23. .venv/Lib/site-packages/PIL/FtexImagePlugin.py +115 -0
  24. .venv/Lib/site-packages/PIL/GbrImagePlugin.py +103 -0
  25. .venv/Lib/site-packages/PIL/GdImageFile.py +102 -0
  26. .venv/Lib/site-packages/PIL/GifImagePlugin.py +1107 -0
  27. .venv/Lib/site-packages/PIL/GimpGradientFile.py +137 -0
  28. .venv/Lib/site-packages/PIL/GimpPaletteFile.py +57 -0
  29. .venv/Lib/site-packages/PIL/GribStubImagePlugin.py +74 -0
  30. .venv/Lib/site-packages/PIL/Hdf5StubImagePlugin.py +74 -0
  31. .venv/Lib/site-packages/PIL/IcnsImagePlugin.py +400 -0
  32. .venv/Lib/site-packages/PIL/IcoImagePlugin.py +358 -0
  33. .venv/Lib/site-packages/PIL/ImImagePlugin.py +371 -0
  34. .venv/Lib/site-packages/PIL/Image.py +0 -0
  35. .venv/Lib/site-packages/PIL/ImageChops.py +311 -0
  36. .venv/Lib/site-packages/PIL/ImageCms.py +1102 -0
  37. .venv/Lib/site-packages/PIL/ImageColor.py +317 -0
  38. .venv/Lib/site-packages/PIL/ImageDraw.py +1087 -0
  39. .venv/Lib/site-packages/PIL/ImageDraw2.py +193 -0
  40. .venv/Lib/site-packages/PIL/ImageEnhance.py +104 -0
  41. .venv/Lib/site-packages/PIL/ImageFile.py +797 -0
  42. .venv/Lib/site-packages/PIL/ImageFilter.py +565 -0
  43. .venv/Lib/site-packages/PIL/ImageFont.py +1252 -0
  44. .venv/Lib/site-packages/PIL/ImageGrab.py +186 -0
  45. .venv/Lib/site-packages/PIL/ImageMath.py +357 -0
  46. .venv/Lib/site-packages/PIL/ImageMode.py +96 -0
  47. .venv/Lib/site-packages/PIL/ImageMorph.py +265 -0
  48. .venv/Lib/site-packages/PIL/ImageOps.py +724 -0
  49. .venv/Lib/site-packages/PIL/ImagePalette.py +263 -0
  50. .venv/Lib/site-packages/PIL/ImagePath.py +20 -0
.env ADDED
@@ -0,0 +1 @@
 
 
1
+ OPENAI_API_KEY="sk-proj-Obr7r1OzJlBpOBqDDip8T3BlbkFJXz3qJW1vYUu8lszF8X4r"
.gitattributes CHANGED
@@ -33,3 +33,19 @@ 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
+ .venv/Lib/site-packages/altair/vegalite/v5/schema/__pycache__/channels.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
37
+ .venv/Lib/site-packages/altair/vegalite/v5/schema/__pycache__/core.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
38
+ .venv/Lib/site-packages/gradio/frpc_windows_amd64_v0.2 filter=lfs diff=lfs merge=lfs -text
39
+ .venv/Lib/site-packages/gradio/templates/frontend/assets/Index-BQLeAZ7H.js.map filter=lfs diff=lfs merge=lfs -text
40
+ .venv/Lib/site-packages/numpy/core/_multiarray_umath.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
41
+ .venv/Lib/site-packages/numpy/core/_simd.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
42
+ .venv/Lib/site-packages/numpy.libs/libopenblas64__v0.3.23-293-gc2f4bdbb-gcc_10_3_0-2bde3a66a51006b2b53eb373ff767a3f.dll filter=lfs diff=lfs merge=lfs -text
43
+ .venv/Lib/site-packages/pandas/_libs/algos.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
44
+ .venv/Lib/site-packages/pandas/_libs/groupby.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
45
+ .venv/Lib/site-packages/pandas/_libs/hashtable.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
46
+ .venv/Lib/site-packages/pandas/_libs/interval.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
47
+ .venv/Lib/site-packages/pandas/_libs/join.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
48
+ .venv/Lib/site-packages/PIL/_imaging.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
49
+ .venv/Lib/site-packages/PIL/_imagingft.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
50
+ .venv/Lib/site-packages/pydantic_core/_pydantic_core.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
51
+ .venv/Scripts/ruff.exe filter=lfs diff=lfs merge=lfs -text
.venv/Lib/site-packages/MarkupSafe-2.1.5.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
.venv/Lib/site-packages/MarkupSafe-2.1.5.dist-info/LICENSE.rst ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright 2010 Pallets
2
+
3
+ Redistribution and use in source and binary forms, with or without
4
+ modification, are permitted provided that the following conditions are
5
+ met:
6
+
7
+ 1. Redistributions of source code must retain the above copyright
8
+ notice, this list of conditions and the following disclaimer.
9
+
10
+ 2. Redistributions in binary form must reproduce the above copyright
11
+ notice, this list of conditions and the following disclaimer in the
12
+ documentation and/or other materials provided with the distribution.
13
+
14
+ 3. Neither the name of the copyright holder nor the names of its
15
+ contributors may be used to endorse or promote products derived from
16
+ this software without specific prior written permission.
17
+
18
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
21
+ PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22
+ HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
24
+ TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
25
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
26
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
27
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
28
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
.venv/Lib/site-packages/MarkupSafe-2.1.5.dist-info/METADATA ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.1
2
+ Name: MarkupSafe
3
+ Version: 2.1.5
4
+ Summary: Safely add untrusted strings to HTML/XML markup.
5
+ Home-page: https://palletsprojects.com/p/markupsafe/
6
+ Maintainer: Pallets
7
+ Maintainer-email: contact@palletsprojects.com
8
+ License: BSD-3-Clause
9
+ Project-URL: Donate, https://palletsprojects.com/donate
10
+ Project-URL: Documentation, https://markupsafe.palletsprojects.com/
11
+ Project-URL: Changes, https://markupsafe.palletsprojects.com/changes/
12
+ Project-URL: Source Code, https://github.com/pallets/markupsafe/
13
+ Project-URL: Issue Tracker, https://github.com/pallets/markupsafe/issues/
14
+ Project-URL: Chat, https://discord.gg/pallets
15
+ Classifier: Development Status :: 5 - Production/Stable
16
+ Classifier: Environment :: Web Environment
17
+ Classifier: Intended Audience :: Developers
18
+ Classifier: License :: OSI Approved :: BSD License
19
+ Classifier: Operating System :: OS Independent
20
+ Classifier: Programming Language :: Python
21
+ Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
22
+ Classifier: Topic :: Text Processing :: Markup :: HTML
23
+ Requires-Python: >=3.7
24
+ Description-Content-Type: text/x-rst
25
+ License-File: LICENSE.rst
26
+
27
+ MarkupSafe
28
+ ==========
29
+
30
+ MarkupSafe implements a text object that escapes characters so it is
31
+ safe to use in HTML and XML. Characters that have special meanings are
32
+ replaced so that they display as the actual characters. This mitigates
33
+ injection attacks, meaning untrusted user input can safely be displayed
34
+ on a page.
35
+
36
+
37
+ Installing
38
+ ----------
39
+
40
+ Install and update using `pip`_:
41
+
42
+ .. code-block:: text
43
+
44
+ pip install -U MarkupSafe
45
+
46
+ .. _pip: https://pip.pypa.io/en/stable/getting-started/
47
+
48
+
49
+ Examples
50
+ --------
51
+
52
+ .. code-block:: pycon
53
+
54
+ >>> from markupsafe import Markup, escape
55
+
56
+ >>> # escape replaces special characters and wraps in Markup
57
+ >>> escape("<script>alert(document.cookie);</script>")
58
+ Markup('&lt;script&gt;alert(document.cookie);&lt;/script&gt;')
59
+
60
+ >>> # wrap in Markup to mark text "safe" and prevent escaping
61
+ >>> Markup("<strong>Hello</strong>")
62
+ Markup('<strong>hello</strong>')
63
+
64
+ >>> escape(Markup("<strong>Hello</strong>"))
65
+ Markup('<strong>hello</strong>')
66
+
67
+ >>> # Markup is a str subclass
68
+ >>> # methods and operators escape their arguments
69
+ >>> template = Markup("Hello <em>{name}</em>")
70
+ >>> template.format(name='"World"')
71
+ Markup('Hello <em>&#34;World&#34;</em>')
72
+
73
+
74
+ Donate
75
+ ------
76
+
77
+ The Pallets organization develops and supports MarkupSafe and other
78
+ popular packages. In order to grow the community of contributors and
79
+ users, and allow the maintainers to devote more time to the projects,
80
+ `please donate today`_.
81
+
82
+ .. _please donate today: https://palletsprojects.com/donate
83
+
84
+
85
+ Links
86
+ -----
87
+
88
+ - Documentation: https://markupsafe.palletsprojects.com/
89
+ - Changes: https://markupsafe.palletsprojects.com/changes/
90
+ - PyPI Releases: https://pypi.org/project/MarkupSafe/
91
+ - Source Code: https://github.com/pallets/markupsafe/
92
+ - Issue Tracker: https://github.com/pallets/markupsafe/issues/
93
+ - Chat: https://discord.gg/pallets
.venv/Lib/site-packages/MarkupSafe-2.1.5.dist-info/RECORD ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MarkupSafe-2.1.5.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ MarkupSafe-2.1.5.dist-info/LICENSE.rst,sha256=RjHsDbX9kKVH4zaBcmTGeYIUM4FG-KyUtKV_lu6MnsQ,1503
3
+ MarkupSafe-2.1.5.dist-info/METADATA,sha256=icNlaniV7YIQZ1BScCVqNaRtm7MAgfw8d3OBmoSVyAY,3096
4
+ MarkupSafe-2.1.5.dist-info/RECORD,,
5
+ MarkupSafe-2.1.5.dist-info/WHEEL,sha256=j9Aissza3750LQHFAQyYerNjmkEON1-8w_RaZNFtKSs,102
6
+ MarkupSafe-2.1.5.dist-info/top_level.txt,sha256=qy0Plje5IJuvsCBjejJyhDCjEAdcDLK_2agVcex8Z6U,11
7
+ markupsafe/__init__.py,sha256=m1ysNeqf55zbEoJtaovca40ivrkEFolPlw5bGoC5Gi4,11290
8
+ markupsafe/__pycache__/__init__.cpython-312.pyc,,
9
+ markupsafe/__pycache__/_native.cpython-312.pyc,,
10
+ markupsafe/_native.py,sha256=_Q7UsXCOvgdonCgqG3l5asANI6eo50EKnDM-mlwEC5M,1776
11
+ markupsafe/_speedups.c,sha256=n3jzzaJwXcoN8nTFyA53f3vSqsWK2vujI-v6QYifjhQ,7403
12
+ markupsafe/_speedups.cp312-win_amd64.pyd,sha256=CLz8k0mpvM-dgLP0eSHpGYHm8shlGxXoCinA12zgHsY,15872
13
+ markupsafe/_speedups.pyi,sha256=f5QtwIOP0eLrxh2v5p6SmaYmlcHIGIfmz0DovaqL0OU,238
14
+ markupsafe/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
.venv/Lib/site-packages/MarkupSafe-2.1.5.dist-info/WHEEL ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.42.0)
3
+ Root-Is-Purelib: false
4
+ Tag: cp312-cp312-win_amd64
5
+
.venv/Lib/site-packages/MarkupSafe-2.1.5.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ markupsafe
.venv/Lib/site-packages/PIL/BdfFontFile.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library
3
+ # $Id$
4
+ #
5
+ # bitmap distribution font (bdf) file parser
6
+ #
7
+ # history:
8
+ # 1996-05-16 fl created (as bdf2pil)
9
+ # 1997-08-25 fl converted to FontFile driver
10
+ # 2001-05-25 fl removed bogus __init__ call
11
+ # 2002-11-20 fl robustification (from Kevin Cazabon, Dmitry Vasiliev)
12
+ # 2003-04-22 fl more robustification (from Graham Dumpleton)
13
+ #
14
+ # Copyright (c) 1997-2003 by Secret Labs AB.
15
+ # Copyright (c) 1997-2003 by Fredrik Lundh.
16
+ #
17
+ # See the README file for information on usage and redistribution.
18
+ #
19
+
20
+ """
21
+ Parse X Bitmap Distribution Format (BDF)
22
+ """
23
+ from __future__ import annotations
24
+
25
+ from typing import BinaryIO
26
+
27
+ from . import FontFile, Image
28
+
29
+ bdf_slant = {
30
+ "R": "Roman",
31
+ "I": "Italic",
32
+ "O": "Oblique",
33
+ "RI": "Reverse Italic",
34
+ "RO": "Reverse Oblique",
35
+ "OT": "Other",
36
+ }
37
+
38
+ bdf_spacing = {"P": "Proportional", "M": "Monospaced", "C": "Cell"}
39
+
40
+
41
+ def bdf_char(
42
+ f: BinaryIO,
43
+ ) -> (
44
+ tuple[
45
+ str,
46
+ int,
47
+ tuple[tuple[int, int], tuple[int, int, int, int], tuple[int, int, int, int]],
48
+ Image.Image,
49
+ ]
50
+ | None
51
+ ):
52
+ # skip to STARTCHAR
53
+ while True:
54
+ s = f.readline()
55
+ if not s:
56
+ return None
57
+ if s[:9] == b"STARTCHAR":
58
+ break
59
+ id = s[9:].strip().decode("ascii")
60
+
61
+ # load symbol properties
62
+ props = {}
63
+ while True:
64
+ s = f.readline()
65
+ if not s or s[:6] == b"BITMAP":
66
+ break
67
+ i = s.find(b" ")
68
+ props[s[:i].decode("ascii")] = s[i + 1 : -1].decode("ascii")
69
+
70
+ # load bitmap
71
+ bitmap = bytearray()
72
+ while True:
73
+ s = f.readline()
74
+ if not s or s[:7] == b"ENDCHAR":
75
+ break
76
+ bitmap += s[:-1]
77
+
78
+ # The word BBX
79
+ # followed by the width in x (BBw), height in y (BBh),
80
+ # and x and y displacement (BBxoff0, BByoff0)
81
+ # of the lower left corner from the origin of the character.
82
+ width, height, x_disp, y_disp = (int(p) for p in props["BBX"].split())
83
+
84
+ # The word DWIDTH
85
+ # followed by the width in x and y of the character in device pixels.
86
+ dwx, dwy = (int(p) for p in props["DWIDTH"].split())
87
+
88
+ bbox = (
89
+ (dwx, dwy),
90
+ (x_disp, -y_disp - height, width + x_disp, -y_disp),
91
+ (0, 0, width, height),
92
+ )
93
+
94
+ try:
95
+ im = Image.frombytes("1", (width, height), bitmap, "hex", "1")
96
+ except ValueError:
97
+ # deal with zero-width characters
98
+ im = Image.new("1", (width, height))
99
+
100
+ return id, int(props["ENCODING"]), bbox, im
101
+
102
+
103
+ class BdfFontFile(FontFile.FontFile):
104
+ """Font file plugin for the X11 BDF format."""
105
+
106
+ def __init__(self, fp: BinaryIO):
107
+ super().__init__()
108
+
109
+ s = fp.readline()
110
+ if s[:13] != b"STARTFONT 2.1":
111
+ msg = "not a valid BDF file"
112
+ raise SyntaxError(msg)
113
+
114
+ props = {}
115
+ comments = []
116
+
117
+ while True:
118
+ s = fp.readline()
119
+ if not s or s[:13] == b"ENDPROPERTIES":
120
+ break
121
+ i = s.find(b" ")
122
+ props[s[:i].decode("ascii")] = s[i + 1 : -1].decode("ascii")
123
+ if s[:i] in [b"COMMENT", b"COPYRIGHT"]:
124
+ if s.find(b"LogicalFontDescription") < 0:
125
+ comments.append(s[i + 1 : -1].decode("ascii"))
126
+
127
+ while True:
128
+ c = bdf_char(fp)
129
+ if not c:
130
+ break
131
+ id, ch, (xy, dst, src), im = c
132
+ if 0 <= ch < len(self.glyph):
133
+ self.glyph[ch] = xy, dst, src, im
.venv/Lib/site-packages/PIL/BlpImagePlugin.py ADDED
@@ -0,0 +1,476 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Blizzard Mipmap Format (.blp)
3
+ Jerome Leclanche <jerome@leclan.ch>
4
+
5
+ The contents of this file are hereby released in the public domain (CC0)
6
+ Full text of the CC0 license:
7
+ https://creativecommons.org/publicdomain/zero/1.0/
8
+
9
+ BLP1 files, used mostly in Warcraft III, are not fully supported.
10
+ All types of BLP2 files used in World of Warcraft are supported.
11
+
12
+ The BLP file structure consists of a header, up to 16 mipmaps of the
13
+ texture
14
+
15
+ Texture sizes must be powers of two, though the two dimensions do
16
+ not have to be equal; 512x256 is valid, but 512x200 is not.
17
+ The first mipmap (mipmap #0) is the full size image; each subsequent
18
+ mipmap halves both dimensions. The final mipmap should be 1x1.
19
+
20
+ BLP files come in many different flavours:
21
+ * JPEG-compressed (type == 0) - only supported for BLP1.
22
+ * RAW images (type == 1, encoding == 1). Each mipmap is stored as an
23
+ array of 8-bit values, one per pixel, left to right, top to bottom.
24
+ Each value is an index to the palette.
25
+ * DXT-compressed (type == 1, encoding == 2):
26
+ - DXT1 compression is used if alpha_encoding == 0.
27
+ - An additional alpha bit is used if alpha_depth == 1.
28
+ - DXT3 compression is used if alpha_encoding == 1.
29
+ - DXT5 compression is used if alpha_encoding == 7.
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ import os
35
+ import struct
36
+ from enum import IntEnum
37
+ from io import BytesIO
38
+
39
+ from . import Image, ImageFile
40
+
41
+
42
+ class Format(IntEnum):
43
+ JPEG = 0
44
+
45
+
46
+ class Encoding(IntEnum):
47
+ UNCOMPRESSED = 1
48
+ DXT = 2
49
+ UNCOMPRESSED_RAW_BGRA = 3
50
+
51
+
52
+ class AlphaEncoding(IntEnum):
53
+ DXT1 = 0
54
+ DXT3 = 1
55
+ DXT5 = 7
56
+
57
+
58
+ def unpack_565(i):
59
+ return ((i >> 11) & 0x1F) << 3, ((i >> 5) & 0x3F) << 2, (i & 0x1F) << 3
60
+
61
+
62
+ def decode_dxt1(data, alpha=False):
63
+ """
64
+ input: one "row" of data (i.e. will produce 4*width pixels)
65
+ """
66
+
67
+ blocks = len(data) // 8 # number of blocks in row
68
+ ret = (bytearray(), bytearray(), bytearray(), bytearray())
69
+
70
+ for block in range(blocks):
71
+ # Decode next 8-byte block.
72
+ idx = block * 8
73
+ color0, color1, bits = struct.unpack_from("<HHI", data, idx)
74
+
75
+ r0, g0, b0 = unpack_565(color0)
76
+ r1, g1, b1 = unpack_565(color1)
77
+
78
+ # Decode this block into 4x4 pixels
79
+ # Accumulate the results onto our 4 row accumulators
80
+ for j in range(4):
81
+ for i in range(4):
82
+ # get next control op and generate a pixel
83
+
84
+ control = bits & 3
85
+ bits = bits >> 2
86
+
87
+ a = 0xFF
88
+ if control == 0:
89
+ r, g, b = r0, g0, b0
90
+ elif control == 1:
91
+ r, g, b = r1, g1, b1
92
+ elif control == 2:
93
+ if color0 > color1:
94
+ r = (2 * r0 + r1) // 3
95
+ g = (2 * g0 + g1) // 3
96
+ b = (2 * b0 + b1) // 3
97
+ else:
98
+ r = (r0 + r1) // 2
99
+ g = (g0 + g1) // 2
100
+ b = (b0 + b1) // 2
101
+ elif control == 3:
102
+ if color0 > color1:
103
+ r = (2 * r1 + r0) // 3
104
+ g = (2 * g1 + g0) // 3
105
+ b = (2 * b1 + b0) // 3
106
+ else:
107
+ r, g, b, a = 0, 0, 0, 0
108
+
109
+ if alpha:
110
+ ret[j].extend([r, g, b, a])
111
+ else:
112
+ ret[j].extend([r, g, b])
113
+
114
+ return ret
115
+
116
+
117
+ def decode_dxt3(data):
118
+ """
119
+ input: one "row" of data (i.e. will produce 4*width pixels)
120
+ """
121
+
122
+ blocks = len(data) // 16 # number of blocks in row
123
+ ret = (bytearray(), bytearray(), bytearray(), bytearray())
124
+
125
+ for block in range(blocks):
126
+ idx = block * 16
127
+ block = data[idx : idx + 16]
128
+ # Decode next 16-byte block.
129
+ bits = struct.unpack_from("<8B", block)
130
+ color0, color1 = struct.unpack_from("<HH", block, 8)
131
+
132
+ (code,) = struct.unpack_from("<I", block, 12)
133
+
134
+ r0, g0, b0 = unpack_565(color0)
135
+ r1, g1, b1 = unpack_565(color1)
136
+
137
+ for j in range(4):
138
+ high = False # Do we want the higher bits?
139
+ for i in range(4):
140
+ alphacode_index = (4 * j + i) // 2
141
+ a = bits[alphacode_index]
142
+ if high:
143
+ high = False
144
+ a >>= 4
145
+ else:
146
+ high = True
147
+ a &= 0xF
148
+ a *= 17 # We get a value between 0 and 15
149
+
150
+ color_code = (code >> 2 * (4 * j + i)) & 0x03
151
+
152
+ if color_code == 0:
153
+ r, g, b = r0, g0, b0
154
+ elif color_code == 1:
155
+ r, g, b = r1, g1, b1
156
+ elif color_code == 2:
157
+ r = (2 * r0 + r1) // 3
158
+ g = (2 * g0 + g1) // 3
159
+ b = (2 * b0 + b1) // 3
160
+ elif color_code == 3:
161
+ r = (2 * r1 + r0) // 3
162
+ g = (2 * g1 + g0) // 3
163
+ b = (2 * b1 + b0) // 3
164
+
165
+ ret[j].extend([r, g, b, a])
166
+
167
+ return ret
168
+
169
+
170
+ def decode_dxt5(data):
171
+ """
172
+ input: one "row" of data (i.e. will produce 4 * width pixels)
173
+ """
174
+
175
+ blocks = len(data) // 16 # number of blocks in row
176
+ ret = (bytearray(), bytearray(), bytearray(), bytearray())
177
+
178
+ for block in range(blocks):
179
+ idx = block * 16
180
+ block = data[idx : idx + 16]
181
+ # Decode next 16-byte block.
182
+ a0, a1 = struct.unpack_from("<BB", block)
183
+
184
+ bits = struct.unpack_from("<6B", block, 2)
185
+ alphacode1 = bits[2] | (bits[3] << 8) | (bits[4] << 16) | (bits[5] << 24)
186
+ alphacode2 = bits[0] | (bits[1] << 8)
187
+
188
+ color0, color1 = struct.unpack_from("<HH", block, 8)
189
+
190
+ (code,) = struct.unpack_from("<I", block, 12)
191
+
192
+ r0, g0, b0 = unpack_565(color0)
193
+ r1, g1, b1 = unpack_565(color1)
194
+
195
+ for j in range(4):
196
+ for i in range(4):
197
+ # get next control op and generate a pixel
198
+ alphacode_index = 3 * (4 * j + i)
199
+
200
+ if alphacode_index <= 12:
201
+ alphacode = (alphacode2 >> alphacode_index) & 0x07
202
+ elif alphacode_index == 15:
203
+ alphacode = (alphacode2 >> 15) | ((alphacode1 << 1) & 0x06)
204
+ else: # alphacode_index >= 18 and alphacode_index <= 45
205
+ alphacode = (alphacode1 >> (alphacode_index - 16)) & 0x07
206
+
207
+ if alphacode == 0:
208
+ a = a0
209
+ elif alphacode == 1:
210
+ a = a1
211
+ elif a0 > a1:
212
+ a = ((8 - alphacode) * a0 + (alphacode - 1) * a1) // 7
213
+ elif alphacode == 6:
214
+ a = 0
215
+ elif alphacode == 7:
216
+ a = 255
217
+ else:
218
+ a = ((6 - alphacode) * a0 + (alphacode - 1) * a1) // 5
219
+
220
+ color_code = (code >> 2 * (4 * j + i)) & 0x03
221
+
222
+ if color_code == 0:
223
+ r, g, b = r0, g0, b0
224
+ elif color_code == 1:
225
+ r, g, b = r1, g1, b1
226
+ elif color_code == 2:
227
+ r = (2 * r0 + r1) // 3
228
+ g = (2 * g0 + g1) // 3
229
+ b = (2 * b0 + b1) // 3
230
+ elif color_code == 3:
231
+ r = (2 * r1 + r0) // 3
232
+ g = (2 * g1 + g0) // 3
233
+ b = (2 * b1 + b0) // 3
234
+
235
+ ret[j].extend([r, g, b, a])
236
+
237
+ return ret
238
+
239
+
240
+ class BLPFormatError(NotImplementedError):
241
+ pass
242
+
243
+
244
+ def _accept(prefix):
245
+ return prefix[:4] in (b"BLP1", b"BLP2")
246
+
247
+
248
+ class BlpImageFile(ImageFile.ImageFile):
249
+ """
250
+ Blizzard Mipmap Format
251
+ """
252
+
253
+ format = "BLP"
254
+ format_description = "Blizzard Mipmap Format"
255
+
256
+ def _open(self):
257
+ self.magic = self.fp.read(4)
258
+
259
+ self.fp.seek(5, os.SEEK_CUR)
260
+ (self._blp_alpha_depth,) = struct.unpack("<b", self.fp.read(1))
261
+
262
+ self.fp.seek(2, os.SEEK_CUR)
263
+ self._size = struct.unpack("<II", self.fp.read(8))
264
+
265
+ if self.magic in (b"BLP1", b"BLP2"):
266
+ decoder = self.magic.decode()
267
+ else:
268
+ msg = f"Bad BLP magic {repr(self.magic)}"
269
+ raise BLPFormatError(msg)
270
+
271
+ self._mode = "RGBA" if self._blp_alpha_depth else "RGB"
272
+ self.tile = [(decoder, (0, 0) + self.size, 0, (self.mode, 0, 1))]
273
+
274
+
275
+ class _BLPBaseDecoder(ImageFile.PyDecoder):
276
+ _pulls_fd = True
277
+
278
+ def decode(self, buffer):
279
+ try:
280
+ self._read_blp_header()
281
+ self._load()
282
+ except struct.error as e:
283
+ msg = "Truncated BLP file"
284
+ raise OSError(msg) from e
285
+ return -1, 0
286
+
287
+ def _read_blp_header(self):
288
+ self.fd.seek(4)
289
+ (self._blp_compression,) = struct.unpack("<i", self._safe_read(4))
290
+
291
+ (self._blp_encoding,) = struct.unpack("<b", self._safe_read(1))
292
+ (self._blp_alpha_depth,) = struct.unpack("<b", self._safe_read(1))
293
+ (self._blp_alpha_encoding,) = struct.unpack("<b", self._safe_read(1))
294
+ self.fd.seek(1, os.SEEK_CUR) # mips
295
+
296
+ self.size = struct.unpack("<II", self._safe_read(8))
297
+
298
+ if isinstance(self, BLP1Decoder):
299
+ # Only present for BLP1
300
+ (self._blp_encoding,) = struct.unpack("<i", self._safe_read(4))
301
+ self.fd.seek(4, os.SEEK_CUR) # subtype
302
+
303
+ self._blp_offsets = struct.unpack("<16I", self._safe_read(16 * 4))
304
+ self._blp_lengths = struct.unpack("<16I", self._safe_read(16 * 4))
305
+
306
+ def _safe_read(self, length):
307
+ return ImageFile._safe_read(self.fd, length)
308
+
309
+ def _read_palette(self):
310
+ ret = []
311
+ for i in range(256):
312
+ try:
313
+ b, g, r, a = struct.unpack("<4B", self._safe_read(4))
314
+ except struct.error:
315
+ break
316
+ ret.append((b, g, r, a))
317
+ return ret
318
+
319
+ def _read_bgra(self, palette):
320
+ data = bytearray()
321
+ _data = BytesIO(self._safe_read(self._blp_lengths[0]))
322
+ while True:
323
+ try:
324
+ (offset,) = struct.unpack("<B", _data.read(1))
325
+ except struct.error:
326
+ break
327
+ b, g, r, a = palette[offset]
328
+ d = (r, g, b)
329
+ if self._blp_alpha_depth:
330
+ d += (a,)
331
+ data.extend(d)
332
+ return data
333
+
334
+
335
+ class BLP1Decoder(_BLPBaseDecoder):
336
+ def _load(self):
337
+ if self._blp_compression == Format.JPEG:
338
+ self._decode_jpeg_stream()
339
+
340
+ elif self._blp_compression == 1:
341
+ if self._blp_encoding in (4, 5):
342
+ palette = self._read_palette()
343
+ data = self._read_bgra(palette)
344
+ self.set_as_raw(data)
345
+ else:
346
+ msg = f"Unsupported BLP encoding {repr(self._blp_encoding)}"
347
+ raise BLPFormatError(msg)
348
+ else:
349
+ msg = f"Unsupported BLP compression {repr(self._blp_encoding)}"
350
+ raise BLPFormatError(msg)
351
+
352
+ def _decode_jpeg_stream(self):
353
+ from .JpegImagePlugin import JpegImageFile
354
+
355
+ (jpeg_header_size,) = struct.unpack("<I", self._safe_read(4))
356
+ jpeg_header = self._safe_read(jpeg_header_size)
357
+ self._safe_read(self._blp_offsets[0] - self.fd.tell()) # What IS this?
358
+ data = self._safe_read(self._blp_lengths[0])
359
+ data = jpeg_header + data
360
+ data = BytesIO(data)
361
+ image = JpegImageFile(data)
362
+ Image._decompression_bomb_check(image.size)
363
+ if image.mode == "CMYK":
364
+ decoder_name, extents, offset, args = image.tile[0]
365
+ image.tile = [(decoder_name, extents, offset, (args[0], "CMYK"))]
366
+ r, g, b = image.convert("RGB").split()
367
+ image = Image.merge("RGB", (b, g, r))
368
+ self.set_as_raw(image.tobytes())
369
+
370
+
371
+ class BLP2Decoder(_BLPBaseDecoder):
372
+ def _load(self):
373
+ palette = self._read_palette()
374
+
375
+ self.fd.seek(self._blp_offsets[0])
376
+
377
+ if self._blp_compression == 1:
378
+ # Uncompressed or DirectX compression
379
+
380
+ if self._blp_encoding == Encoding.UNCOMPRESSED:
381
+ data = self._read_bgra(palette)
382
+
383
+ elif self._blp_encoding == Encoding.DXT:
384
+ data = bytearray()
385
+ if self._blp_alpha_encoding == AlphaEncoding.DXT1:
386
+ linesize = (self.size[0] + 3) // 4 * 8
387
+ for yb in range((self.size[1] + 3) // 4):
388
+ for d in decode_dxt1(
389
+ self._safe_read(linesize), alpha=bool(self._blp_alpha_depth)
390
+ ):
391
+ data += d
392
+
393
+ elif self._blp_alpha_encoding == AlphaEncoding.DXT3:
394
+ linesize = (self.size[0] + 3) // 4 * 16
395
+ for yb in range((self.size[1] + 3) // 4):
396
+ for d in decode_dxt3(self._safe_read(linesize)):
397
+ data += d
398
+
399
+ elif self._blp_alpha_encoding == AlphaEncoding.DXT5:
400
+ linesize = (self.size[0] + 3) // 4 * 16
401
+ for yb in range((self.size[1] + 3) // 4):
402
+ for d in decode_dxt5(self._safe_read(linesize)):
403
+ data += d
404
+ else:
405
+ msg = f"Unsupported alpha encoding {repr(self._blp_alpha_encoding)}"
406
+ raise BLPFormatError(msg)
407
+ else:
408
+ msg = f"Unknown BLP encoding {repr(self._blp_encoding)}"
409
+ raise BLPFormatError(msg)
410
+
411
+ else:
412
+ msg = f"Unknown BLP compression {repr(self._blp_compression)}"
413
+ raise BLPFormatError(msg)
414
+
415
+ self.set_as_raw(data)
416
+
417
+
418
+ class BLPEncoder(ImageFile.PyEncoder):
419
+ _pushes_fd = True
420
+
421
+ def _write_palette(self):
422
+ data = b""
423
+ palette = self.im.getpalette("RGBA", "RGBA")
424
+ for i in range(len(palette) // 4):
425
+ r, g, b, a = palette[i * 4 : (i + 1) * 4]
426
+ data += struct.pack("<4B", b, g, r, a)
427
+ while len(data) < 256 * 4:
428
+ data += b"\x00" * 4
429
+ return data
430
+
431
+ def encode(self, bufsize):
432
+ palette_data = self._write_palette()
433
+
434
+ offset = 20 + 16 * 4 * 2 + len(palette_data)
435
+ data = struct.pack("<16I", offset, *((0,) * 15))
436
+
437
+ w, h = self.im.size
438
+ data += struct.pack("<16I", w * h, *((0,) * 15))
439
+
440
+ data += palette_data
441
+
442
+ for y in range(h):
443
+ for x in range(w):
444
+ data += struct.pack("<B", self.im.getpixel((x, y)))
445
+
446
+ return len(data), 0, data
447
+
448
+
449
+ def _save(im, fp, filename):
450
+ if im.mode != "P":
451
+ msg = "Unsupported BLP image mode"
452
+ raise ValueError(msg)
453
+
454
+ magic = b"BLP1" if im.encoderinfo.get("blp_version") == "BLP1" else b"BLP2"
455
+ fp.write(magic)
456
+
457
+ fp.write(struct.pack("<i", 1)) # Uncompressed or DirectX compression
458
+ fp.write(struct.pack("<b", Encoding.UNCOMPRESSED))
459
+ fp.write(struct.pack("<b", 1 if im.palette.mode == "RGBA" else 0))
460
+ fp.write(struct.pack("<b", 0)) # alpha encoding
461
+ fp.write(struct.pack("<b", 0)) # mips
462
+ fp.write(struct.pack("<II", *im.size))
463
+ if magic == b"BLP1":
464
+ fp.write(struct.pack("<i", 5))
465
+ fp.write(struct.pack("<i", 0))
466
+
467
+ ImageFile._save(im, fp, [("BLP", (0, 0) + im.size, 0, im.mode)])
468
+
469
+
470
+ Image.register_open(BlpImageFile.format, BlpImageFile, _accept)
471
+ Image.register_extension(BlpImageFile.format, ".blp")
472
+ Image.register_decoder("BLP1", BLP1Decoder)
473
+ Image.register_decoder("BLP2", BLP2Decoder)
474
+
475
+ Image.register_save(BlpImageFile.format, _save)
476
+ Image.register_encoder("BLP", BLPEncoder)
.venv/Lib/site-packages/PIL/BmpImagePlugin.py ADDED
@@ -0,0 +1,472 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # BMP file handler
6
+ #
7
+ # Windows (and OS/2) native bitmap storage format.
8
+ #
9
+ # history:
10
+ # 1995-09-01 fl Created
11
+ # 1996-04-30 fl Added save
12
+ # 1997-08-27 fl Fixed save of 1-bit images
13
+ # 1998-03-06 fl Load P images as L where possible
14
+ # 1998-07-03 fl Load P images as 1 where possible
15
+ # 1998-12-29 fl Handle small palettes
16
+ # 2002-12-30 fl Fixed load of 1-bit palette images
17
+ # 2003-04-21 fl Fixed load of 1-bit monochrome images
18
+ # 2003-04-23 fl Added limited support for BI_BITFIELDS compression
19
+ #
20
+ # Copyright (c) 1997-2003 by Secret Labs AB
21
+ # Copyright (c) 1995-2003 by Fredrik Lundh
22
+ #
23
+ # See the README file for information on usage and redistribution.
24
+ #
25
+ from __future__ import annotations
26
+
27
+ import os
28
+
29
+ from . import Image, ImageFile, ImagePalette
30
+ from ._binary import i16le as i16
31
+ from ._binary import i32le as i32
32
+ from ._binary import o8
33
+ from ._binary import o16le as o16
34
+ from ._binary import o32le as o32
35
+
36
+ #
37
+ # --------------------------------------------------------------------
38
+ # Read BMP file
39
+
40
+ BIT2MODE = {
41
+ # bits => mode, rawmode
42
+ 1: ("P", "P;1"),
43
+ 4: ("P", "P;4"),
44
+ 8: ("P", "P"),
45
+ 16: ("RGB", "BGR;15"),
46
+ 24: ("RGB", "BGR"),
47
+ 32: ("RGB", "BGRX"),
48
+ }
49
+
50
+
51
+ def _accept(prefix):
52
+ return prefix[:2] == b"BM"
53
+
54
+
55
+ def _dib_accept(prefix):
56
+ return i32(prefix) in [12, 40, 64, 108, 124]
57
+
58
+
59
+ # =============================================================================
60
+ # Image plugin for the Windows BMP format.
61
+ # =============================================================================
62
+ class BmpImageFile(ImageFile.ImageFile):
63
+ """Image plugin for the Windows Bitmap format (BMP)"""
64
+
65
+ # ------------------------------------------------------------- Description
66
+ format_description = "Windows Bitmap"
67
+ format = "BMP"
68
+
69
+ # -------------------------------------------------- BMP Compression values
70
+ COMPRESSIONS = {"RAW": 0, "RLE8": 1, "RLE4": 2, "BITFIELDS": 3, "JPEG": 4, "PNG": 5}
71
+ for k, v in COMPRESSIONS.items():
72
+ vars()[k] = v
73
+
74
+ def _bitmap(self, header=0, offset=0):
75
+ """Read relevant info about the BMP"""
76
+ read, seek = self.fp.read, self.fp.seek
77
+ if header:
78
+ seek(header)
79
+ # read bmp header size @offset 14 (this is part of the header size)
80
+ file_info = {"header_size": i32(read(4)), "direction": -1}
81
+
82
+ # -------------------- If requested, read header at a specific position
83
+ # read the rest of the bmp header, without its size
84
+ header_data = ImageFile._safe_read(self.fp, file_info["header_size"] - 4)
85
+
86
+ # -------------------------------------------------- IBM OS/2 Bitmap v1
87
+ # ----- This format has different offsets because of width/height types
88
+ if file_info["header_size"] == 12:
89
+ file_info["width"] = i16(header_data, 0)
90
+ file_info["height"] = i16(header_data, 2)
91
+ file_info["planes"] = i16(header_data, 4)
92
+ file_info["bits"] = i16(header_data, 6)
93
+ file_info["compression"] = self.RAW
94
+ file_info["palette_padding"] = 3
95
+
96
+ # --------------------------------------------- Windows Bitmap v2 to v5
97
+ # v3, OS/2 v2, v4, v5
98
+ elif file_info["header_size"] in (40, 64, 108, 124):
99
+ file_info["y_flip"] = header_data[7] == 0xFF
100
+ file_info["direction"] = 1 if file_info["y_flip"] else -1
101
+ file_info["width"] = i32(header_data, 0)
102
+ file_info["height"] = (
103
+ i32(header_data, 4)
104
+ if not file_info["y_flip"]
105
+ else 2**32 - i32(header_data, 4)
106
+ )
107
+ file_info["planes"] = i16(header_data, 8)
108
+ file_info["bits"] = i16(header_data, 10)
109
+ file_info["compression"] = i32(header_data, 12)
110
+ # byte size of pixel data
111
+ file_info["data_size"] = i32(header_data, 16)
112
+ file_info["pixels_per_meter"] = (
113
+ i32(header_data, 20),
114
+ i32(header_data, 24),
115
+ )
116
+ file_info["colors"] = i32(header_data, 28)
117
+ file_info["palette_padding"] = 4
118
+ self.info["dpi"] = tuple(x / 39.3701 for x in file_info["pixels_per_meter"])
119
+ if file_info["compression"] == self.BITFIELDS:
120
+ if len(header_data) >= 52:
121
+ for idx, mask in enumerate(
122
+ ["r_mask", "g_mask", "b_mask", "a_mask"]
123
+ ):
124
+ file_info[mask] = i32(header_data, 36 + idx * 4)
125
+ else:
126
+ # 40 byte headers only have the three components in the
127
+ # bitfields masks, ref:
128
+ # https://msdn.microsoft.com/en-us/library/windows/desktop/dd183376(v=vs.85).aspx
129
+ # See also
130
+ # https://github.com/python-pillow/Pillow/issues/1293
131
+ # There is a 4th component in the RGBQuad, in the alpha
132
+ # location, but it is listed as a reserved component,
133
+ # and it is not generally an alpha channel
134
+ file_info["a_mask"] = 0x0
135
+ for mask in ["r_mask", "g_mask", "b_mask"]:
136
+ file_info[mask] = i32(read(4))
137
+ file_info["rgb_mask"] = (
138
+ file_info["r_mask"],
139
+ file_info["g_mask"],
140
+ file_info["b_mask"],
141
+ )
142
+ file_info["rgba_mask"] = (
143
+ file_info["r_mask"],
144
+ file_info["g_mask"],
145
+ file_info["b_mask"],
146
+ file_info["a_mask"],
147
+ )
148
+ else:
149
+ msg = f"Unsupported BMP header type ({file_info['header_size']})"
150
+ raise OSError(msg)
151
+
152
+ # ------------------ Special case : header is reported 40, which
153
+ # ---------------------- is shorter than real size for bpp >= 16
154
+ self._size = file_info["width"], file_info["height"]
155
+
156
+ # ------- If color count was not found in the header, compute from bits
157
+ file_info["colors"] = (
158
+ file_info["colors"]
159
+ if file_info.get("colors", 0)
160
+ else (1 << file_info["bits"])
161
+ )
162
+ if offset == 14 + file_info["header_size"] and file_info["bits"] <= 8:
163
+ offset += 4 * file_info["colors"]
164
+
165
+ # ---------------------- Check bit depth for unusual unsupported values
166
+ self._mode, raw_mode = BIT2MODE.get(file_info["bits"], (None, None))
167
+ if self.mode is None:
168
+ msg = f"Unsupported BMP pixel depth ({file_info['bits']})"
169
+ raise OSError(msg)
170
+
171
+ # ---------------- Process BMP with Bitfields compression (not palette)
172
+ decoder_name = "raw"
173
+ if file_info["compression"] == self.BITFIELDS:
174
+ SUPPORTED = {
175
+ 32: [
176
+ (0xFF0000, 0xFF00, 0xFF, 0x0),
177
+ (0xFF000000, 0xFF0000, 0xFF00, 0x0),
178
+ (0xFF000000, 0xFF0000, 0xFF00, 0xFF),
179
+ (0xFF, 0xFF00, 0xFF0000, 0xFF000000),
180
+ (0xFF0000, 0xFF00, 0xFF, 0xFF000000),
181
+ (0x0, 0x0, 0x0, 0x0),
182
+ ],
183
+ 24: [(0xFF0000, 0xFF00, 0xFF)],
184
+ 16: [(0xF800, 0x7E0, 0x1F), (0x7C00, 0x3E0, 0x1F)],
185
+ }
186
+ MASK_MODES = {
187
+ (32, (0xFF0000, 0xFF00, 0xFF, 0x0)): "BGRX",
188
+ (32, (0xFF000000, 0xFF0000, 0xFF00, 0x0)): "XBGR",
189
+ (32, (0xFF000000, 0xFF0000, 0xFF00, 0xFF)): "ABGR",
190
+ (32, (0xFF, 0xFF00, 0xFF0000, 0xFF000000)): "RGBA",
191
+ (32, (0xFF0000, 0xFF00, 0xFF, 0xFF000000)): "BGRA",
192
+ (32, (0x0, 0x0, 0x0, 0x0)): "BGRA",
193
+ (24, (0xFF0000, 0xFF00, 0xFF)): "BGR",
194
+ (16, (0xF800, 0x7E0, 0x1F)): "BGR;16",
195
+ (16, (0x7C00, 0x3E0, 0x1F)): "BGR;15",
196
+ }
197
+ if file_info["bits"] in SUPPORTED:
198
+ if (
199
+ file_info["bits"] == 32
200
+ and file_info["rgba_mask"] in SUPPORTED[file_info["bits"]]
201
+ ):
202
+ raw_mode = MASK_MODES[(file_info["bits"], file_info["rgba_mask"])]
203
+ self._mode = "RGBA" if "A" in raw_mode else self.mode
204
+ elif (
205
+ file_info["bits"] in (24, 16)
206
+ and file_info["rgb_mask"] in SUPPORTED[file_info["bits"]]
207
+ ):
208
+ raw_mode = MASK_MODES[(file_info["bits"], file_info["rgb_mask"])]
209
+ else:
210
+ msg = "Unsupported BMP bitfields layout"
211
+ raise OSError(msg)
212
+ else:
213
+ msg = "Unsupported BMP bitfields layout"
214
+ raise OSError(msg)
215
+ elif file_info["compression"] == self.RAW:
216
+ if file_info["bits"] == 32 and header == 22: # 32-bit .cur offset
217
+ raw_mode, self._mode = "BGRA", "RGBA"
218
+ elif file_info["compression"] in (self.RLE8, self.RLE4):
219
+ decoder_name = "bmp_rle"
220
+ else:
221
+ msg = f"Unsupported BMP compression ({file_info['compression']})"
222
+ raise OSError(msg)
223
+
224
+ # --------------- Once the header is processed, process the palette/LUT
225
+ if self.mode == "P": # Paletted for 1, 4 and 8 bit images
226
+ # ---------------------------------------------------- 1-bit images
227
+ if not (0 < file_info["colors"] <= 65536):
228
+ msg = f"Unsupported BMP Palette size ({file_info['colors']})"
229
+ raise OSError(msg)
230
+ else:
231
+ padding = file_info["palette_padding"]
232
+ palette = read(padding * file_info["colors"])
233
+ grayscale = True
234
+ indices = (
235
+ (0, 255)
236
+ if file_info["colors"] == 2
237
+ else list(range(file_info["colors"]))
238
+ )
239
+
240
+ # ----------------- Check if grayscale and ignore palette if so
241
+ for ind, val in enumerate(indices):
242
+ rgb = palette[ind * padding : ind * padding + 3]
243
+ if rgb != o8(val) * 3:
244
+ grayscale = False
245
+
246
+ # ------- If all colors are gray, white or black, ditch palette
247
+ if grayscale:
248
+ self._mode = "1" if file_info["colors"] == 2 else "L"
249
+ raw_mode = self.mode
250
+ else:
251
+ self._mode = "P"
252
+ self.palette = ImagePalette.raw(
253
+ "BGRX" if padding == 4 else "BGR", palette
254
+ )
255
+
256
+ # ---------------------------- Finally set the tile data for the plugin
257
+ self.info["compression"] = file_info["compression"]
258
+ args = [raw_mode]
259
+ if decoder_name == "bmp_rle":
260
+ args.append(file_info["compression"] == self.RLE4)
261
+ else:
262
+ args.append(((file_info["width"] * file_info["bits"] + 31) >> 3) & (~3))
263
+ args.append(file_info["direction"])
264
+ self.tile = [
265
+ (
266
+ decoder_name,
267
+ (0, 0, file_info["width"], file_info["height"]),
268
+ offset or self.fp.tell(),
269
+ tuple(args),
270
+ )
271
+ ]
272
+
273
+ def _open(self):
274
+ """Open file, check magic number and read header"""
275
+ # read 14 bytes: magic number, filesize, reserved, header final offset
276
+ head_data = self.fp.read(14)
277
+ # choke if the file does not have the required magic bytes
278
+ if not _accept(head_data):
279
+ msg = "Not a BMP file"
280
+ raise SyntaxError(msg)
281
+ # read the start position of the BMP image data (u32)
282
+ offset = i32(head_data, 10)
283
+ # load bitmap information (offset=raster info)
284
+ self._bitmap(offset=offset)
285
+
286
+
287
+ class BmpRleDecoder(ImageFile.PyDecoder):
288
+ _pulls_fd = True
289
+
290
+ def decode(self, buffer):
291
+ rle4 = self.args[1]
292
+ data = bytearray()
293
+ x = 0
294
+ dest_length = self.state.xsize * self.state.ysize
295
+ while len(data) < dest_length:
296
+ pixels = self.fd.read(1)
297
+ byte = self.fd.read(1)
298
+ if not pixels or not byte:
299
+ break
300
+ num_pixels = pixels[0]
301
+ if num_pixels:
302
+ # encoded mode
303
+ if x + num_pixels > self.state.xsize:
304
+ # Too much data for row
305
+ num_pixels = max(0, self.state.xsize - x)
306
+ if rle4:
307
+ first_pixel = o8(byte[0] >> 4)
308
+ second_pixel = o8(byte[0] & 0x0F)
309
+ for index in range(num_pixels):
310
+ if index % 2 == 0:
311
+ data += first_pixel
312
+ else:
313
+ data += second_pixel
314
+ else:
315
+ data += byte * num_pixels
316
+ x += num_pixels
317
+ else:
318
+ if byte[0] == 0:
319
+ # end of line
320
+ while len(data) % self.state.xsize != 0:
321
+ data += b"\x00"
322
+ x = 0
323
+ elif byte[0] == 1:
324
+ # end of bitmap
325
+ break
326
+ elif byte[0] == 2:
327
+ # delta
328
+ bytes_read = self.fd.read(2)
329
+ if len(bytes_read) < 2:
330
+ break
331
+ right, up = self.fd.read(2)
332
+ data += b"\x00" * (right + up * self.state.xsize)
333
+ x = len(data) % self.state.xsize
334
+ else:
335
+ # absolute mode
336
+ if rle4:
337
+ # 2 pixels per byte
338
+ byte_count = byte[0] // 2
339
+ bytes_read = self.fd.read(byte_count)
340
+ for byte_read in bytes_read:
341
+ data += o8(byte_read >> 4)
342
+ data += o8(byte_read & 0x0F)
343
+ else:
344
+ byte_count = byte[0]
345
+ bytes_read = self.fd.read(byte_count)
346
+ data += bytes_read
347
+ if len(bytes_read) < byte_count:
348
+ break
349
+ x += byte[0]
350
+
351
+ # align to 16-bit word boundary
352
+ if self.fd.tell() % 2 != 0:
353
+ self.fd.seek(1, os.SEEK_CUR)
354
+ rawmode = "L" if self.mode == "L" else "P"
355
+ self.set_as_raw(bytes(data), (rawmode, 0, self.args[-1]))
356
+ return -1, 0
357
+
358
+
359
+ # =============================================================================
360
+ # Image plugin for the DIB format (BMP alias)
361
+ # =============================================================================
362
+ class DibImageFile(BmpImageFile):
363
+ format = "DIB"
364
+ format_description = "Windows Bitmap"
365
+
366
+ def _open(self):
367
+ self._bitmap()
368
+
369
+
370
+ #
371
+ # --------------------------------------------------------------------
372
+ # Write BMP file
373
+
374
+
375
+ SAVE = {
376
+ "1": ("1", 1, 2),
377
+ "L": ("L", 8, 256),
378
+ "P": ("P", 8, 256),
379
+ "RGB": ("BGR", 24, 0),
380
+ "RGBA": ("BGRA", 32, 0),
381
+ }
382
+
383
+
384
+ def _dib_save(im, fp, filename):
385
+ _save(im, fp, filename, False)
386
+
387
+
388
+ def _save(im, fp, filename, bitmap_header=True):
389
+ try:
390
+ rawmode, bits, colors = SAVE[im.mode]
391
+ except KeyError as e:
392
+ msg = f"cannot write mode {im.mode} as BMP"
393
+ raise OSError(msg) from e
394
+
395
+ info = im.encoderinfo
396
+
397
+ dpi = info.get("dpi", (96, 96))
398
+
399
+ # 1 meter == 39.3701 inches
400
+ ppm = tuple(int(x * 39.3701 + 0.5) for x in dpi)
401
+
402
+ stride = ((im.size[0] * bits + 7) // 8 + 3) & (~3)
403
+ header = 40 # or 64 for OS/2 version 2
404
+ image = stride * im.size[1]
405
+
406
+ if im.mode == "1":
407
+ palette = b"".join(o8(i) * 4 for i in (0, 255))
408
+ elif im.mode == "L":
409
+ palette = b"".join(o8(i) * 4 for i in range(256))
410
+ elif im.mode == "P":
411
+ palette = im.im.getpalette("RGB", "BGRX")
412
+ colors = len(palette) // 4
413
+ else:
414
+ palette = None
415
+
416
+ # bitmap header
417
+ if bitmap_header:
418
+ offset = 14 + header + colors * 4
419
+ file_size = offset + image
420
+ if file_size > 2**32 - 1:
421
+ msg = "File size is too large for the BMP format"
422
+ raise ValueError(msg)
423
+ fp.write(
424
+ b"BM" # file type (magic)
425
+ + o32(file_size) # file size
426
+ + o32(0) # reserved
427
+ + o32(offset) # image data offset
428
+ )
429
+
430
+ # bitmap info header
431
+ fp.write(
432
+ o32(header) # info header size
433
+ + o32(im.size[0]) # width
434
+ + o32(im.size[1]) # height
435
+ + o16(1) # planes
436
+ + o16(bits) # depth
437
+ + o32(0) # compression (0=uncompressed)
438
+ + o32(image) # size of bitmap
439
+ + o32(ppm[0]) # resolution
440
+ + o32(ppm[1]) # resolution
441
+ + o32(colors) # colors used
442
+ + o32(colors) # colors important
443
+ )
444
+
445
+ fp.write(b"\0" * (header - 40)) # padding (for OS/2 format)
446
+
447
+ if palette:
448
+ fp.write(palette)
449
+
450
+ ImageFile._save(im, fp, [("raw", (0, 0) + im.size, 0, (rawmode, stride, -1))])
451
+
452
+
453
+ #
454
+ # --------------------------------------------------------------------
455
+ # Registry
456
+
457
+
458
+ Image.register_open(BmpImageFile.format, BmpImageFile, _accept)
459
+ Image.register_save(BmpImageFile.format, _save)
460
+
461
+ Image.register_extension(BmpImageFile.format, ".bmp")
462
+
463
+ Image.register_mime(BmpImageFile.format, "image/bmp")
464
+
465
+ Image.register_decoder("bmp_rle", BmpRleDecoder)
466
+
467
+ Image.register_open(DibImageFile.format, DibImageFile, _dib_accept)
468
+ Image.register_save(DibImageFile.format, _dib_save)
469
+
470
+ Image.register_extension(DibImageFile.format, ".dib")
471
+
472
+ Image.register_mime(DibImageFile.format, "image/bmp")
.venv/Lib/site-packages/PIL/BufrStubImagePlugin.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library
3
+ # $Id$
4
+ #
5
+ # BUFR stub adapter
6
+ #
7
+ # Copyright (c) 1996-2003 by Fredrik Lundh
8
+ #
9
+ # See the README file for information on usage and redistribution.
10
+ #
11
+ from __future__ import annotations
12
+
13
+ from . import Image, ImageFile
14
+
15
+ _handler = None
16
+
17
+
18
+ def register_handler(handler):
19
+ """
20
+ Install application-specific BUFR image handler.
21
+
22
+ :param handler: Handler object.
23
+ """
24
+ global _handler
25
+ _handler = handler
26
+
27
+
28
+ # --------------------------------------------------------------------
29
+ # Image adapter
30
+
31
+
32
+ def _accept(prefix):
33
+ return prefix[:4] == b"BUFR" or prefix[:4] == b"ZCZC"
34
+
35
+
36
+ class BufrStubImageFile(ImageFile.StubImageFile):
37
+ format = "BUFR"
38
+ format_description = "BUFR"
39
+
40
+ def _open(self):
41
+ offset = self.fp.tell()
42
+
43
+ if not _accept(self.fp.read(4)):
44
+ msg = "Not a BUFR file"
45
+ raise SyntaxError(msg)
46
+
47
+ self.fp.seek(offset)
48
+
49
+ # make something up
50
+ self._mode = "F"
51
+ self._size = 1, 1
52
+
53
+ loader = self._load()
54
+ if loader:
55
+ loader.open(self)
56
+
57
+ def _load(self):
58
+ return _handler
59
+
60
+
61
+ def _save(im, fp, filename):
62
+ if _handler is None or not hasattr(_handler, "save"):
63
+ msg = "BUFR save handler not installed"
64
+ raise OSError(msg)
65
+ _handler.save(im, fp, filename)
66
+
67
+
68
+ # --------------------------------------------------------------------
69
+ # Registry
70
+
71
+ Image.register_open(BufrStubImageFile.format, BufrStubImageFile, _accept)
72
+ Image.register_save(BufrStubImageFile.format, _save)
73
+
74
+ Image.register_extension(BufrStubImageFile.format, ".bufr")
.venv/Lib/site-packages/PIL/ContainerIO.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # a class to read from a container file
6
+ #
7
+ # History:
8
+ # 1995-06-18 fl Created
9
+ # 1995-09-07 fl Added readline(), readlines()
10
+ #
11
+ # Copyright (c) 1997-2001 by Secret Labs AB
12
+ # Copyright (c) 1995 by Fredrik Lundh
13
+ #
14
+ # See the README file for information on usage and redistribution.
15
+ #
16
+ from __future__ import annotations
17
+
18
+ import io
19
+ from typing import IO, AnyStr, Generic, Literal
20
+
21
+
22
+ class ContainerIO(Generic[AnyStr]):
23
+ """
24
+ A file object that provides read access to a part of an existing
25
+ file (for example a TAR file).
26
+ """
27
+
28
+ def __init__(self, file: IO[AnyStr], offset: int, length: int) -> None:
29
+ """
30
+ Create file object.
31
+
32
+ :param file: Existing file.
33
+ :param offset: Start of region, in bytes.
34
+ :param length: Size of region, in bytes.
35
+ """
36
+ self.fh: IO[AnyStr] = file
37
+ self.pos = 0
38
+ self.offset = offset
39
+ self.length = length
40
+ self.fh.seek(offset)
41
+
42
+ ##
43
+ # Always false.
44
+
45
+ def isatty(self) -> bool:
46
+ return False
47
+
48
+ def seek(self, offset: int, mode: Literal[0, 1, 2] = io.SEEK_SET) -> None:
49
+ """
50
+ Move file pointer.
51
+
52
+ :param offset: Offset in bytes.
53
+ :param mode: Starting position. Use 0 for beginning of region, 1
54
+ for current offset, and 2 for end of region. You cannot move
55
+ the pointer outside the defined region.
56
+ """
57
+ if mode == 1:
58
+ self.pos = self.pos + offset
59
+ elif mode == 2:
60
+ self.pos = self.length + offset
61
+ else:
62
+ self.pos = offset
63
+ # clamp
64
+ self.pos = max(0, min(self.pos, self.length))
65
+ self.fh.seek(self.offset + self.pos)
66
+
67
+ def tell(self) -> int:
68
+ """
69
+ Get current file pointer.
70
+
71
+ :returns: Offset from start of region, in bytes.
72
+ """
73
+ return self.pos
74
+
75
+ def read(self, n: int = 0) -> AnyStr:
76
+ """
77
+ Read data.
78
+
79
+ :param n: Number of bytes to read. If omitted or zero,
80
+ read until end of region.
81
+ :returns: An 8-bit string.
82
+ """
83
+ if n:
84
+ n = min(n, self.length - self.pos)
85
+ else:
86
+ n = self.length - self.pos
87
+ if not n: # EOF
88
+ return b"" if "b" in self.fh.mode else "" # type: ignore[return-value]
89
+ self.pos = self.pos + n
90
+ return self.fh.read(n)
91
+
92
+ def readline(self) -> AnyStr:
93
+ """
94
+ Read a line of text.
95
+
96
+ :returns: An 8-bit string.
97
+ """
98
+ s: AnyStr = b"" if "b" in self.fh.mode else "" # type: ignore[assignment]
99
+ newline_character = b"\n" if "b" in self.fh.mode else "\n"
100
+ while True:
101
+ c = self.read(1)
102
+ if not c:
103
+ break
104
+ s = s + c
105
+ if c == newline_character:
106
+ break
107
+ return s
108
+
109
+ def readlines(self) -> list[AnyStr]:
110
+ """
111
+ Read multiple lines of text.
112
+
113
+ :returns: A list of 8-bit strings.
114
+ """
115
+ lines = []
116
+ while True:
117
+ s = self.readline()
118
+ if not s:
119
+ break
120
+ lines.append(s)
121
+ return lines
.venv/Lib/site-packages/PIL/CurImagePlugin.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # Windows Cursor support for PIL
6
+ #
7
+ # notes:
8
+ # uses BmpImagePlugin.py to read the bitmap data.
9
+ #
10
+ # history:
11
+ # 96-05-27 fl Created
12
+ #
13
+ # Copyright (c) Secret Labs AB 1997.
14
+ # Copyright (c) Fredrik Lundh 1996.
15
+ #
16
+ # See the README file for information on usage and redistribution.
17
+ #
18
+ from __future__ import annotations
19
+
20
+ from . import BmpImagePlugin, Image
21
+ from ._binary import i16le as i16
22
+ from ._binary import i32le as i32
23
+
24
+ #
25
+ # --------------------------------------------------------------------
26
+
27
+
28
+ def _accept(prefix):
29
+ return prefix[:4] == b"\0\0\2\0"
30
+
31
+
32
+ ##
33
+ # Image plugin for Windows Cursor files.
34
+
35
+
36
+ class CurImageFile(BmpImagePlugin.BmpImageFile):
37
+ format = "CUR"
38
+ format_description = "Windows Cursor"
39
+
40
+ def _open(self):
41
+ offset = self.fp.tell()
42
+
43
+ # check magic
44
+ s = self.fp.read(6)
45
+ if not _accept(s):
46
+ msg = "not a CUR file"
47
+ raise SyntaxError(msg)
48
+
49
+ # pick the largest cursor in the file
50
+ m = b""
51
+ for i in range(i16(s, 4)):
52
+ s = self.fp.read(16)
53
+ if not m:
54
+ m = s
55
+ elif s[0] > m[0] and s[1] > m[1]:
56
+ m = s
57
+ if not m:
58
+ msg = "No cursors were found"
59
+ raise TypeError(msg)
60
+
61
+ # load as bitmap
62
+ self._bitmap(i32(m, 12) + offset)
63
+
64
+ # patch up the bitmap height
65
+ self._size = self.size[0], self.size[1] // 2
66
+ d, e, o, a = self.tile[0]
67
+ self.tile[0] = d, (0, 0) + self.size, o, a
68
+
69
+
70
+ #
71
+ # --------------------------------------------------------------------
72
+
73
+ Image.register_open(CurImageFile.format, CurImageFile, _accept)
74
+
75
+ Image.register_extension(CurImageFile.format, ".cur")
.venv/Lib/site-packages/PIL/DcxImagePlugin.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # DCX file handling
6
+ #
7
+ # DCX is a container file format defined by Intel, commonly used
8
+ # for fax applications. Each DCX file consists of a directory
9
+ # (a list of file offsets) followed by a set of (usually 1-bit)
10
+ # PCX files.
11
+ #
12
+ # History:
13
+ # 1995-09-09 fl Created
14
+ # 1996-03-20 fl Properly derived from PcxImageFile.
15
+ # 1998-07-15 fl Renamed offset attribute to avoid name clash
16
+ # 2002-07-30 fl Fixed file handling
17
+ #
18
+ # Copyright (c) 1997-98 by Secret Labs AB.
19
+ # Copyright (c) 1995-96 by Fredrik Lundh.
20
+ #
21
+ # See the README file for information on usage and redistribution.
22
+ #
23
+ from __future__ import annotations
24
+
25
+ from . import Image
26
+ from ._binary import i32le as i32
27
+ from .PcxImagePlugin import PcxImageFile
28
+
29
+ MAGIC = 0x3ADE68B1 # QUIZ: what's this value, then?
30
+
31
+
32
+ def _accept(prefix):
33
+ return len(prefix) >= 4 and i32(prefix) == MAGIC
34
+
35
+
36
+ ##
37
+ # Image plugin for the Intel DCX format.
38
+
39
+
40
+ class DcxImageFile(PcxImageFile):
41
+ format = "DCX"
42
+ format_description = "Intel DCX"
43
+ _close_exclusive_fp_after_loading = False
44
+
45
+ def _open(self):
46
+ # Header
47
+ s = self.fp.read(4)
48
+ if not _accept(s):
49
+ msg = "not a DCX file"
50
+ raise SyntaxError(msg)
51
+
52
+ # Component directory
53
+ self._offset = []
54
+ for i in range(1024):
55
+ offset = i32(self.fp.read(4))
56
+ if not offset:
57
+ break
58
+ self._offset.append(offset)
59
+
60
+ self._fp = self.fp
61
+ self.frame = None
62
+ self.n_frames = len(self._offset)
63
+ self.is_animated = self.n_frames > 1
64
+ self.seek(0)
65
+
66
+ def seek(self, frame):
67
+ if not self._seek_check(frame):
68
+ return
69
+ self.frame = frame
70
+ self.fp = self._fp
71
+ self.fp.seek(self._offset[frame])
72
+ PcxImageFile._open(self)
73
+
74
+ def tell(self):
75
+ return self.frame
76
+
77
+
78
+ Image.register_open(DcxImageFile.format, DcxImageFile, _accept)
79
+
80
+ Image.register_extension(DcxImageFile.format, ".dcx")
.venv/Lib/site-packages/PIL/DdsImagePlugin.py ADDED
@@ -0,0 +1,572 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A Pillow loader for .dds files (S3TC-compressed aka DXTC)
3
+ Jerome Leclanche <jerome@leclan.ch>
4
+
5
+ Documentation:
6
+ https://web.archive.org/web/20170802060935/http://oss.sgi.com/projects/ogl-sample/registry/EXT/texture_compression_s3tc.txt
7
+
8
+ The contents of this file are hereby released in the public domain (CC0)
9
+ Full text of the CC0 license:
10
+ https://creativecommons.org/publicdomain/zero/1.0/
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import io
16
+ import struct
17
+ import sys
18
+ from enum import IntEnum, IntFlag
19
+
20
+ from . import Image, ImageFile, ImagePalette
21
+ from ._binary import i32le as i32
22
+ from ._binary import o8
23
+ from ._binary import o32le as o32
24
+
25
+ # Magic ("DDS ")
26
+ DDS_MAGIC = 0x20534444
27
+
28
+
29
+ # DDS flags
30
+ class DDSD(IntFlag):
31
+ CAPS = 0x1
32
+ HEIGHT = 0x2
33
+ WIDTH = 0x4
34
+ PITCH = 0x8
35
+ PIXELFORMAT = 0x1000
36
+ MIPMAPCOUNT = 0x20000
37
+ LINEARSIZE = 0x80000
38
+ DEPTH = 0x800000
39
+
40
+
41
+ # DDS caps
42
+ class DDSCAPS(IntFlag):
43
+ COMPLEX = 0x8
44
+ TEXTURE = 0x1000
45
+ MIPMAP = 0x400000
46
+
47
+
48
+ class DDSCAPS2(IntFlag):
49
+ CUBEMAP = 0x200
50
+ CUBEMAP_POSITIVEX = 0x400
51
+ CUBEMAP_NEGATIVEX = 0x800
52
+ CUBEMAP_POSITIVEY = 0x1000
53
+ CUBEMAP_NEGATIVEY = 0x2000
54
+ CUBEMAP_POSITIVEZ = 0x4000
55
+ CUBEMAP_NEGATIVEZ = 0x8000
56
+ VOLUME = 0x200000
57
+
58
+
59
+ # Pixel Format
60
+ class DDPF(IntFlag):
61
+ ALPHAPIXELS = 0x1
62
+ ALPHA = 0x2
63
+ FOURCC = 0x4
64
+ PALETTEINDEXED8 = 0x20
65
+ RGB = 0x40
66
+ LUMINANCE = 0x20000
67
+
68
+
69
+ # dxgiformat.h
70
+ class DXGI_FORMAT(IntEnum):
71
+ UNKNOWN = 0
72
+ R32G32B32A32_TYPELESS = 1
73
+ R32G32B32A32_FLOAT = 2
74
+ R32G32B32A32_UINT = 3
75
+ R32G32B32A32_SINT = 4
76
+ R32G32B32_TYPELESS = 5
77
+ R32G32B32_FLOAT = 6
78
+ R32G32B32_UINT = 7
79
+ R32G32B32_SINT = 8
80
+ R16G16B16A16_TYPELESS = 9
81
+ R16G16B16A16_FLOAT = 10
82
+ R16G16B16A16_UNORM = 11
83
+ R16G16B16A16_UINT = 12
84
+ R16G16B16A16_SNORM = 13
85
+ R16G16B16A16_SINT = 14
86
+ R32G32_TYPELESS = 15
87
+ R32G32_FLOAT = 16
88
+ R32G32_UINT = 17
89
+ R32G32_SINT = 18
90
+ R32G8X24_TYPELESS = 19
91
+ D32_FLOAT_S8X24_UINT = 20
92
+ R32_FLOAT_X8X24_TYPELESS = 21
93
+ X32_TYPELESS_G8X24_UINT = 22
94
+ R10G10B10A2_TYPELESS = 23
95
+ R10G10B10A2_UNORM = 24
96
+ R10G10B10A2_UINT = 25
97
+ R11G11B10_FLOAT = 26
98
+ R8G8B8A8_TYPELESS = 27
99
+ R8G8B8A8_UNORM = 28
100
+ R8G8B8A8_UNORM_SRGB = 29
101
+ R8G8B8A8_UINT = 30
102
+ R8G8B8A8_SNORM = 31
103
+ R8G8B8A8_SINT = 32
104
+ R16G16_TYPELESS = 33
105
+ R16G16_FLOAT = 34
106
+ R16G16_UNORM = 35
107
+ R16G16_UINT = 36
108
+ R16G16_SNORM = 37
109
+ R16G16_SINT = 38
110
+ R32_TYPELESS = 39
111
+ D32_FLOAT = 40
112
+ R32_FLOAT = 41
113
+ R32_UINT = 42
114
+ R32_SINT = 43
115
+ R24G8_TYPELESS = 44
116
+ D24_UNORM_S8_UINT = 45
117
+ R24_UNORM_X8_TYPELESS = 46
118
+ X24_TYPELESS_G8_UINT = 47
119
+ R8G8_TYPELESS = 48
120
+ R8G8_UNORM = 49
121
+ R8G8_UINT = 50
122
+ R8G8_SNORM = 51
123
+ R8G8_SINT = 52
124
+ R16_TYPELESS = 53
125
+ R16_FLOAT = 54
126
+ D16_UNORM = 55
127
+ R16_UNORM = 56
128
+ R16_UINT = 57
129
+ R16_SNORM = 58
130
+ R16_SINT = 59
131
+ R8_TYPELESS = 60
132
+ R8_UNORM = 61
133
+ R8_UINT = 62
134
+ R8_SNORM = 63
135
+ R8_SINT = 64
136
+ A8_UNORM = 65
137
+ R1_UNORM = 66
138
+ R9G9B9E5_SHAREDEXP = 67
139
+ R8G8_B8G8_UNORM = 68
140
+ G8R8_G8B8_UNORM = 69
141
+ BC1_TYPELESS = 70
142
+ BC1_UNORM = 71
143
+ BC1_UNORM_SRGB = 72
144
+ BC2_TYPELESS = 73
145
+ BC2_UNORM = 74
146
+ BC2_UNORM_SRGB = 75
147
+ BC3_TYPELESS = 76
148
+ BC3_UNORM = 77
149
+ BC3_UNORM_SRGB = 78
150
+ BC4_TYPELESS = 79
151
+ BC4_UNORM = 80
152
+ BC4_SNORM = 81
153
+ BC5_TYPELESS = 82
154
+ BC5_UNORM = 83
155
+ BC5_SNORM = 84
156
+ B5G6R5_UNORM = 85
157
+ B5G5R5A1_UNORM = 86
158
+ B8G8R8A8_UNORM = 87
159
+ B8G8R8X8_UNORM = 88
160
+ R10G10B10_XR_BIAS_A2_UNORM = 89
161
+ B8G8R8A8_TYPELESS = 90
162
+ B8G8R8A8_UNORM_SRGB = 91
163
+ B8G8R8X8_TYPELESS = 92
164
+ B8G8R8X8_UNORM_SRGB = 93
165
+ BC6H_TYPELESS = 94
166
+ BC6H_UF16 = 95
167
+ BC6H_SF16 = 96
168
+ BC7_TYPELESS = 97
169
+ BC7_UNORM = 98
170
+ BC7_UNORM_SRGB = 99
171
+ AYUV = 100
172
+ Y410 = 101
173
+ Y416 = 102
174
+ NV12 = 103
175
+ P010 = 104
176
+ P016 = 105
177
+ OPAQUE_420 = 106
178
+ YUY2 = 107
179
+ Y210 = 108
180
+ Y216 = 109
181
+ NV11 = 110
182
+ AI44 = 111
183
+ IA44 = 112
184
+ P8 = 113
185
+ A8P8 = 114
186
+ B4G4R4A4_UNORM = 115
187
+ P208 = 130
188
+ V208 = 131
189
+ V408 = 132
190
+ SAMPLER_FEEDBACK_MIN_MIP_OPAQUE = 189
191
+ SAMPLER_FEEDBACK_MIP_REGION_USED_OPAQUE = 190
192
+
193
+
194
+ class D3DFMT(IntEnum):
195
+ UNKNOWN = 0
196
+ R8G8B8 = 20
197
+ A8R8G8B8 = 21
198
+ X8R8G8B8 = 22
199
+ R5G6B5 = 23
200
+ X1R5G5B5 = 24
201
+ A1R5G5B5 = 25
202
+ A4R4G4B4 = 26
203
+ R3G3B2 = 27
204
+ A8 = 28
205
+ A8R3G3B2 = 29
206
+ X4R4G4B4 = 30
207
+ A2B10G10R10 = 31
208
+ A8B8G8R8 = 32
209
+ X8B8G8R8 = 33
210
+ G16R16 = 34
211
+ A2R10G10B10 = 35
212
+ A16B16G16R16 = 36
213
+ A8P8 = 40
214
+ P8 = 41
215
+ L8 = 50
216
+ A8L8 = 51
217
+ A4L4 = 52
218
+ V8U8 = 60
219
+ L6V5U5 = 61
220
+ X8L8V8U8 = 62
221
+ Q8W8V8U8 = 63
222
+ V16U16 = 64
223
+ A2W10V10U10 = 67
224
+ D16_LOCKABLE = 70
225
+ D32 = 71
226
+ D15S1 = 73
227
+ D24S8 = 75
228
+ D24X8 = 77
229
+ D24X4S4 = 79
230
+ D16 = 80
231
+ D32F_LOCKABLE = 82
232
+ D24FS8 = 83
233
+ D32_LOCKABLE = 84
234
+ S8_LOCKABLE = 85
235
+ L16 = 81
236
+ VERTEXDATA = 100
237
+ INDEX16 = 101
238
+ INDEX32 = 102
239
+ Q16W16V16U16 = 110
240
+ R16F = 111
241
+ G16R16F = 112
242
+ A16B16G16R16F = 113
243
+ R32F = 114
244
+ G32R32F = 115
245
+ A32B32G32R32F = 116
246
+ CxV8U8 = 117
247
+ A1 = 118
248
+ A2B10G10R10_XR_BIAS = 119
249
+ BINARYBUFFER = 199
250
+
251
+ UYVY = i32(b"UYVY")
252
+ R8G8_B8G8 = i32(b"RGBG")
253
+ YUY2 = i32(b"YUY2")
254
+ G8R8_G8B8 = i32(b"GRGB")
255
+ DXT1 = i32(b"DXT1")
256
+ DXT2 = i32(b"DXT2")
257
+ DXT3 = i32(b"DXT3")
258
+ DXT4 = i32(b"DXT4")
259
+ DXT5 = i32(b"DXT5")
260
+ DX10 = i32(b"DX10")
261
+ BC4S = i32(b"BC4S")
262
+ BC4U = i32(b"BC4U")
263
+ BC5S = i32(b"BC5S")
264
+ BC5U = i32(b"BC5U")
265
+ ATI1 = i32(b"ATI1")
266
+ ATI2 = i32(b"ATI2")
267
+ MULTI2_ARGB8 = i32(b"MET1")
268
+
269
+
270
+ # Backward compatibility layer
271
+ module = sys.modules[__name__]
272
+ for item in DDSD:
273
+ assert item.name is not None
274
+ setattr(module, "DDSD_" + item.name, item.value)
275
+ for item1 in DDSCAPS:
276
+ assert item1.name is not None
277
+ setattr(module, "DDSCAPS_" + item1.name, item1.value)
278
+ for item2 in DDSCAPS2:
279
+ assert item2.name is not None
280
+ setattr(module, "DDSCAPS2_" + item2.name, item2.value)
281
+ for item3 in DDPF:
282
+ assert item3.name is not None
283
+ setattr(module, "DDPF_" + item3.name, item3.value)
284
+
285
+ DDS_FOURCC = DDPF.FOURCC
286
+ DDS_RGB = DDPF.RGB
287
+ DDS_RGBA = DDPF.RGB | DDPF.ALPHAPIXELS
288
+ DDS_LUMINANCE = DDPF.LUMINANCE
289
+ DDS_LUMINANCEA = DDPF.LUMINANCE | DDPF.ALPHAPIXELS
290
+ DDS_ALPHA = DDPF.ALPHA
291
+ DDS_PAL8 = DDPF.PALETTEINDEXED8
292
+
293
+ DDS_HEADER_FLAGS_TEXTURE = DDSD.CAPS | DDSD.HEIGHT | DDSD.WIDTH | DDSD.PIXELFORMAT
294
+ DDS_HEADER_FLAGS_MIPMAP = DDSD.MIPMAPCOUNT
295
+ DDS_HEADER_FLAGS_VOLUME = DDSD.DEPTH
296
+ DDS_HEADER_FLAGS_PITCH = DDSD.PITCH
297
+ DDS_HEADER_FLAGS_LINEARSIZE = DDSD.LINEARSIZE
298
+
299
+ DDS_HEIGHT = DDSD.HEIGHT
300
+ DDS_WIDTH = DDSD.WIDTH
301
+
302
+ DDS_SURFACE_FLAGS_TEXTURE = DDSCAPS.TEXTURE
303
+ DDS_SURFACE_FLAGS_MIPMAP = DDSCAPS.COMPLEX | DDSCAPS.MIPMAP
304
+ DDS_SURFACE_FLAGS_CUBEMAP = DDSCAPS.COMPLEX
305
+
306
+ DDS_CUBEMAP_POSITIVEX = DDSCAPS2.CUBEMAP | DDSCAPS2.CUBEMAP_POSITIVEX
307
+ DDS_CUBEMAP_NEGATIVEX = DDSCAPS2.CUBEMAP | DDSCAPS2.CUBEMAP_NEGATIVEX
308
+ DDS_CUBEMAP_POSITIVEY = DDSCAPS2.CUBEMAP | DDSCAPS2.CUBEMAP_POSITIVEY
309
+ DDS_CUBEMAP_NEGATIVEY = DDSCAPS2.CUBEMAP | DDSCAPS2.CUBEMAP_NEGATIVEY
310
+ DDS_CUBEMAP_POSITIVEZ = DDSCAPS2.CUBEMAP | DDSCAPS2.CUBEMAP_POSITIVEZ
311
+ DDS_CUBEMAP_NEGATIVEZ = DDSCAPS2.CUBEMAP | DDSCAPS2.CUBEMAP_NEGATIVEZ
312
+
313
+ DXT1_FOURCC = D3DFMT.DXT1
314
+ DXT3_FOURCC = D3DFMT.DXT3
315
+ DXT5_FOURCC = D3DFMT.DXT5
316
+
317
+ DXGI_FORMAT_R8G8B8A8_TYPELESS = DXGI_FORMAT.R8G8B8A8_TYPELESS
318
+ DXGI_FORMAT_R8G8B8A8_UNORM = DXGI_FORMAT.R8G8B8A8_UNORM
319
+ DXGI_FORMAT_R8G8B8A8_UNORM_SRGB = DXGI_FORMAT.R8G8B8A8_UNORM_SRGB
320
+ DXGI_FORMAT_BC5_TYPELESS = DXGI_FORMAT.BC5_TYPELESS
321
+ DXGI_FORMAT_BC5_UNORM = DXGI_FORMAT.BC5_UNORM
322
+ DXGI_FORMAT_BC5_SNORM = DXGI_FORMAT.BC5_SNORM
323
+ DXGI_FORMAT_BC6H_UF16 = DXGI_FORMAT.BC6H_UF16
324
+ DXGI_FORMAT_BC6H_SF16 = DXGI_FORMAT.BC6H_SF16
325
+ DXGI_FORMAT_BC7_TYPELESS = DXGI_FORMAT.BC7_TYPELESS
326
+ DXGI_FORMAT_BC7_UNORM = DXGI_FORMAT.BC7_UNORM
327
+ DXGI_FORMAT_BC7_UNORM_SRGB = DXGI_FORMAT.BC7_UNORM_SRGB
328
+
329
+
330
+ class DdsImageFile(ImageFile.ImageFile):
331
+ format = "DDS"
332
+ format_description = "DirectDraw Surface"
333
+
334
+ def _open(self):
335
+ if not _accept(self.fp.read(4)):
336
+ msg = "not a DDS file"
337
+ raise SyntaxError(msg)
338
+ (header_size,) = struct.unpack("<I", self.fp.read(4))
339
+ if header_size != 124:
340
+ msg = f"Unsupported header size {repr(header_size)}"
341
+ raise OSError(msg)
342
+ header_bytes = self.fp.read(header_size - 4)
343
+ if len(header_bytes) != 120:
344
+ msg = f"Incomplete header: {len(header_bytes)} bytes"
345
+ raise OSError(msg)
346
+ header = io.BytesIO(header_bytes)
347
+
348
+ flags, height, width = struct.unpack("<3I", header.read(12))
349
+ self._size = (width, height)
350
+ extents = (0, 0) + self.size
351
+
352
+ pitch, depth, mipmaps = struct.unpack("<3I", header.read(12))
353
+ struct.unpack("<11I", header.read(44)) # reserved
354
+
355
+ # pixel format
356
+ pfsize, pfflags, fourcc, bitcount = struct.unpack("<4I", header.read(16))
357
+ n = 0
358
+ rawmode = None
359
+ if pfflags & DDPF.RGB:
360
+ # Texture contains uncompressed RGB data
361
+ if pfflags & DDPF.ALPHAPIXELS:
362
+ self._mode = "RGBA"
363
+ mask_count = 4
364
+ else:
365
+ self._mode = "RGB"
366
+ mask_count = 3
367
+
368
+ masks = struct.unpack(f"<{mask_count}I", header.read(mask_count * 4))
369
+ self.tile = [("dds_rgb", extents, 0, (bitcount, masks))]
370
+ return
371
+ elif pfflags & DDPF.LUMINANCE:
372
+ if bitcount == 8:
373
+ self._mode = "L"
374
+ elif bitcount == 16 and pfflags & DDPF.ALPHAPIXELS:
375
+ self._mode = "LA"
376
+ else:
377
+ msg = f"Unsupported bitcount {bitcount} for {pfflags}"
378
+ raise OSError(msg)
379
+ elif pfflags & DDPF.PALETTEINDEXED8:
380
+ self._mode = "P"
381
+ self.palette = ImagePalette.raw("RGBA", self.fp.read(1024))
382
+ elif pfflags & DDPF.FOURCC:
383
+ offset = header_size + 4
384
+ if fourcc == D3DFMT.DXT1:
385
+ self._mode = "RGBA"
386
+ self.pixel_format = "DXT1"
387
+ n = 1
388
+ elif fourcc == D3DFMT.DXT3:
389
+ self._mode = "RGBA"
390
+ self.pixel_format = "DXT3"
391
+ n = 2
392
+ elif fourcc == D3DFMT.DXT5:
393
+ self._mode = "RGBA"
394
+ self.pixel_format = "DXT5"
395
+ n = 3
396
+ elif fourcc in (D3DFMT.BC4U, D3DFMT.ATI1):
397
+ self._mode = "L"
398
+ self.pixel_format = "BC4"
399
+ n = 4
400
+ elif fourcc == D3DFMT.BC5S:
401
+ self._mode = "RGB"
402
+ self.pixel_format = "BC5S"
403
+ n = 5
404
+ elif fourcc in (D3DFMT.BC5U, D3DFMT.ATI2):
405
+ self._mode = "RGB"
406
+ self.pixel_format = "BC5"
407
+ n = 5
408
+ elif fourcc == D3DFMT.DX10:
409
+ offset += 20
410
+ # ignoring flags which pertain to volume textures and cubemaps
411
+ (dxgi_format,) = struct.unpack("<I", self.fp.read(4))
412
+ self.fp.read(16)
413
+ if dxgi_format in (
414
+ DXGI_FORMAT.BC1_UNORM,
415
+ DXGI_FORMAT.BC1_TYPELESS,
416
+ ):
417
+ self._mode = "RGBA"
418
+ self.pixel_format = "BC1"
419
+ n = 1
420
+ elif dxgi_format in (DXGI_FORMAT.BC4_TYPELESS, DXGI_FORMAT.BC4_UNORM):
421
+ self._mode = "L"
422
+ self.pixel_format = "BC4"
423
+ n = 4
424
+ elif dxgi_format in (DXGI_FORMAT.BC5_TYPELESS, DXGI_FORMAT.BC5_UNORM):
425
+ self._mode = "RGB"
426
+ self.pixel_format = "BC5"
427
+ n = 5
428
+ elif dxgi_format == DXGI_FORMAT.BC5_SNORM:
429
+ self._mode = "RGB"
430
+ self.pixel_format = "BC5S"
431
+ n = 5
432
+ elif dxgi_format == DXGI_FORMAT.BC6H_UF16:
433
+ self._mode = "RGB"
434
+ self.pixel_format = "BC6H"
435
+ n = 6
436
+ elif dxgi_format == DXGI_FORMAT.BC6H_SF16:
437
+ self._mode = "RGB"
438
+ self.pixel_format = "BC6HS"
439
+ n = 6
440
+ elif dxgi_format in (
441
+ DXGI_FORMAT.BC7_TYPELESS,
442
+ DXGI_FORMAT.BC7_UNORM,
443
+ DXGI_FORMAT.BC7_UNORM_SRGB,
444
+ ):
445
+ self._mode = "RGBA"
446
+ self.pixel_format = "BC7"
447
+ n = 7
448
+ if dxgi_format == DXGI_FORMAT.BC7_UNORM_SRGB:
449
+ self.info["gamma"] = 1 / 2.2
450
+ elif dxgi_format in (
451
+ DXGI_FORMAT.R8G8B8A8_TYPELESS,
452
+ DXGI_FORMAT.R8G8B8A8_UNORM,
453
+ DXGI_FORMAT.R8G8B8A8_UNORM_SRGB,
454
+ ):
455
+ self._mode = "RGBA"
456
+ if dxgi_format == DXGI_FORMAT.R8G8B8A8_UNORM_SRGB:
457
+ self.info["gamma"] = 1 / 2.2
458
+ else:
459
+ msg = f"Unimplemented DXGI format {dxgi_format}"
460
+ raise NotImplementedError(msg)
461
+ else:
462
+ msg = f"Unimplemented pixel format {repr(fourcc)}"
463
+ raise NotImplementedError(msg)
464
+ else:
465
+ msg = f"Unknown pixel format flags {pfflags}"
466
+ raise NotImplementedError(msg)
467
+
468
+ if n:
469
+ self.tile = [
470
+ ImageFile._Tile("bcn", extents, offset, (n, self.pixel_format))
471
+ ]
472
+ else:
473
+ self.tile = [ImageFile._Tile("raw", extents, 0, rawmode or self.mode)]
474
+
475
+ def load_seek(self, pos):
476
+ pass
477
+
478
+
479
+ class DdsRgbDecoder(ImageFile.PyDecoder):
480
+ _pulls_fd = True
481
+
482
+ def decode(self, buffer):
483
+ bitcount, masks = self.args
484
+
485
+ # Some masks will be padded with zeros, e.g. R 0b11 G 0b1100
486
+ # Calculate how many zeros each mask is padded with
487
+ mask_offsets = []
488
+ # And the maximum value of each channel without the padding
489
+ mask_totals = []
490
+ for mask in masks:
491
+ offset = 0
492
+ if mask != 0:
493
+ while mask >> (offset + 1) << (offset + 1) == mask:
494
+ offset += 1
495
+ mask_offsets.append(offset)
496
+ mask_totals.append(mask >> offset)
497
+
498
+ data = bytearray()
499
+ bytecount = bitcount // 8
500
+ dest_length = self.state.xsize * self.state.ysize * len(masks)
501
+ while len(data) < dest_length:
502
+ value = int.from_bytes(self.fd.read(bytecount), "little")
503
+ for i, mask in enumerate(masks):
504
+ masked_value = value & mask
505
+ # Remove the zero padding, and scale it to 8 bits
506
+ data += o8(
507
+ int(((masked_value >> mask_offsets[i]) / mask_totals[i]) * 255)
508
+ )
509
+ self.set_as_raw(data)
510
+ return -1, 0
511
+
512
+
513
+ def _save(im, fp, filename):
514
+ if im.mode not in ("RGB", "RGBA", "L", "LA"):
515
+ msg = f"cannot write mode {im.mode} as DDS"
516
+ raise OSError(msg)
517
+
518
+ alpha = im.mode[-1] == "A"
519
+ if im.mode[0] == "L":
520
+ pixel_flags = DDPF.LUMINANCE
521
+ rawmode = im.mode
522
+ if alpha:
523
+ rgba_mask = [0x000000FF, 0x000000FF, 0x000000FF]
524
+ else:
525
+ rgba_mask = [0xFF000000, 0xFF000000, 0xFF000000]
526
+ else:
527
+ pixel_flags = DDPF.RGB
528
+ rawmode = im.mode[::-1]
529
+ rgba_mask = [0x00FF0000, 0x0000FF00, 0x000000FF]
530
+
531
+ if alpha:
532
+ r, g, b, a = im.split()
533
+ im = Image.merge("RGBA", (a, r, g, b))
534
+ if alpha:
535
+ pixel_flags |= DDPF.ALPHAPIXELS
536
+ rgba_mask.append(0xFF000000 if alpha else 0)
537
+
538
+ flags = DDSD.CAPS | DDSD.HEIGHT | DDSD.WIDTH | DDSD.PITCH | DDSD.PIXELFORMAT
539
+ bitcount = len(im.getbands()) * 8
540
+ pitch = (im.width * bitcount + 7) // 8
541
+
542
+ fp.write(
543
+ o32(DDS_MAGIC)
544
+ + struct.pack(
545
+ "<7I",
546
+ 124, # header size
547
+ flags, # flags
548
+ im.height,
549
+ im.width,
550
+ pitch,
551
+ 0, # depth
552
+ 0, # mipmaps
553
+ )
554
+ + struct.pack("11I", *((0,) * 11)) # reserved
555
+ # pfsize, pfflags, fourcc, bitcount
556
+ + struct.pack("<4I", 32, pixel_flags, 0, bitcount)
557
+ + struct.pack("<4I", *rgba_mask) # dwRGBABitMask
558
+ + struct.pack("<5I", DDSCAPS.TEXTURE, 0, 0, 0, 0)
559
+ )
560
+ ImageFile._save(
561
+ im, fp, [ImageFile._Tile("raw", (0, 0) + im.size, 0, (rawmode, 0, 1))]
562
+ )
563
+
564
+
565
+ def _accept(prefix):
566
+ return prefix[:4] == b"DDS "
567
+
568
+
569
+ Image.register_open(DdsImageFile.format, DdsImageFile, _accept)
570
+ Image.register_decoder("dds_rgb", DdsRgbDecoder)
571
+ Image.register_save(DdsImageFile.format, _save)
572
+ Image.register_extension(DdsImageFile.format, ".dds")
.venv/Lib/site-packages/PIL/EpsImagePlugin.py ADDED
@@ -0,0 +1,474 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # EPS file handling
6
+ #
7
+ # History:
8
+ # 1995-09-01 fl Created (0.1)
9
+ # 1996-05-18 fl Don't choke on "atend" fields, Ghostscript interface (0.2)
10
+ # 1996-08-22 fl Don't choke on floating point BoundingBox values
11
+ # 1996-08-23 fl Handle files from Macintosh (0.3)
12
+ # 2001-02-17 fl Use 're' instead of 'regex' (Python 2.1) (0.4)
13
+ # 2003-09-07 fl Check gs.close status (from Federico Di Gregorio) (0.5)
14
+ # 2014-05-07 e Handling of EPS with binary preview and fixed resolution
15
+ # resizing
16
+ #
17
+ # Copyright (c) 1997-2003 by Secret Labs AB.
18
+ # Copyright (c) 1995-2003 by Fredrik Lundh
19
+ #
20
+ # See the README file for information on usage and redistribution.
21
+ #
22
+ from __future__ import annotations
23
+
24
+ import io
25
+ import os
26
+ import re
27
+ import subprocess
28
+ import sys
29
+ import tempfile
30
+
31
+ from . import Image, ImageFile
32
+ from ._binary import i32le as i32
33
+ from ._deprecate import deprecate
34
+
35
+ # --------------------------------------------------------------------
36
+
37
+
38
+ split = re.compile(r"^%%([^:]*):[ \t]*(.*)[ \t]*$")
39
+ field = re.compile(r"^%[%!\w]([^:]*)[ \t]*$")
40
+
41
+ gs_binary: str | bool | None = None
42
+ gs_windows_binary = None
43
+
44
+
45
+ def has_ghostscript():
46
+ global gs_binary, gs_windows_binary
47
+ if gs_binary is None:
48
+ if sys.platform.startswith("win"):
49
+ if gs_windows_binary is None:
50
+ import shutil
51
+
52
+ for binary in ("gswin32c", "gswin64c", "gs"):
53
+ if shutil.which(binary) is not None:
54
+ gs_windows_binary = binary
55
+ break
56
+ else:
57
+ gs_windows_binary = False
58
+ gs_binary = gs_windows_binary
59
+ else:
60
+ try:
61
+ subprocess.check_call(["gs", "--version"], stdout=subprocess.DEVNULL)
62
+ gs_binary = "gs"
63
+ except OSError:
64
+ gs_binary = False
65
+ return gs_binary is not False
66
+
67
+
68
+ def Ghostscript(tile, size, fp, scale=1, transparency=False):
69
+ """Render an image using Ghostscript"""
70
+ global gs_binary
71
+ if not has_ghostscript():
72
+ msg = "Unable to locate Ghostscript on paths"
73
+ raise OSError(msg)
74
+
75
+ # Unpack decoder tile
76
+ decoder, tile, offset, data = tile[0]
77
+ length, bbox = data
78
+
79
+ # Hack to support hi-res rendering
80
+ scale = int(scale) or 1
81
+ width = size[0] * scale
82
+ height = size[1] * scale
83
+ # resolution is dependent on bbox and size
84
+ res_x = 72.0 * width / (bbox[2] - bbox[0])
85
+ res_y = 72.0 * height / (bbox[3] - bbox[1])
86
+
87
+ out_fd, outfile = tempfile.mkstemp()
88
+ os.close(out_fd)
89
+
90
+ infile_temp = None
91
+ if hasattr(fp, "name") and os.path.exists(fp.name):
92
+ infile = fp.name
93
+ else:
94
+ in_fd, infile_temp = tempfile.mkstemp()
95
+ os.close(in_fd)
96
+ infile = infile_temp
97
+
98
+ # Ignore length and offset!
99
+ # Ghostscript can read it
100
+ # Copy whole file to read in Ghostscript
101
+ with open(infile_temp, "wb") as f:
102
+ # fetch length of fp
103
+ fp.seek(0, io.SEEK_END)
104
+ fsize = fp.tell()
105
+ # ensure start position
106
+ # go back
107
+ fp.seek(0)
108
+ lengthfile = fsize
109
+ while lengthfile > 0:
110
+ s = fp.read(min(lengthfile, 100 * 1024))
111
+ if not s:
112
+ break
113
+ lengthfile -= len(s)
114
+ f.write(s)
115
+
116
+ device = "pngalpha" if transparency else "ppmraw"
117
+
118
+ # Build Ghostscript command
119
+ command = [
120
+ gs_binary,
121
+ "-q", # quiet mode
122
+ f"-g{width:d}x{height:d}", # set output geometry (pixels)
123
+ f"-r{res_x:f}x{res_y:f}", # set input DPI (dots per inch)
124
+ "-dBATCH", # exit after processing
125
+ "-dNOPAUSE", # don't pause between pages
126
+ "-dSAFER", # safe mode
127
+ f"-sDEVICE={device}",
128
+ f"-sOutputFile={outfile}", # output file
129
+ # adjust for image origin
130
+ "-c",
131
+ f"{-bbox[0]} {-bbox[1]} translate",
132
+ "-f",
133
+ infile, # input file
134
+ # showpage (see https://bugs.ghostscript.com/show_bug.cgi?id=698272)
135
+ "-c",
136
+ "showpage",
137
+ ]
138
+
139
+ # push data through Ghostscript
140
+ try:
141
+ startupinfo = None
142
+ if sys.platform.startswith("win"):
143
+ startupinfo = subprocess.STARTUPINFO()
144
+ startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
145
+ subprocess.check_call(command, startupinfo=startupinfo)
146
+ out_im = Image.open(outfile)
147
+ out_im.load()
148
+ finally:
149
+ try:
150
+ os.unlink(outfile)
151
+ if infile_temp:
152
+ os.unlink(infile_temp)
153
+ except OSError:
154
+ pass
155
+
156
+ im = out_im.im.copy()
157
+ out_im.close()
158
+ return im
159
+
160
+
161
+ class PSFile:
162
+ """
163
+ Wrapper for bytesio object that treats either CR or LF as end of line.
164
+ This class is no longer used internally, but kept for backwards compatibility.
165
+ """
166
+
167
+ def __init__(self, fp):
168
+ deprecate(
169
+ "PSFile",
170
+ 11,
171
+ action="If you need the functionality of this class "
172
+ "you will need to implement it yourself.",
173
+ )
174
+ self.fp = fp
175
+ self.char = None
176
+
177
+ def seek(self, offset, whence=io.SEEK_SET):
178
+ self.char = None
179
+ self.fp.seek(offset, whence)
180
+
181
+ def readline(self):
182
+ s = [self.char or b""]
183
+ self.char = None
184
+
185
+ c = self.fp.read(1)
186
+ while (c not in b"\r\n") and len(c):
187
+ s.append(c)
188
+ c = self.fp.read(1)
189
+
190
+ self.char = self.fp.read(1)
191
+ # line endings can be 1 or 2 of \r \n, in either order
192
+ if self.char in b"\r\n":
193
+ self.char = None
194
+
195
+ return b"".join(s).decode("latin-1")
196
+
197
+
198
+ def _accept(prefix):
199
+ return prefix[:4] == b"%!PS" or (len(prefix) >= 4 and i32(prefix) == 0xC6D3D0C5)
200
+
201
+
202
+ ##
203
+ # Image plugin for Encapsulated PostScript. This plugin supports only
204
+ # a few variants of this format.
205
+
206
+
207
+ class EpsImageFile(ImageFile.ImageFile):
208
+ """EPS File Parser for the Python Imaging Library"""
209
+
210
+ format = "EPS"
211
+ format_description = "Encapsulated Postscript"
212
+
213
+ mode_map = {1: "L", 2: "LAB", 3: "RGB", 4: "CMYK"}
214
+
215
+ def _open(self):
216
+ (length, offset) = self._find_offset(self.fp)
217
+
218
+ # go to offset - start of "%!PS"
219
+ self.fp.seek(offset)
220
+
221
+ self._mode = "RGB"
222
+ self._size = None
223
+
224
+ byte_arr = bytearray(255)
225
+ bytes_mv = memoryview(byte_arr)
226
+ bytes_read = 0
227
+ reading_header_comments = True
228
+ reading_trailer_comments = False
229
+ trailer_reached = False
230
+
231
+ def check_required_header_comments():
232
+ if "PS-Adobe" not in self.info:
233
+ msg = 'EPS header missing "%!PS-Adobe" comment'
234
+ raise SyntaxError(msg)
235
+ if "BoundingBox" not in self.info:
236
+ msg = 'EPS header missing "%%BoundingBox" comment'
237
+ raise SyntaxError(msg)
238
+
239
+ def _read_comment(s):
240
+ nonlocal reading_trailer_comments
241
+ try:
242
+ m = split.match(s)
243
+ except re.error as e:
244
+ msg = "not an EPS file"
245
+ raise SyntaxError(msg) from e
246
+
247
+ if m:
248
+ k, v = m.group(1, 2)
249
+ self.info[k] = v
250
+ if k == "BoundingBox":
251
+ if v == "(atend)":
252
+ reading_trailer_comments = True
253
+ elif not self._size or (
254
+ trailer_reached and reading_trailer_comments
255
+ ):
256
+ try:
257
+ # Note: The DSC spec says that BoundingBox
258
+ # fields should be integers, but some drivers
259
+ # put floating point values there anyway.
260
+ box = [int(float(i)) for i in v.split()]
261
+ self._size = box[2] - box[0], box[3] - box[1]
262
+ self.tile = [
263
+ ("eps", (0, 0) + self.size, offset, (length, box))
264
+ ]
265
+ except Exception:
266
+ pass
267
+ return True
268
+
269
+ while True:
270
+ byte = self.fp.read(1)
271
+ if byte == b"":
272
+ # if we didn't read a byte we must be at the end of the file
273
+ if bytes_read == 0:
274
+ break
275
+ elif byte in b"\r\n":
276
+ # if we read a line ending character, ignore it and parse what
277
+ # we have already read. if we haven't read any other characters,
278
+ # continue reading
279
+ if bytes_read == 0:
280
+ continue
281
+ else:
282
+ # ASCII/hexadecimal lines in an EPS file must not exceed
283
+ # 255 characters, not including line ending characters
284
+ if bytes_read >= 255:
285
+ # only enforce this for lines starting with a "%",
286
+ # otherwise assume it's binary data
287
+ if byte_arr[0] == ord("%"):
288
+ msg = "not an EPS file"
289
+ raise SyntaxError(msg)
290
+ else:
291
+ if reading_header_comments:
292
+ check_required_header_comments()
293
+ reading_header_comments = False
294
+ # reset bytes_read so we can keep reading
295
+ # data until the end of the line
296
+ bytes_read = 0
297
+ byte_arr[bytes_read] = byte[0]
298
+ bytes_read += 1
299
+ continue
300
+
301
+ if reading_header_comments:
302
+ # Load EPS header
303
+
304
+ # if this line doesn't start with a "%",
305
+ # or does start with "%%EndComments",
306
+ # then we've reached the end of the header/comments
307
+ if byte_arr[0] != ord("%") or bytes_mv[:13] == b"%%EndComments":
308
+ check_required_header_comments()
309
+ reading_header_comments = False
310
+ continue
311
+
312
+ s = str(bytes_mv[:bytes_read], "latin-1")
313
+ if not _read_comment(s):
314
+ m = field.match(s)
315
+ if m:
316
+ k = m.group(1)
317
+ if k[:8] == "PS-Adobe":
318
+ self.info["PS-Adobe"] = k[9:]
319
+ else:
320
+ self.info[k] = ""
321
+ elif s[0] == "%":
322
+ # handle non-DSC PostScript comments that some
323
+ # tools mistakenly put in the Comments section
324
+ pass
325
+ else:
326
+ msg = "bad EPS header"
327
+ raise OSError(msg)
328
+ elif bytes_mv[:11] == b"%ImageData:":
329
+ # Check for an "ImageData" descriptor
330
+ # https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#50577413_pgfId-1035096
331
+
332
+ # Values:
333
+ # columns
334
+ # rows
335
+ # bit depth (1 or 8)
336
+ # mode (1: L, 2: LAB, 3: RGB, 4: CMYK)
337
+ # number of padding channels
338
+ # block size (number of bytes per row per channel)
339
+ # binary/ascii (1: binary, 2: ascii)
340
+ # data start identifier (the image data follows after a single line
341
+ # consisting only of this quoted value)
342
+ image_data_values = byte_arr[11:bytes_read].split(None, 7)
343
+ columns, rows, bit_depth, mode_id = (
344
+ int(value) for value in image_data_values[:4]
345
+ )
346
+
347
+ if bit_depth == 1:
348
+ self._mode = "1"
349
+ elif bit_depth == 8:
350
+ try:
351
+ self._mode = self.mode_map[mode_id]
352
+ except ValueError:
353
+ break
354
+ else:
355
+ break
356
+
357
+ self._size = columns, rows
358
+ return
359
+ elif bytes_mv[:5] == b"%%EOF":
360
+ break
361
+ elif trailer_reached and reading_trailer_comments:
362
+ # Load EPS trailer
363
+ s = str(bytes_mv[:bytes_read], "latin-1")
364
+ _read_comment(s)
365
+ elif bytes_mv[:9] == b"%%Trailer":
366
+ trailer_reached = True
367
+ bytes_read = 0
368
+
369
+ check_required_header_comments()
370
+
371
+ if not self._size:
372
+ msg = "cannot determine EPS bounding box"
373
+ raise OSError(msg)
374
+
375
+ def _find_offset(self, fp):
376
+ s = fp.read(4)
377
+
378
+ if s == b"%!PS":
379
+ # for HEAD without binary preview
380
+ fp.seek(0, io.SEEK_END)
381
+ length = fp.tell()
382
+ offset = 0
383
+ elif i32(s) == 0xC6D3D0C5:
384
+ # FIX for: Some EPS file not handled correctly / issue #302
385
+ # EPS can contain binary data
386
+ # or start directly with latin coding
387
+ # more info see:
388
+ # https://web.archive.org/web/20160528181353/http://partners.adobe.com/public/developer/en/ps/5002.EPSF_Spec.pdf
389
+ s = fp.read(8)
390
+ offset = i32(s)
391
+ length = i32(s, 4)
392
+ else:
393
+ msg = "not an EPS file"
394
+ raise SyntaxError(msg)
395
+
396
+ return length, offset
397
+
398
+ def load(self, scale=1, transparency=False):
399
+ # Load EPS via Ghostscript
400
+ if self.tile:
401
+ self.im = Ghostscript(self.tile, self.size, self.fp, scale, transparency)
402
+ self._mode = self.im.mode
403
+ self._size = self.im.size
404
+ self.tile = []
405
+ return Image.Image.load(self)
406
+
407
+ def load_seek(self, pos):
408
+ # we can't incrementally load, so force ImageFile.parser to
409
+ # use our custom load method by defining this method.
410
+ pass
411
+
412
+
413
+ # --------------------------------------------------------------------
414
+
415
+
416
+ def _save(im, fp, filename, eps=1):
417
+ """EPS Writer for the Python Imaging Library."""
418
+
419
+ # make sure image data is available
420
+ im.load()
421
+
422
+ # determine PostScript image mode
423
+ if im.mode == "L":
424
+ operator = (8, 1, b"image")
425
+ elif im.mode == "RGB":
426
+ operator = (8, 3, b"false 3 colorimage")
427
+ elif im.mode == "CMYK":
428
+ operator = (8, 4, b"false 4 colorimage")
429
+ else:
430
+ msg = "image mode is not supported"
431
+ raise ValueError(msg)
432
+
433
+ if eps:
434
+ # write EPS header
435
+ fp.write(b"%!PS-Adobe-3.0 EPSF-3.0\n")
436
+ fp.write(b"%%Creator: PIL 0.1 EpsEncode\n")
437
+ # fp.write("%%CreationDate: %s"...)
438
+ fp.write(b"%%%%BoundingBox: 0 0 %d %d\n" % im.size)
439
+ fp.write(b"%%Pages: 1\n")
440
+ fp.write(b"%%EndComments\n")
441
+ fp.write(b"%%Page: 1 1\n")
442
+ fp.write(b"%%ImageData: %d %d " % im.size)
443
+ fp.write(b'%d %d 0 1 1 "%s"\n' % operator)
444
+
445
+ # image header
446
+ fp.write(b"gsave\n")
447
+ fp.write(b"10 dict begin\n")
448
+ fp.write(b"/buf %d string def\n" % (im.size[0] * operator[1]))
449
+ fp.write(b"%d %d scale\n" % im.size)
450
+ fp.write(b"%d %d 8\n" % im.size) # <= bits
451
+ fp.write(b"[%d 0 0 -%d 0 %d]\n" % (im.size[0], im.size[1], im.size[1]))
452
+ fp.write(b"{ currentfile buf readhexstring pop } bind\n")
453
+ fp.write(operator[2] + b"\n")
454
+ if hasattr(fp, "flush"):
455
+ fp.flush()
456
+
457
+ ImageFile._save(im, fp, [("eps", (0, 0) + im.size, 0, None)])
458
+
459
+ fp.write(b"\n%%%%EndBinary\n")
460
+ fp.write(b"grestore end\n")
461
+ if hasattr(fp, "flush"):
462
+ fp.flush()
463
+
464
+
465
+ # --------------------------------------------------------------------
466
+
467
+
468
+ Image.register_open(EpsImageFile.format, EpsImageFile, _accept)
469
+
470
+ Image.register_save(EpsImageFile.format, _save)
471
+
472
+ Image.register_extensions(EpsImageFile.format, [".ps", ".eps"])
473
+
474
+ Image.register_mime(EpsImageFile.format, "application/postscript")
.venv/Lib/site-packages/PIL/ExifTags.py ADDED
@@ -0,0 +1,381 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # EXIF tags
6
+ #
7
+ # Copyright (c) 2003 by Secret Labs AB
8
+ #
9
+ # See the README file for information on usage and redistribution.
10
+ #
11
+
12
+ """
13
+ This module provides constants and clear-text names for various
14
+ well-known EXIF tags.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ from enum import IntEnum
19
+
20
+
21
+ class Base(IntEnum):
22
+ # possibly incomplete
23
+ InteropIndex = 0x0001
24
+ ProcessingSoftware = 0x000B
25
+ NewSubfileType = 0x00FE
26
+ SubfileType = 0x00FF
27
+ ImageWidth = 0x0100
28
+ ImageLength = 0x0101
29
+ BitsPerSample = 0x0102
30
+ Compression = 0x0103
31
+ PhotometricInterpretation = 0x0106
32
+ Thresholding = 0x0107
33
+ CellWidth = 0x0108
34
+ CellLength = 0x0109
35
+ FillOrder = 0x010A
36
+ DocumentName = 0x010D
37
+ ImageDescription = 0x010E
38
+ Make = 0x010F
39
+ Model = 0x0110
40
+ StripOffsets = 0x0111
41
+ Orientation = 0x0112
42
+ SamplesPerPixel = 0x0115
43
+ RowsPerStrip = 0x0116
44
+ StripByteCounts = 0x0117
45
+ MinSampleValue = 0x0118
46
+ MaxSampleValue = 0x0119
47
+ XResolution = 0x011A
48
+ YResolution = 0x011B
49
+ PlanarConfiguration = 0x011C
50
+ PageName = 0x011D
51
+ FreeOffsets = 0x0120
52
+ FreeByteCounts = 0x0121
53
+ GrayResponseUnit = 0x0122
54
+ GrayResponseCurve = 0x0123
55
+ T4Options = 0x0124
56
+ T6Options = 0x0125
57
+ ResolutionUnit = 0x0128
58
+ PageNumber = 0x0129
59
+ TransferFunction = 0x012D
60
+ Software = 0x0131
61
+ DateTime = 0x0132
62
+ Artist = 0x013B
63
+ HostComputer = 0x013C
64
+ Predictor = 0x013D
65
+ WhitePoint = 0x013E
66
+ PrimaryChromaticities = 0x013F
67
+ ColorMap = 0x0140
68
+ HalftoneHints = 0x0141
69
+ TileWidth = 0x0142
70
+ TileLength = 0x0143
71
+ TileOffsets = 0x0144
72
+ TileByteCounts = 0x0145
73
+ SubIFDs = 0x014A
74
+ InkSet = 0x014C
75
+ InkNames = 0x014D
76
+ NumberOfInks = 0x014E
77
+ DotRange = 0x0150
78
+ TargetPrinter = 0x0151
79
+ ExtraSamples = 0x0152
80
+ SampleFormat = 0x0153
81
+ SMinSampleValue = 0x0154
82
+ SMaxSampleValue = 0x0155
83
+ TransferRange = 0x0156
84
+ ClipPath = 0x0157
85
+ XClipPathUnits = 0x0158
86
+ YClipPathUnits = 0x0159
87
+ Indexed = 0x015A
88
+ JPEGTables = 0x015B
89
+ OPIProxy = 0x015F
90
+ JPEGProc = 0x0200
91
+ JpegIFOffset = 0x0201
92
+ JpegIFByteCount = 0x0202
93
+ JpegRestartInterval = 0x0203
94
+ JpegLosslessPredictors = 0x0205
95
+ JpegPointTransforms = 0x0206
96
+ JpegQTables = 0x0207
97
+ JpegDCTables = 0x0208
98
+ JpegACTables = 0x0209
99
+ YCbCrCoefficients = 0x0211
100
+ YCbCrSubSampling = 0x0212
101
+ YCbCrPositioning = 0x0213
102
+ ReferenceBlackWhite = 0x0214
103
+ XMLPacket = 0x02BC
104
+ RelatedImageFileFormat = 0x1000
105
+ RelatedImageWidth = 0x1001
106
+ RelatedImageLength = 0x1002
107
+ Rating = 0x4746
108
+ RatingPercent = 0x4749
109
+ ImageID = 0x800D
110
+ CFARepeatPatternDim = 0x828D
111
+ BatteryLevel = 0x828F
112
+ Copyright = 0x8298
113
+ ExposureTime = 0x829A
114
+ FNumber = 0x829D
115
+ IPTCNAA = 0x83BB
116
+ ImageResources = 0x8649
117
+ ExifOffset = 0x8769
118
+ InterColorProfile = 0x8773
119
+ ExposureProgram = 0x8822
120
+ SpectralSensitivity = 0x8824
121
+ GPSInfo = 0x8825
122
+ ISOSpeedRatings = 0x8827
123
+ OECF = 0x8828
124
+ Interlace = 0x8829
125
+ TimeZoneOffset = 0x882A
126
+ SelfTimerMode = 0x882B
127
+ SensitivityType = 0x8830
128
+ StandardOutputSensitivity = 0x8831
129
+ RecommendedExposureIndex = 0x8832
130
+ ISOSpeed = 0x8833
131
+ ISOSpeedLatitudeyyy = 0x8834
132
+ ISOSpeedLatitudezzz = 0x8835
133
+ ExifVersion = 0x9000
134
+ DateTimeOriginal = 0x9003
135
+ DateTimeDigitized = 0x9004
136
+ OffsetTime = 0x9010
137
+ OffsetTimeOriginal = 0x9011
138
+ OffsetTimeDigitized = 0x9012
139
+ ComponentsConfiguration = 0x9101
140
+ CompressedBitsPerPixel = 0x9102
141
+ ShutterSpeedValue = 0x9201
142
+ ApertureValue = 0x9202
143
+ BrightnessValue = 0x9203
144
+ ExposureBiasValue = 0x9204
145
+ MaxApertureValue = 0x9205
146
+ SubjectDistance = 0x9206
147
+ MeteringMode = 0x9207
148
+ LightSource = 0x9208
149
+ Flash = 0x9209
150
+ FocalLength = 0x920A
151
+ Noise = 0x920D
152
+ ImageNumber = 0x9211
153
+ SecurityClassification = 0x9212
154
+ ImageHistory = 0x9213
155
+ TIFFEPStandardID = 0x9216
156
+ MakerNote = 0x927C
157
+ UserComment = 0x9286
158
+ SubsecTime = 0x9290
159
+ SubsecTimeOriginal = 0x9291
160
+ SubsecTimeDigitized = 0x9292
161
+ AmbientTemperature = 0x9400
162
+ Humidity = 0x9401
163
+ Pressure = 0x9402
164
+ WaterDepth = 0x9403
165
+ Acceleration = 0x9404
166
+ CameraElevationAngle = 0x9405
167
+ XPTitle = 0x9C9B
168
+ XPComment = 0x9C9C
169
+ XPAuthor = 0x9C9D
170
+ XPKeywords = 0x9C9E
171
+ XPSubject = 0x9C9F
172
+ FlashPixVersion = 0xA000
173
+ ColorSpace = 0xA001
174
+ ExifImageWidth = 0xA002
175
+ ExifImageHeight = 0xA003
176
+ RelatedSoundFile = 0xA004
177
+ ExifInteroperabilityOffset = 0xA005
178
+ FlashEnergy = 0xA20B
179
+ SpatialFrequencyResponse = 0xA20C
180
+ FocalPlaneXResolution = 0xA20E
181
+ FocalPlaneYResolution = 0xA20F
182
+ FocalPlaneResolutionUnit = 0xA210
183
+ SubjectLocation = 0xA214
184
+ ExposureIndex = 0xA215
185
+ SensingMethod = 0xA217
186
+ FileSource = 0xA300
187
+ SceneType = 0xA301
188
+ CFAPattern = 0xA302
189
+ CustomRendered = 0xA401
190
+ ExposureMode = 0xA402
191
+ WhiteBalance = 0xA403
192
+ DigitalZoomRatio = 0xA404
193
+ FocalLengthIn35mmFilm = 0xA405
194
+ SceneCaptureType = 0xA406
195
+ GainControl = 0xA407
196
+ Contrast = 0xA408
197
+ Saturation = 0xA409
198
+ Sharpness = 0xA40A
199
+ DeviceSettingDescription = 0xA40B
200
+ SubjectDistanceRange = 0xA40C
201
+ ImageUniqueID = 0xA420
202
+ CameraOwnerName = 0xA430
203
+ BodySerialNumber = 0xA431
204
+ LensSpecification = 0xA432
205
+ LensMake = 0xA433
206
+ LensModel = 0xA434
207
+ LensSerialNumber = 0xA435
208
+ CompositeImage = 0xA460
209
+ CompositeImageCount = 0xA461
210
+ CompositeImageExposureTimes = 0xA462
211
+ Gamma = 0xA500
212
+ PrintImageMatching = 0xC4A5
213
+ DNGVersion = 0xC612
214
+ DNGBackwardVersion = 0xC613
215
+ UniqueCameraModel = 0xC614
216
+ LocalizedCameraModel = 0xC615
217
+ CFAPlaneColor = 0xC616
218
+ CFALayout = 0xC617
219
+ LinearizationTable = 0xC618
220
+ BlackLevelRepeatDim = 0xC619
221
+ BlackLevel = 0xC61A
222
+ BlackLevelDeltaH = 0xC61B
223
+ BlackLevelDeltaV = 0xC61C
224
+ WhiteLevel = 0xC61D
225
+ DefaultScale = 0xC61E
226
+ DefaultCropOrigin = 0xC61F
227
+ DefaultCropSize = 0xC620
228
+ ColorMatrix1 = 0xC621
229
+ ColorMatrix2 = 0xC622
230
+ CameraCalibration1 = 0xC623
231
+ CameraCalibration2 = 0xC624
232
+ ReductionMatrix1 = 0xC625
233
+ ReductionMatrix2 = 0xC626
234
+ AnalogBalance = 0xC627
235
+ AsShotNeutral = 0xC628
236
+ AsShotWhiteXY = 0xC629
237
+ BaselineExposure = 0xC62A
238
+ BaselineNoise = 0xC62B
239
+ BaselineSharpness = 0xC62C
240
+ BayerGreenSplit = 0xC62D
241
+ LinearResponseLimit = 0xC62E
242
+ CameraSerialNumber = 0xC62F
243
+ LensInfo = 0xC630
244
+ ChromaBlurRadius = 0xC631
245
+ AntiAliasStrength = 0xC632
246
+ ShadowScale = 0xC633
247
+ DNGPrivateData = 0xC634
248
+ MakerNoteSafety = 0xC635
249
+ CalibrationIlluminant1 = 0xC65A
250
+ CalibrationIlluminant2 = 0xC65B
251
+ BestQualityScale = 0xC65C
252
+ RawDataUniqueID = 0xC65D
253
+ OriginalRawFileName = 0xC68B
254
+ OriginalRawFileData = 0xC68C
255
+ ActiveArea = 0xC68D
256
+ MaskedAreas = 0xC68E
257
+ AsShotICCProfile = 0xC68F
258
+ AsShotPreProfileMatrix = 0xC690
259
+ CurrentICCProfile = 0xC691
260
+ CurrentPreProfileMatrix = 0xC692
261
+ ColorimetricReference = 0xC6BF
262
+ CameraCalibrationSignature = 0xC6F3
263
+ ProfileCalibrationSignature = 0xC6F4
264
+ AsShotProfileName = 0xC6F6
265
+ NoiseReductionApplied = 0xC6F7
266
+ ProfileName = 0xC6F8
267
+ ProfileHueSatMapDims = 0xC6F9
268
+ ProfileHueSatMapData1 = 0xC6FA
269
+ ProfileHueSatMapData2 = 0xC6FB
270
+ ProfileToneCurve = 0xC6FC
271
+ ProfileEmbedPolicy = 0xC6FD
272
+ ProfileCopyright = 0xC6FE
273
+ ForwardMatrix1 = 0xC714
274
+ ForwardMatrix2 = 0xC715
275
+ PreviewApplicationName = 0xC716
276
+ PreviewApplicationVersion = 0xC717
277
+ PreviewSettingsName = 0xC718
278
+ PreviewSettingsDigest = 0xC719
279
+ PreviewColorSpace = 0xC71A
280
+ PreviewDateTime = 0xC71B
281
+ RawImageDigest = 0xC71C
282
+ OriginalRawFileDigest = 0xC71D
283
+ SubTileBlockSize = 0xC71E
284
+ RowInterleaveFactor = 0xC71F
285
+ ProfileLookTableDims = 0xC725
286
+ ProfileLookTableData = 0xC726
287
+ OpcodeList1 = 0xC740
288
+ OpcodeList2 = 0xC741
289
+ OpcodeList3 = 0xC74E
290
+ NoiseProfile = 0xC761
291
+
292
+
293
+ """Maps EXIF tags to tag names."""
294
+ TAGS = {
295
+ **{i.value: i.name for i in Base},
296
+ 0x920C: "SpatialFrequencyResponse",
297
+ 0x9214: "SubjectLocation",
298
+ 0x9215: "ExposureIndex",
299
+ 0x828E: "CFAPattern",
300
+ 0x920B: "FlashEnergy",
301
+ 0x9216: "TIFF/EPStandardID",
302
+ }
303
+
304
+
305
+ class GPS(IntEnum):
306
+ GPSVersionID = 0
307
+ GPSLatitudeRef = 1
308
+ GPSLatitude = 2
309
+ GPSLongitudeRef = 3
310
+ GPSLongitude = 4
311
+ GPSAltitudeRef = 5
312
+ GPSAltitude = 6
313
+ GPSTimeStamp = 7
314
+ GPSSatellites = 8
315
+ GPSStatus = 9
316
+ GPSMeasureMode = 10
317
+ GPSDOP = 11
318
+ GPSSpeedRef = 12
319
+ GPSSpeed = 13
320
+ GPSTrackRef = 14
321
+ GPSTrack = 15
322
+ GPSImgDirectionRef = 16
323
+ GPSImgDirection = 17
324
+ GPSMapDatum = 18
325
+ GPSDestLatitudeRef = 19
326
+ GPSDestLatitude = 20
327
+ GPSDestLongitudeRef = 21
328
+ GPSDestLongitude = 22
329
+ GPSDestBearingRef = 23
330
+ GPSDestBearing = 24
331
+ GPSDestDistanceRef = 25
332
+ GPSDestDistance = 26
333
+ GPSProcessingMethod = 27
334
+ GPSAreaInformation = 28
335
+ GPSDateStamp = 29
336
+ GPSDifferential = 30
337
+ GPSHPositioningError = 31
338
+
339
+
340
+ """Maps EXIF GPS tags to tag names."""
341
+ GPSTAGS = {i.value: i.name for i in GPS}
342
+
343
+
344
+ class Interop(IntEnum):
345
+ InteropIndex = 1
346
+ InteropVersion = 2
347
+ RelatedImageFileFormat = 4096
348
+ RelatedImageWidth = 4097
349
+ RleatedImageHeight = 4098
350
+
351
+
352
+ class IFD(IntEnum):
353
+ Exif = 34665
354
+ GPSInfo = 34853
355
+ Makernote = 37500
356
+ Interop = 40965
357
+ IFD1 = -1
358
+
359
+
360
+ class LightSource(IntEnum):
361
+ Unknown = 0
362
+ Daylight = 1
363
+ Fluorescent = 2
364
+ Tungsten = 3
365
+ Flash = 4
366
+ Fine = 9
367
+ Cloudy = 10
368
+ Shade = 11
369
+ DaylightFluorescent = 12
370
+ DayWhiteFluorescent = 13
371
+ CoolWhiteFluorescent = 14
372
+ WhiteFluorescent = 15
373
+ StandardLightA = 17
374
+ StandardLightB = 18
375
+ StandardLightC = 19
376
+ D55 = 20
377
+ D65 = 21
378
+ D75 = 22
379
+ D50 = 23
380
+ ISO = 24
381
+ Other = 255
.venv/Lib/site-packages/PIL/FitsImagePlugin.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library
3
+ # $Id$
4
+ #
5
+ # FITS file handling
6
+ #
7
+ # Copyright (c) 1998-2003 by Fredrik Lundh
8
+ #
9
+ # See the README file for information on usage and redistribution.
10
+ #
11
+ from __future__ import annotations
12
+
13
+ import gzip
14
+ import math
15
+
16
+ from . import Image, ImageFile
17
+
18
+
19
+ def _accept(prefix: bytes) -> bool:
20
+ return prefix[:6] == b"SIMPLE"
21
+
22
+
23
+ class FitsImageFile(ImageFile.ImageFile):
24
+ format = "FITS"
25
+ format_description = "FITS"
26
+
27
+ def _open(self) -> None:
28
+ assert self.fp is not None
29
+
30
+ headers: dict[bytes, bytes] = {}
31
+ header_in_progress = False
32
+ decoder_name = ""
33
+ while True:
34
+ header = self.fp.read(80)
35
+ if not header:
36
+ msg = "Truncated FITS file"
37
+ raise OSError(msg)
38
+ keyword = header[:8].strip()
39
+ if keyword in (b"SIMPLE", b"XTENSION"):
40
+ header_in_progress = True
41
+ elif headers and not header_in_progress:
42
+ # This is now a data unit
43
+ break
44
+ elif keyword == b"END":
45
+ # Seek to the end of the header unit
46
+ self.fp.seek(math.ceil(self.fp.tell() / 2880) * 2880)
47
+ if not decoder_name:
48
+ decoder_name, offset, args = self._parse_headers(headers)
49
+
50
+ header_in_progress = False
51
+ continue
52
+
53
+ if decoder_name:
54
+ # Keep going to read past the headers
55
+ continue
56
+
57
+ value = header[8:].split(b"/")[0].strip()
58
+ if value.startswith(b"="):
59
+ value = value[1:].strip()
60
+ if not headers and (not _accept(keyword) or value != b"T"):
61
+ msg = "Not a FITS file"
62
+ raise SyntaxError(msg)
63
+ headers[keyword] = value
64
+
65
+ if not decoder_name:
66
+ msg = "No image data"
67
+ raise ValueError(msg)
68
+
69
+ offset += self.fp.tell() - 80
70
+ self.tile = [(decoder_name, (0, 0) + self.size, offset, args)]
71
+
72
+ def _get_size(
73
+ self, headers: dict[bytes, bytes], prefix: bytes
74
+ ) -> tuple[int, int] | None:
75
+ naxis = int(headers[prefix + b"NAXIS"])
76
+ if naxis == 0:
77
+ return None
78
+
79
+ if naxis == 1:
80
+ return 1, int(headers[prefix + b"NAXIS1"])
81
+ else:
82
+ return int(headers[prefix + b"NAXIS1"]), int(headers[prefix + b"NAXIS2"])
83
+
84
+ def _parse_headers(
85
+ self, headers: dict[bytes, bytes]
86
+ ) -> tuple[str, int, tuple[str | int, ...]]:
87
+ prefix = b""
88
+ decoder_name = "raw"
89
+ offset = 0
90
+ if (
91
+ headers.get(b"XTENSION") == b"'BINTABLE'"
92
+ and headers.get(b"ZIMAGE") == b"T"
93
+ and headers[b"ZCMPTYPE"] == b"'GZIP_1 '"
94
+ ):
95
+ no_prefix_size = self._get_size(headers, prefix) or (0, 0)
96
+ number_of_bits = int(headers[b"BITPIX"])
97
+ offset = no_prefix_size[0] * no_prefix_size[1] * (number_of_bits // 8)
98
+
99
+ prefix = b"Z"
100
+ decoder_name = "fits_gzip"
101
+
102
+ size = self._get_size(headers, prefix)
103
+ if not size:
104
+ return "", 0, ()
105
+
106
+ self._size = size
107
+
108
+ number_of_bits = int(headers[prefix + b"BITPIX"])
109
+ if number_of_bits == 8:
110
+ self._mode = "L"
111
+ elif number_of_bits == 16:
112
+ self._mode = "I;16"
113
+ elif number_of_bits == 32:
114
+ self._mode = "I"
115
+ elif number_of_bits in (-32, -64):
116
+ self._mode = "F"
117
+
118
+ args = (self.mode, 0, -1) if decoder_name == "raw" else (number_of_bits,)
119
+ return decoder_name, offset, args
120
+
121
+
122
+ class FitsGzipDecoder(ImageFile.PyDecoder):
123
+ _pulls_fd = True
124
+
125
+ def decode(self, buffer):
126
+ assert self.fd is not None
127
+ value = gzip.decompress(self.fd.read())
128
+
129
+ rows = []
130
+ offset = 0
131
+ number_of_bits = min(self.args[0] // 8, 4)
132
+ for y in range(self.state.ysize):
133
+ row = bytearray()
134
+ for x in range(self.state.xsize):
135
+ row += value[offset + (4 - number_of_bits) : offset + 4]
136
+ offset += 4
137
+ rows.append(row)
138
+ self.set_as_raw(bytes([pixel for row in rows[::-1] for pixel in row]))
139
+ return -1, 0
140
+
141
+
142
+ # --------------------------------------------------------------------
143
+ # Registry
144
+
145
+ Image.register_open(FitsImageFile.format, FitsImageFile, _accept)
146
+ Image.register_decoder("fits_gzip", FitsGzipDecoder)
147
+
148
+ Image.register_extensions(FitsImageFile.format, [".fit", ".fits"])
.venv/Lib/site-packages/PIL/FliImagePlugin.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # FLI/FLC file handling.
6
+ #
7
+ # History:
8
+ # 95-09-01 fl Created
9
+ # 97-01-03 fl Fixed parser, setup decoder tile
10
+ # 98-07-15 fl Renamed offset attribute to avoid name clash
11
+ #
12
+ # Copyright (c) Secret Labs AB 1997-98.
13
+ # Copyright (c) Fredrik Lundh 1995-97.
14
+ #
15
+ # See the README file for information on usage and redistribution.
16
+ #
17
+ from __future__ import annotations
18
+
19
+ import os
20
+
21
+ from . import Image, ImageFile, ImagePalette
22
+ from ._binary import i16le as i16
23
+ from ._binary import i32le as i32
24
+ from ._binary import o8
25
+
26
+ #
27
+ # decoder
28
+
29
+
30
+ def _accept(prefix):
31
+ return (
32
+ len(prefix) >= 6
33
+ and i16(prefix, 4) in [0xAF11, 0xAF12]
34
+ and i16(prefix, 14) in [0, 3] # flags
35
+ )
36
+
37
+
38
+ ##
39
+ # Image plugin for the FLI/FLC animation format. Use the <b>seek</b>
40
+ # method to load individual frames.
41
+
42
+
43
+ class FliImageFile(ImageFile.ImageFile):
44
+ format = "FLI"
45
+ format_description = "Autodesk FLI/FLC Animation"
46
+ _close_exclusive_fp_after_loading = False
47
+
48
+ def _open(self):
49
+ # HEAD
50
+ s = self.fp.read(128)
51
+ if not (_accept(s) and s[20:22] == b"\x00\x00"):
52
+ msg = "not an FLI/FLC file"
53
+ raise SyntaxError(msg)
54
+
55
+ # frames
56
+ self.n_frames = i16(s, 6)
57
+ self.is_animated = self.n_frames > 1
58
+
59
+ # image characteristics
60
+ self._mode = "P"
61
+ self._size = i16(s, 8), i16(s, 10)
62
+
63
+ # animation speed
64
+ duration = i32(s, 16)
65
+ magic = i16(s, 4)
66
+ if magic == 0xAF11:
67
+ duration = (duration * 1000) // 70
68
+ self.info["duration"] = duration
69
+
70
+ # look for palette
71
+ palette = [(a, a, a) for a in range(256)]
72
+
73
+ s = self.fp.read(16)
74
+
75
+ self.__offset = 128
76
+
77
+ if i16(s, 4) == 0xF100:
78
+ # prefix chunk; ignore it
79
+ self.__offset = self.__offset + i32(s)
80
+ self.fp.seek(self.__offset)
81
+ s = self.fp.read(16)
82
+
83
+ if i16(s, 4) == 0xF1FA:
84
+ # look for palette chunk
85
+ number_of_subchunks = i16(s, 6)
86
+ chunk_size = None
87
+ for _ in range(number_of_subchunks):
88
+ if chunk_size is not None:
89
+ self.fp.seek(chunk_size - 6, os.SEEK_CUR)
90
+ s = self.fp.read(6)
91
+ chunk_type = i16(s, 4)
92
+ if chunk_type in (4, 11):
93
+ self._palette(palette, 2 if chunk_type == 11 else 0)
94
+ break
95
+ chunk_size = i32(s)
96
+ if not chunk_size:
97
+ break
98
+
99
+ palette = [o8(r) + o8(g) + o8(b) for (r, g, b) in palette]
100
+ self.palette = ImagePalette.raw("RGB", b"".join(palette))
101
+
102
+ # set things up to decode first frame
103
+ self.__frame = -1
104
+ self._fp = self.fp
105
+ self.__rewind = self.fp.tell()
106
+ self.seek(0)
107
+
108
+ def _palette(self, palette, shift):
109
+ # load palette
110
+
111
+ i = 0
112
+ for e in range(i16(self.fp.read(2))):
113
+ s = self.fp.read(2)
114
+ i = i + s[0]
115
+ n = s[1]
116
+ if n == 0:
117
+ n = 256
118
+ s = self.fp.read(n * 3)
119
+ for n in range(0, len(s), 3):
120
+ r = s[n] << shift
121
+ g = s[n + 1] << shift
122
+ b = s[n + 2] << shift
123
+ palette[i] = (r, g, b)
124
+ i += 1
125
+
126
+ def seek(self, frame):
127
+ if not self._seek_check(frame):
128
+ return
129
+ if frame < self.__frame:
130
+ self._seek(0)
131
+
132
+ for f in range(self.__frame + 1, frame + 1):
133
+ self._seek(f)
134
+
135
+ def _seek(self, frame):
136
+ if frame == 0:
137
+ self.__frame = -1
138
+ self._fp.seek(self.__rewind)
139
+ self.__offset = 128
140
+ else:
141
+ # ensure that the previous frame was loaded
142
+ self.load()
143
+
144
+ if frame != self.__frame + 1:
145
+ msg = f"cannot seek to frame {frame}"
146
+ raise ValueError(msg)
147
+ self.__frame = frame
148
+
149
+ # move to next frame
150
+ self.fp = self._fp
151
+ self.fp.seek(self.__offset)
152
+
153
+ s = self.fp.read(4)
154
+ if not s:
155
+ msg = "missing frame size"
156
+ raise EOFError(msg)
157
+
158
+ framesize = i32(s)
159
+
160
+ self.decodermaxblock = framesize
161
+ self.tile = [("fli", (0, 0) + self.size, self.__offset, None)]
162
+
163
+ self.__offset += framesize
164
+
165
+ def tell(self):
166
+ return self.__frame
167
+
168
+
169
+ #
170
+ # registry
171
+
172
+ Image.register_open(FliImageFile.format, FliImageFile, _accept)
173
+
174
+ Image.register_extensions(FliImageFile.format, [".fli", ".flc"])
.venv/Lib/site-packages/PIL/FontFile.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library
3
+ # $Id$
4
+ #
5
+ # base class for raster font file parsers
6
+ #
7
+ # history:
8
+ # 1997-06-05 fl created
9
+ # 1997-08-19 fl restrict image width
10
+ #
11
+ # Copyright (c) 1997-1998 by Secret Labs AB
12
+ # Copyright (c) 1997-1998 by Fredrik Lundh
13
+ #
14
+ # See the README file for information on usage and redistribution.
15
+ #
16
+ from __future__ import annotations
17
+
18
+ import os
19
+ from typing import BinaryIO
20
+
21
+ from . import Image, _binary
22
+
23
+ WIDTH = 800
24
+
25
+
26
+ def puti16(
27
+ fp: BinaryIO, values: tuple[int, int, int, int, int, int, int, int, int, int]
28
+ ) -> None:
29
+ """Write network order (big-endian) 16-bit sequence"""
30
+ for v in values:
31
+ if v < 0:
32
+ v += 65536
33
+ fp.write(_binary.o16be(v))
34
+
35
+
36
+ class FontFile:
37
+ """Base class for raster font file handlers."""
38
+
39
+ bitmap: Image.Image | None = None
40
+
41
+ def __init__(self) -> None:
42
+ self.info: dict[bytes, bytes | int] = {}
43
+ self.glyph: list[
44
+ tuple[
45
+ tuple[int, int],
46
+ tuple[int, int, int, int],
47
+ tuple[int, int, int, int],
48
+ Image.Image,
49
+ ]
50
+ | None
51
+ ] = [None] * 256
52
+
53
+ def __getitem__(self, ix: int) -> (
54
+ tuple[
55
+ tuple[int, int],
56
+ tuple[int, int, int, int],
57
+ tuple[int, int, int, int],
58
+ Image.Image,
59
+ ]
60
+ | None
61
+ ):
62
+ return self.glyph[ix]
63
+
64
+ def compile(self) -> None:
65
+ """Create metrics and bitmap"""
66
+
67
+ if self.bitmap:
68
+ return
69
+
70
+ # create bitmap large enough to hold all data
71
+ h = w = maxwidth = 0
72
+ lines = 1
73
+ for glyph in self.glyph:
74
+ if glyph:
75
+ d, dst, src, im = glyph
76
+ h = max(h, src[3] - src[1])
77
+ w = w + (src[2] - src[0])
78
+ if w > WIDTH:
79
+ lines += 1
80
+ w = src[2] - src[0]
81
+ maxwidth = max(maxwidth, w)
82
+
83
+ xsize = maxwidth
84
+ ysize = lines * h
85
+
86
+ if xsize == 0 and ysize == 0:
87
+ return
88
+
89
+ self.ysize = h
90
+
91
+ # paste glyphs into bitmap
92
+ self.bitmap = Image.new("1", (xsize, ysize))
93
+ self.metrics: list[
94
+ tuple[tuple[int, int], tuple[int, int, int, int], tuple[int, int, int, int]]
95
+ | None
96
+ ] = [None] * 256
97
+ x = y = 0
98
+ for i in range(256):
99
+ glyph = self[i]
100
+ if glyph:
101
+ d, dst, src, im = glyph
102
+ xx = src[2] - src[0]
103
+ x0, y0 = x, y
104
+ x = x + xx
105
+ if x > WIDTH:
106
+ x, y = 0, y + h
107
+ x0, y0 = x, y
108
+ x = xx
109
+ s = src[0] + x0, src[1] + y0, src[2] + x0, src[3] + y0
110
+ self.bitmap.paste(im.crop(src), s)
111
+ self.metrics[i] = d, dst, s
112
+
113
+ def save(self, filename: str) -> None:
114
+ """Save font"""
115
+
116
+ self.compile()
117
+
118
+ # font data
119
+ if not self.bitmap:
120
+ msg = "No bitmap created"
121
+ raise ValueError(msg)
122
+ self.bitmap.save(os.path.splitext(filename)[0] + ".pbm", "PNG")
123
+
124
+ # font metrics
125
+ with open(os.path.splitext(filename)[0] + ".pil", "wb") as fp:
126
+ fp.write(b"PILfont\n")
127
+ fp.write(f";;;;;;{self.ysize};\n".encode("ascii")) # HACK!!!
128
+ fp.write(b"DATA\n")
129
+ for id in range(256):
130
+ m = self.metrics[id]
131
+ if not m:
132
+ puti16(fp, (0,) * 10)
133
+ else:
134
+ puti16(fp, m[0] + m[1] + m[2])
.venv/Lib/site-packages/PIL/FpxImagePlugin.py ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # THIS IS WORK IN PROGRESS
3
+ #
4
+ # The Python Imaging Library.
5
+ # $Id$
6
+ #
7
+ # FlashPix support for PIL
8
+ #
9
+ # History:
10
+ # 97-01-25 fl Created (reads uncompressed RGB images only)
11
+ #
12
+ # Copyright (c) Secret Labs AB 1997.
13
+ # Copyright (c) Fredrik Lundh 1997.
14
+ #
15
+ # See the README file for information on usage and redistribution.
16
+ #
17
+ from __future__ import annotations
18
+
19
+ import olefile
20
+
21
+ from . import Image, ImageFile
22
+ from ._binary import i32le as i32
23
+
24
+ # we map from colour field tuples to (mode, rawmode) descriptors
25
+ MODES = {
26
+ # opacity
27
+ (0x00007FFE,): ("A", "L"),
28
+ # monochrome
29
+ (0x00010000,): ("L", "L"),
30
+ (0x00018000, 0x00017FFE): ("RGBA", "LA"),
31
+ # photo YCC
32
+ (0x00020000, 0x00020001, 0x00020002): ("RGB", "YCC;P"),
33
+ (0x00028000, 0x00028001, 0x00028002, 0x00027FFE): ("RGBA", "YCCA;P"),
34
+ # standard RGB (NIFRGB)
35
+ (0x00030000, 0x00030001, 0x00030002): ("RGB", "RGB"),
36
+ (0x00038000, 0x00038001, 0x00038002, 0x00037FFE): ("RGBA", "RGBA"),
37
+ }
38
+
39
+
40
+ #
41
+ # --------------------------------------------------------------------
42
+
43
+
44
+ def _accept(prefix):
45
+ return prefix[:8] == olefile.MAGIC
46
+
47
+
48
+ ##
49
+ # Image plugin for the FlashPix images.
50
+
51
+
52
+ class FpxImageFile(ImageFile.ImageFile):
53
+ format = "FPX"
54
+ format_description = "FlashPix"
55
+
56
+ def _open(self):
57
+ #
58
+ # read the OLE directory and see if this is a likely
59
+ # to be a FlashPix file
60
+
61
+ try:
62
+ self.ole = olefile.OleFileIO(self.fp)
63
+ except OSError as e:
64
+ msg = "not an FPX file; invalid OLE file"
65
+ raise SyntaxError(msg) from e
66
+
67
+ if self.ole.root.clsid != "56616700-C154-11CE-8553-00AA00A1F95B":
68
+ msg = "not an FPX file; bad root CLSID"
69
+ raise SyntaxError(msg)
70
+
71
+ self._open_index(1)
72
+
73
+ def _open_index(self, index=1):
74
+ #
75
+ # get the Image Contents Property Set
76
+
77
+ prop = self.ole.getproperties(
78
+ [f"Data Object Store {index:06d}", "\005Image Contents"]
79
+ )
80
+
81
+ # size (highest resolution)
82
+
83
+ self._size = prop[0x1000002], prop[0x1000003]
84
+
85
+ size = max(self.size)
86
+ i = 1
87
+ while size > 64:
88
+ size = size / 2
89
+ i += 1
90
+ self.maxid = i - 1
91
+
92
+ # mode. instead of using a single field for this, flashpix
93
+ # requires you to specify the mode for each channel in each
94
+ # resolution subimage, and leaves it to the decoder to make
95
+ # sure that they all match. for now, we'll cheat and assume
96
+ # that this is always the case.
97
+
98
+ id = self.maxid << 16
99
+
100
+ s = prop[0x2000002 | id]
101
+
102
+ bands = i32(s, 4)
103
+ if bands > 4:
104
+ msg = "Invalid number of bands"
105
+ raise OSError(msg)
106
+
107
+ # note: for now, we ignore the "uncalibrated" flag
108
+ colors = tuple(i32(s, 8 + i * 4) & 0x7FFFFFFF for i in range(bands))
109
+
110
+ self._mode, self.rawmode = MODES[colors]
111
+
112
+ # load JPEG tables, if any
113
+ self.jpeg = {}
114
+ for i in range(256):
115
+ id = 0x3000001 | (i << 16)
116
+ if id in prop:
117
+ self.jpeg[i] = prop[id]
118
+
119
+ self._open_subimage(1, self.maxid)
120
+
121
+ def _open_subimage(self, index=1, subimage=0):
122
+ #
123
+ # setup tile descriptors for a given subimage
124
+
125
+ stream = [
126
+ f"Data Object Store {index:06d}",
127
+ f"Resolution {subimage:04d}",
128
+ "Subimage 0000 Header",
129
+ ]
130
+
131
+ fp = self.ole.openstream(stream)
132
+
133
+ # skip prefix
134
+ fp.read(28)
135
+
136
+ # header stream
137
+ s = fp.read(36)
138
+
139
+ size = i32(s, 4), i32(s, 8)
140
+ # tilecount = i32(s, 12)
141
+ tilesize = i32(s, 16), i32(s, 20)
142
+ # channels = i32(s, 24)
143
+ offset = i32(s, 28)
144
+ length = i32(s, 32)
145
+
146
+ if size != self.size:
147
+ msg = "subimage mismatch"
148
+ raise OSError(msg)
149
+
150
+ # get tile descriptors
151
+ fp.seek(28 + offset)
152
+ s = fp.read(i32(s, 12) * length)
153
+
154
+ x = y = 0
155
+ xsize, ysize = size
156
+ xtile, ytile = tilesize
157
+ self.tile = []
158
+
159
+ for i in range(0, len(s), length):
160
+ x1 = min(xsize, x + xtile)
161
+ y1 = min(ysize, y + ytile)
162
+
163
+ compression = i32(s, i + 8)
164
+
165
+ if compression == 0:
166
+ self.tile.append(
167
+ (
168
+ "raw",
169
+ (x, y, x1, y1),
170
+ i32(s, i) + 28,
171
+ (self.rawmode,),
172
+ )
173
+ )
174
+
175
+ elif compression == 1:
176
+ # FIXME: the fill decoder is not implemented
177
+ self.tile.append(
178
+ (
179
+ "fill",
180
+ (x, y, x1, y1),
181
+ i32(s, i) + 28,
182
+ (self.rawmode, s[12:16]),
183
+ )
184
+ )
185
+
186
+ elif compression == 2:
187
+ internal_color_conversion = s[14]
188
+ jpeg_tables = s[15]
189
+ rawmode = self.rawmode
190
+
191
+ if internal_color_conversion:
192
+ # The image is stored as usual (usually YCbCr).
193
+ if rawmode == "RGBA":
194
+ # For "RGBA", data is stored as YCbCrA based on
195
+ # negative RGB. The following trick works around
196
+ # this problem :
197
+ jpegmode, rawmode = "YCbCrK", "CMYK"
198
+ else:
199
+ jpegmode = None # let the decoder decide
200
+
201
+ else:
202
+ # The image is stored as defined by rawmode
203
+ jpegmode = rawmode
204
+
205
+ self.tile.append(
206
+ (
207
+ "jpeg",
208
+ (x, y, x1, y1),
209
+ i32(s, i) + 28,
210
+ (rawmode, jpegmode),
211
+ )
212
+ )
213
+
214
+ # FIXME: jpeg tables are tile dependent; the prefix
215
+ # data must be placed in the tile descriptor itself!
216
+
217
+ if jpeg_tables:
218
+ self.tile_prefix = self.jpeg[jpeg_tables]
219
+
220
+ else:
221
+ msg = "unknown/invalid compression"
222
+ raise OSError(msg)
223
+
224
+ x = x + xtile
225
+ if x >= xsize:
226
+ x, y = 0, y + ytile
227
+ if y >= ysize:
228
+ break # isn't really required
229
+
230
+ self.stream = stream
231
+ self._fp = self.fp
232
+ self.fp = None
233
+
234
+ def load(self):
235
+ if not self.fp:
236
+ self.fp = self.ole.openstream(self.stream[:2] + ["Subimage 0000 Data"])
237
+
238
+ return ImageFile.ImageFile.load(self)
239
+
240
+ def close(self):
241
+ self.ole.close()
242
+ super().close()
243
+
244
+ def __exit__(self, *args):
245
+ self.ole.close()
246
+ super().__exit__()
247
+
248
+
249
+ #
250
+ # --------------------------------------------------------------------
251
+
252
+
253
+ Image.register_open(FpxImageFile.format, FpxImageFile, _accept)
254
+
255
+ Image.register_extension(FpxImageFile.format, ".fpx")
.venv/Lib/site-packages/PIL/FtexImagePlugin.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A Pillow loader for .ftc and .ftu files (FTEX)
3
+ Jerome Leclanche <jerome@leclan.ch>
4
+
5
+ The contents of this file are hereby released in the public domain (CC0)
6
+ Full text of the CC0 license:
7
+ https://creativecommons.org/publicdomain/zero/1.0/
8
+
9
+ Independence War 2: Edge Of Chaos - Texture File Format - 16 October 2001
10
+
11
+ The textures used for 3D objects in Independence War 2: Edge Of Chaos are in a
12
+ packed custom format called FTEX. This file format uses file extensions FTC
13
+ and FTU.
14
+ * FTC files are compressed textures (using standard texture compression).
15
+ * FTU files are not compressed.
16
+ Texture File Format
17
+ The FTC and FTU texture files both use the same format. This
18
+ has the following structure:
19
+ {header}
20
+ {format_directory}
21
+ {data}
22
+ Where:
23
+ {header} = {
24
+ u32:magic,
25
+ u32:version,
26
+ u32:width,
27
+ u32:height,
28
+ u32:mipmap_count,
29
+ u32:format_count
30
+ }
31
+
32
+ * The "magic" number is "FTEX".
33
+ * "width" and "height" are the dimensions of the texture.
34
+ * "mipmap_count" is the number of mipmaps in the texture.
35
+ * "format_count" is the number of texture formats (different versions of the
36
+ same texture) in this file.
37
+
38
+ {format_directory} = format_count * { u32:format, u32:where }
39
+
40
+ The format value is 0 for DXT1 compressed textures and 1 for 24-bit RGB
41
+ uncompressed textures.
42
+ The texture data for a format starts at the position "where" in the file.
43
+
44
+ Each set of texture data in the file has the following structure:
45
+ {data} = format_count * { u32:mipmap_size, mipmap_size * { u8 } }
46
+ * "mipmap_size" is the number of bytes in that mip level. For compressed
47
+ textures this is the size of the texture data compressed with DXT1. For 24 bit
48
+ uncompressed textures, this is 3 * width * height. Following this are the image
49
+ bytes for that mipmap level.
50
+
51
+ Note: All data is stored in little-Endian (Intel) byte order.
52
+ """
53
+
54
+ from __future__ import annotations
55
+
56
+ import struct
57
+ from enum import IntEnum
58
+ from io import BytesIO
59
+
60
+ from . import Image, ImageFile
61
+
62
+ MAGIC = b"FTEX"
63
+
64
+
65
+ class Format(IntEnum):
66
+ DXT1 = 0
67
+ UNCOMPRESSED = 1
68
+
69
+
70
+ class FtexImageFile(ImageFile.ImageFile):
71
+ format = "FTEX"
72
+ format_description = "Texture File Format (IW2:EOC)"
73
+
74
+ def _open(self):
75
+ if not _accept(self.fp.read(4)):
76
+ msg = "not an FTEX file"
77
+ raise SyntaxError(msg)
78
+ struct.unpack("<i", self.fp.read(4)) # version
79
+ self._size = struct.unpack("<2i", self.fp.read(8))
80
+ mipmap_count, format_count = struct.unpack("<2i", self.fp.read(8))
81
+
82
+ self._mode = "RGB"
83
+
84
+ # Only support single-format files.
85
+ # I don't know of any multi-format file.
86
+ assert format_count == 1
87
+
88
+ format, where = struct.unpack("<2i", self.fp.read(8))
89
+ self.fp.seek(where)
90
+ (mipmap_size,) = struct.unpack("<i", self.fp.read(4))
91
+
92
+ data = self.fp.read(mipmap_size)
93
+
94
+ if format == Format.DXT1:
95
+ self._mode = "RGBA"
96
+ self.tile = [("bcn", (0, 0) + self.size, 0, 1)]
97
+ elif format == Format.UNCOMPRESSED:
98
+ self.tile = [("raw", (0, 0) + self.size, 0, ("RGB", 0, 1))]
99
+ else:
100
+ msg = f"Invalid texture compression format: {repr(format)}"
101
+ raise ValueError(msg)
102
+
103
+ self.fp.close()
104
+ self.fp = BytesIO(data)
105
+
106
+ def load_seek(self, pos):
107
+ pass
108
+
109
+
110
+ def _accept(prefix):
111
+ return prefix[:4] == MAGIC
112
+
113
+
114
+ Image.register_open(FtexImageFile.format, FtexImageFile, _accept)
115
+ Image.register_extensions(FtexImageFile.format, [".ftc", ".ftu"])
.venv/Lib/site-packages/PIL/GbrImagePlugin.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library
3
+ #
4
+ # load a GIMP brush file
5
+ #
6
+ # History:
7
+ # 96-03-14 fl Created
8
+ # 16-01-08 es Version 2
9
+ #
10
+ # Copyright (c) Secret Labs AB 1997.
11
+ # Copyright (c) Fredrik Lundh 1996.
12
+ # Copyright (c) Eric Soroos 2016.
13
+ #
14
+ # See the README file for information on usage and redistribution.
15
+ #
16
+ #
17
+ # See https://github.com/GNOME/gimp/blob/mainline/devel-docs/gbr.txt for
18
+ # format documentation.
19
+ #
20
+ # This code Interprets version 1 and 2 .gbr files.
21
+ # Version 1 files are obsolete, and should not be used for new
22
+ # brushes.
23
+ # Version 2 files are saved by GIMP v2.8 (at least)
24
+ # Version 3 files have a format specifier of 18 for 16bit floats in
25
+ # the color depth field. This is currently unsupported by Pillow.
26
+ from __future__ import annotations
27
+
28
+ from . import Image, ImageFile
29
+ from ._binary import i32be as i32
30
+
31
+
32
+ def _accept(prefix):
33
+ return len(prefix) >= 8 and i32(prefix, 0) >= 20 and i32(prefix, 4) in (1, 2)
34
+
35
+
36
+ ##
37
+ # Image plugin for the GIMP brush format.
38
+
39
+
40
+ class GbrImageFile(ImageFile.ImageFile):
41
+ format = "GBR"
42
+ format_description = "GIMP brush file"
43
+
44
+ def _open(self):
45
+ header_size = i32(self.fp.read(4))
46
+ if header_size < 20:
47
+ msg = "not a GIMP brush"
48
+ raise SyntaxError(msg)
49
+ version = i32(self.fp.read(4))
50
+ if version not in (1, 2):
51
+ msg = f"Unsupported GIMP brush version: {version}"
52
+ raise SyntaxError(msg)
53
+
54
+ width = i32(self.fp.read(4))
55
+ height = i32(self.fp.read(4))
56
+ color_depth = i32(self.fp.read(4))
57
+ if width <= 0 or height <= 0:
58
+ msg = "not a GIMP brush"
59
+ raise SyntaxError(msg)
60
+ if color_depth not in (1, 4):
61
+ msg = f"Unsupported GIMP brush color depth: {color_depth}"
62
+ raise SyntaxError(msg)
63
+
64
+ if version == 1:
65
+ comment_length = header_size - 20
66
+ else:
67
+ comment_length = header_size - 28
68
+ magic_number = self.fp.read(4)
69
+ if magic_number != b"GIMP":
70
+ msg = "not a GIMP brush, bad magic number"
71
+ raise SyntaxError(msg)
72
+ self.info["spacing"] = i32(self.fp.read(4))
73
+
74
+ comment = self.fp.read(comment_length)[:-1]
75
+
76
+ if color_depth == 1:
77
+ self._mode = "L"
78
+ else:
79
+ self._mode = "RGBA"
80
+
81
+ self._size = width, height
82
+
83
+ self.info["comment"] = comment
84
+
85
+ # Image might not be small
86
+ Image._decompression_bomb_check(self.size)
87
+
88
+ # Data is an uncompressed block of w * h * bytes/pixel
89
+ self._data_size = width * height * color_depth
90
+
91
+ def load(self):
92
+ if not self.im:
93
+ self.im = Image.core.new(self.mode, self.size)
94
+ self.frombytes(self.fp.read(self._data_size))
95
+ return Image.Image.load(self)
96
+
97
+
98
+ #
99
+ # registry
100
+
101
+
102
+ Image.register_open(GbrImageFile.format, GbrImageFile, _accept)
103
+ Image.register_extension(GbrImageFile.format, ".gbr")
.venv/Lib/site-packages/PIL/GdImageFile.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # GD file handling
6
+ #
7
+ # History:
8
+ # 1996-04-12 fl Created
9
+ #
10
+ # Copyright (c) 1997 by Secret Labs AB.
11
+ # Copyright (c) 1996 by Fredrik Lundh.
12
+ #
13
+ # See the README file for information on usage and redistribution.
14
+ #
15
+
16
+
17
+ """
18
+ .. note::
19
+ This format cannot be automatically recognized, so the
20
+ class is not registered for use with :py:func:`PIL.Image.open()`. To open a
21
+ gd file, use the :py:func:`PIL.GdImageFile.open()` function instead.
22
+
23
+ .. warning::
24
+ THE GD FORMAT IS NOT DESIGNED FOR DATA INTERCHANGE. This
25
+ implementation is provided for convenience and demonstrational
26
+ purposes only.
27
+ """
28
+ from __future__ import annotations
29
+
30
+ from typing import IO
31
+
32
+ from . import ImageFile, ImagePalette, UnidentifiedImageError
33
+ from ._binary import i16be as i16
34
+ from ._binary import i32be as i32
35
+ from ._typing import StrOrBytesPath
36
+
37
+
38
+ class GdImageFile(ImageFile.ImageFile):
39
+ """
40
+ Image plugin for the GD uncompressed format. Note that this format
41
+ is not supported by the standard :py:func:`PIL.Image.open()` function. To use
42
+ this plugin, you have to import the :py:mod:`PIL.GdImageFile` module and
43
+ use the :py:func:`PIL.GdImageFile.open()` function.
44
+ """
45
+
46
+ format = "GD"
47
+ format_description = "GD uncompressed images"
48
+
49
+ def _open(self) -> None:
50
+ # Header
51
+ assert self.fp is not None
52
+
53
+ s = self.fp.read(1037)
54
+
55
+ if i16(s) not in [65534, 65535]:
56
+ msg = "Not a valid GD 2.x .gd file"
57
+ raise SyntaxError(msg)
58
+
59
+ self._mode = "L" # FIXME: "P"
60
+ self._size = i16(s, 2), i16(s, 4)
61
+
62
+ true_color = s[6]
63
+ true_color_offset = 2 if true_color else 0
64
+
65
+ # transparency index
66
+ tindex = i32(s, 7 + true_color_offset)
67
+ if tindex < 256:
68
+ self.info["transparency"] = tindex
69
+
70
+ self.palette = ImagePalette.raw(
71
+ "XBGR", s[7 + true_color_offset + 4 : 7 + true_color_offset + 4 + 256 * 4]
72
+ )
73
+
74
+ self.tile = [
75
+ (
76
+ "raw",
77
+ (0, 0) + self.size,
78
+ 7 + true_color_offset + 4 + 256 * 4,
79
+ ("L", 0, 1),
80
+ )
81
+ ]
82
+
83
+
84
+ def open(fp: StrOrBytesPath | IO[bytes], mode: str = "r") -> GdImageFile:
85
+ """
86
+ Load texture from a GD image file.
87
+
88
+ :param fp: GD file name, or an opened file handle.
89
+ :param mode: Optional mode. In this version, if the mode argument
90
+ is given, it must be "r".
91
+ :returns: An image instance.
92
+ :raises OSError: If the image could not be read.
93
+ """
94
+ if mode != "r":
95
+ msg = "bad mode"
96
+ raise ValueError(msg)
97
+
98
+ try:
99
+ return GdImageFile(fp)
100
+ except SyntaxError as e:
101
+ msg = "cannot identify this image file"
102
+ raise UnidentifiedImageError(msg) from e
.venv/Lib/site-packages/PIL/GifImagePlugin.py ADDED
@@ -0,0 +1,1107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # GIF file handling
6
+ #
7
+ # History:
8
+ # 1995-09-01 fl Created
9
+ # 1996-12-14 fl Added interlace support
10
+ # 1996-12-30 fl Added animation support
11
+ # 1997-01-05 fl Added write support, fixed local colour map bug
12
+ # 1997-02-23 fl Make sure to load raster data in getdata()
13
+ # 1997-07-05 fl Support external decoder (0.4)
14
+ # 1998-07-09 fl Handle all modes when saving (0.5)
15
+ # 1998-07-15 fl Renamed offset attribute to avoid name clash
16
+ # 2001-04-16 fl Added rewind support (seek to frame 0) (0.6)
17
+ # 2001-04-17 fl Added palette optimization (0.7)
18
+ # 2002-06-06 fl Added transparency support for save (0.8)
19
+ # 2004-02-24 fl Disable interlacing for small images
20
+ #
21
+ # Copyright (c) 1997-2004 by Secret Labs AB
22
+ # Copyright (c) 1995-2004 by Fredrik Lundh
23
+ #
24
+ # See the README file for information on usage and redistribution.
25
+ #
26
+ from __future__ import annotations
27
+
28
+ import itertools
29
+ import math
30
+ import os
31
+ import subprocess
32
+ from enum import IntEnum
33
+
34
+ from . import (
35
+ Image,
36
+ ImageChops,
37
+ ImageFile,
38
+ ImageMath,
39
+ ImageOps,
40
+ ImagePalette,
41
+ ImageSequence,
42
+ )
43
+ from ._binary import i16le as i16
44
+ from ._binary import o8
45
+ from ._binary import o16le as o16
46
+
47
+
48
+ class LoadingStrategy(IntEnum):
49
+ """.. versionadded:: 9.1.0"""
50
+
51
+ RGB_AFTER_FIRST = 0
52
+ RGB_AFTER_DIFFERENT_PALETTE_ONLY = 1
53
+ RGB_ALWAYS = 2
54
+
55
+
56
+ #: .. versionadded:: 9.1.0
57
+ LOADING_STRATEGY = LoadingStrategy.RGB_AFTER_FIRST
58
+
59
+ # --------------------------------------------------------------------
60
+ # Identify/read GIF files
61
+
62
+
63
+ def _accept(prefix):
64
+ return prefix[:6] in [b"GIF87a", b"GIF89a"]
65
+
66
+
67
+ ##
68
+ # Image plugin for GIF images. This plugin supports both GIF87 and
69
+ # GIF89 images.
70
+
71
+
72
+ class GifImageFile(ImageFile.ImageFile):
73
+ format = "GIF"
74
+ format_description = "Compuserve GIF"
75
+ _close_exclusive_fp_after_loading = False
76
+
77
+ global_palette = None
78
+
79
+ def data(self):
80
+ s = self.fp.read(1)
81
+ if s and s[0]:
82
+ return self.fp.read(s[0])
83
+ return None
84
+
85
+ def _is_palette_needed(self, p):
86
+ for i in range(0, len(p), 3):
87
+ if not (i // 3 == p[i] == p[i + 1] == p[i + 2]):
88
+ return True
89
+ return False
90
+
91
+ def _open(self):
92
+ # Screen
93
+ s = self.fp.read(13)
94
+ if not _accept(s):
95
+ msg = "not a GIF file"
96
+ raise SyntaxError(msg)
97
+
98
+ self.info["version"] = s[:6]
99
+ self._size = i16(s, 6), i16(s, 8)
100
+ self.tile = []
101
+ flags = s[10]
102
+ bits = (flags & 7) + 1
103
+
104
+ if flags & 128:
105
+ # get global palette
106
+ self.info["background"] = s[11]
107
+ # check if palette contains colour indices
108
+ p = self.fp.read(3 << bits)
109
+ if self._is_palette_needed(p):
110
+ p = ImagePalette.raw("RGB", p)
111
+ self.global_palette = self.palette = p
112
+
113
+ self._fp = self.fp # FIXME: hack
114
+ self.__rewind = self.fp.tell()
115
+ self._n_frames = None
116
+ self._is_animated = None
117
+ self._seek(0) # get ready to read first frame
118
+
119
+ @property
120
+ def n_frames(self):
121
+ if self._n_frames is None:
122
+ current = self.tell()
123
+ try:
124
+ while True:
125
+ self._seek(self.tell() + 1, False)
126
+ except EOFError:
127
+ self._n_frames = self.tell() + 1
128
+ self.seek(current)
129
+ return self._n_frames
130
+
131
+ @property
132
+ def is_animated(self):
133
+ if self._is_animated is None:
134
+ if self._n_frames is not None:
135
+ self._is_animated = self._n_frames != 1
136
+ else:
137
+ current = self.tell()
138
+ if current:
139
+ self._is_animated = True
140
+ else:
141
+ try:
142
+ self._seek(1, False)
143
+ self._is_animated = True
144
+ except EOFError:
145
+ self._is_animated = False
146
+
147
+ self.seek(current)
148
+ return self._is_animated
149
+
150
+ def seek(self, frame):
151
+ if not self._seek_check(frame):
152
+ return
153
+ if frame < self.__frame:
154
+ self.im = None
155
+ self._seek(0)
156
+
157
+ last_frame = self.__frame
158
+ for f in range(self.__frame + 1, frame + 1):
159
+ try:
160
+ self._seek(f)
161
+ except EOFError as e:
162
+ self.seek(last_frame)
163
+ msg = "no more images in GIF file"
164
+ raise EOFError(msg) from e
165
+
166
+ def _seek(self, frame, update_image=True):
167
+ if frame == 0:
168
+ # rewind
169
+ self.__offset = 0
170
+ self.dispose = None
171
+ self.__frame = -1
172
+ self._fp.seek(self.__rewind)
173
+ self.disposal_method = 0
174
+ if "comment" in self.info:
175
+ del self.info["comment"]
176
+ else:
177
+ # ensure that the previous frame was loaded
178
+ if self.tile and update_image:
179
+ self.load()
180
+
181
+ if frame != self.__frame + 1:
182
+ msg = f"cannot seek to frame {frame}"
183
+ raise ValueError(msg)
184
+
185
+ self.fp = self._fp
186
+ if self.__offset:
187
+ # backup to last frame
188
+ self.fp.seek(self.__offset)
189
+ while self.data():
190
+ pass
191
+ self.__offset = 0
192
+
193
+ s = self.fp.read(1)
194
+ if not s or s == b";":
195
+ msg = "no more images in GIF file"
196
+ raise EOFError(msg)
197
+
198
+ palette = None
199
+
200
+ info = {}
201
+ frame_transparency = None
202
+ interlace = None
203
+ frame_dispose_extent = None
204
+ while True:
205
+ if not s:
206
+ s = self.fp.read(1)
207
+ if not s or s == b";":
208
+ break
209
+
210
+ elif s == b"!":
211
+ #
212
+ # extensions
213
+ #
214
+ s = self.fp.read(1)
215
+ block = self.data()
216
+ if s[0] == 249:
217
+ #
218
+ # graphic control extension
219
+ #
220
+ flags = block[0]
221
+ if flags & 1:
222
+ frame_transparency = block[3]
223
+ info["duration"] = i16(block, 1) * 10
224
+
225
+ # disposal method - find the value of bits 4 - 6
226
+ dispose_bits = 0b00011100 & flags
227
+ dispose_bits = dispose_bits >> 2
228
+ if dispose_bits:
229
+ # only set the dispose if it is not
230
+ # unspecified. I'm not sure if this is
231
+ # correct, but it seems to prevent the last
232
+ # frame from looking odd for some animations
233
+ self.disposal_method = dispose_bits
234
+ elif s[0] == 254:
235
+ #
236
+ # comment extension
237
+ #
238
+ comment = b""
239
+
240
+ # Read this comment block
241
+ while block:
242
+ comment += block
243
+ block = self.data()
244
+
245
+ if "comment" in info:
246
+ # If multiple comment blocks in frame, separate with \n
247
+ info["comment"] += b"\n" + comment
248
+ else:
249
+ info["comment"] = comment
250
+ s = None
251
+ continue
252
+ elif s[0] == 255 and frame == 0:
253
+ #
254
+ # application extension
255
+ #
256
+ info["extension"] = block, self.fp.tell()
257
+ if block[:11] == b"NETSCAPE2.0":
258
+ block = self.data()
259
+ if len(block) >= 3 and block[0] == 1:
260
+ self.info["loop"] = i16(block, 1)
261
+ while self.data():
262
+ pass
263
+
264
+ elif s == b",":
265
+ #
266
+ # local image
267
+ #
268
+ s = self.fp.read(9)
269
+
270
+ # extent
271
+ x0, y0 = i16(s, 0), i16(s, 2)
272
+ x1, y1 = x0 + i16(s, 4), y0 + i16(s, 6)
273
+ if (x1 > self.size[0] or y1 > self.size[1]) and update_image:
274
+ self._size = max(x1, self.size[0]), max(y1, self.size[1])
275
+ Image._decompression_bomb_check(self._size)
276
+ frame_dispose_extent = x0, y0, x1, y1
277
+ flags = s[8]
278
+
279
+ interlace = (flags & 64) != 0
280
+
281
+ if flags & 128:
282
+ bits = (flags & 7) + 1
283
+ p = self.fp.read(3 << bits)
284
+ if self._is_palette_needed(p):
285
+ palette = ImagePalette.raw("RGB", p)
286
+ else:
287
+ palette = False
288
+
289
+ # image data
290
+ bits = self.fp.read(1)[0]
291
+ self.__offset = self.fp.tell()
292
+ break
293
+ s = None
294
+
295
+ if interlace is None:
296
+ msg = "image not found in GIF frame"
297
+ raise EOFError(msg)
298
+
299
+ self.__frame = frame
300
+ if not update_image:
301
+ return
302
+
303
+ self.tile = []
304
+
305
+ if self.dispose:
306
+ self.im.paste(self.dispose, self.dispose_extent)
307
+
308
+ self._frame_palette = palette if palette is not None else self.global_palette
309
+ self._frame_transparency = frame_transparency
310
+ if frame == 0:
311
+ if self._frame_palette:
312
+ if LOADING_STRATEGY == LoadingStrategy.RGB_ALWAYS:
313
+ self._mode = "RGBA" if frame_transparency is not None else "RGB"
314
+ else:
315
+ self._mode = "P"
316
+ else:
317
+ self._mode = "L"
318
+
319
+ if not palette and self.global_palette:
320
+ from copy import copy
321
+
322
+ palette = copy(self.global_palette)
323
+ self.palette = palette
324
+ else:
325
+ if self.mode == "P":
326
+ if (
327
+ LOADING_STRATEGY != LoadingStrategy.RGB_AFTER_DIFFERENT_PALETTE_ONLY
328
+ or palette
329
+ ):
330
+ self.pyaccess = None
331
+ if "transparency" in self.info:
332
+ self.im.putpalettealpha(self.info["transparency"], 0)
333
+ self.im = self.im.convert("RGBA", Image.Dither.FLOYDSTEINBERG)
334
+ self._mode = "RGBA"
335
+ del self.info["transparency"]
336
+ else:
337
+ self._mode = "RGB"
338
+ self.im = self.im.convert("RGB", Image.Dither.FLOYDSTEINBERG)
339
+
340
+ def _rgb(color):
341
+ if self._frame_palette:
342
+ if color * 3 + 3 > len(self._frame_palette.palette):
343
+ color = 0
344
+ color = tuple(self._frame_palette.palette[color * 3 : color * 3 + 3])
345
+ else:
346
+ color = (color, color, color)
347
+ return color
348
+
349
+ self.dispose_extent = frame_dispose_extent
350
+ try:
351
+ if self.disposal_method < 2:
352
+ # do not dispose or none specified
353
+ self.dispose = None
354
+ elif self.disposal_method == 2:
355
+ # replace with background colour
356
+
357
+ # only dispose the extent in this frame
358
+ x0, y0, x1, y1 = self.dispose_extent
359
+ dispose_size = (x1 - x0, y1 - y0)
360
+
361
+ Image._decompression_bomb_check(dispose_size)
362
+
363
+ # by convention, attempt to use transparency first
364
+ dispose_mode = "P"
365
+ color = self.info.get("transparency", frame_transparency)
366
+ if color is not None:
367
+ if self.mode in ("RGB", "RGBA"):
368
+ dispose_mode = "RGBA"
369
+ color = _rgb(color) + (0,)
370
+ else:
371
+ color = self.info.get("background", 0)
372
+ if self.mode in ("RGB", "RGBA"):
373
+ dispose_mode = "RGB"
374
+ color = _rgb(color)
375
+ self.dispose = Image.core.fill(dispose_mode, dispose_size, color)
376
+ else:
377
+ # replace with previous contents
378
+ if self.im is not None:
379
+ # only dispose the extent in this frame
380
+ self.dispose = self._crop(self.im, self.dispose_extent)
381
+ elif frame_transparency is not None:
382
+ x0, y0, x1, y1 = self.dispose_extent
383
+ dispose_size = (x1 - x0, y1 - y0)
384
+
385
+ Image._decompression_bomb_check(dispose_size)
386
+ dispose_mode = "P"
387
+ color = frame_transparency
388
+ if self.mode in ("RGB", "RGBA"):
389
+ dispose_mode = "RGBA"
390
+ color = _rgb(frame_transparency) + (0,)
391
+ self.dispose = Image.core.fill(dispose_mode, dispose_size, color)
392
+ except AttributeError:
393
+ pass
394
+
395
+ if interlace is not None:
396
+ transparency = -1
397
+ if frame_transparency is not None:
398
+ if frame == 0:
399
+ if LOADING_STRATEGY != LoadingStrategy.RGB_ALWAYS:
400
+ self.info["transparency"] = frame_transparency
401
+ elif self.mode not in ("RGB", "RGBA"):
402
+ transparency = frame_transparency
403
+ self.tile = [
404
+ (
405
+ "gif",
406
+ (x0, y0, x1, y1),
407
+ self.__offset,
408
+ (bits, interlace, transparency),
409
+ )
410
+ ]
411
+
412
+ if info.get("comment"):
413
+ self.info["comment"] = info["comment"]
414
+ for k in ["duration", "extension"]:
415
+ if k in info:
416
+ self.info[k] = info[k]
417
+ elif k in self.info:
418
+ del self.info[k]
419
+
420
+ def load_prepare(self):
421
+ temp_mode = "P" if self._frame_palette else "L"
422
+ self._prev_im = None
423
+ if self.__frame == 0:
424
+ if self._frame_transparency is not None:
425
+ self.im = Image.core.fill(
426
+ temp_mode, self.size, self._frame_transparency
427
+ )
428
+ elif self.mode in ("RGB", "RGBA"):
429
+ self._prev_im = self.im
430
+ if self._frame_palette:
431
+ self.im = Image.core.fill("P", self.size, self._frame_transparency or 0)
432
+ self.im.putpalette(*self._frame_palette.getdata())
433
+ else:
434
+ self.im = None
435
+ self._mode = temp_mode
436
+ self._frame_palette = None
437
+
438
+ super().load_prepare()
439
+
440
+ def load_end(self):
441
+ if self.__frame == 0:
442
+ if self.mode == "P" and LOADING_STRATEGY == LoadingStrategy.RGB_ALWAYS:
443
+ if self._frame_transparency is not None:
444
+ self.im.putpalettealpha(self._frame_transparency, 0)
445
+ self._mode = "RGBA"
446
+ else:
447
+ self._mode = "RGB"
448
+ self.im = self.im.convert(self.mode, Image.Dither.FLOYDSTEINBERG)
449
+ return
450
+ if not self._prev_im:
451
+ return
452
+ if self._frame_transparency is not None:
453
+ self.im.putpalettealpha(self._frame_transparency, 0)
454
+ frame_im = self.im.convert("RGBA")
455
+ else:
456
+ frame_im = self.im.convert("RGB")
457
+ frame_im = self._crop(frame_im, self.dispose_extent)
458
+
459
+ self.im = self._prev_im
460
+ self._mode = self.im.mode
461
+ if frame_im.mode == "RGBA":
462
+ self.im.paste(frame_im, self.dispose_extent, frame_im)
463
+ else:
464
+ self.im.paste(frame_im, self.dispose_extent)
465
+
466
+ def tell(self):
467
+ return self.__frame
468
+
469
+
470
+ # --------------------------------------------------------------------
471
+ # Write GIF files
472
+
473
+
474
+ RAWMODE = {"1": "L", "L": "L", "P": "P"}
475
+
476
+
477
+ def _normalize_mode(im):
478
+ """
479
+ Takes an image (or frame), returns an image in a mode that is appropriate
480
+ for saving in a Gif.
481
+
482
+ It may return the original image, or it may return an image converted to
483
+ palette or 'L' mode.
484
+
485
+ :param im: Image object
486
+ :returns: Image object
487
+ """
488
+ if im.mode in RAWMODE:
489
+ im.load()
490
+ return im
491
+ if Image.getmodebase(im.mode) == "RGB":
492
+ im = im.convert("P", palette=Image.Palette.ADAPTIVE)
493
+ if im.palette.mode == "RGBA":
494
+ for rgba in im.palette.colors:
495
+ if rgba[3] == 0:
496
+ im.info["transparency"] = im.palette.colors[rgba]
497
+ break
498
+ return im
499
+ return im.convert("L")
500
+
501
+
502
+ def _normalize_palette(im, palette, info):
503
+ """
504
+ Normalizes the palette for image.
505
+ - Sets the palette to the incoming palette, if provided.
506
+ - Ensures that there's a palette for L mode images
507
+ - Optimizes the palette if necessary/desired.
508
+
509
+ :param im: Image object
510
+ :param palette: bytes object containing the source palette, or ....
511
+ :param info: encoderinfo
512
+ :returns: Image object
513
+ """
514
+ source_palette = None
515
+ if palette:
516
+ # a bytes palette
517
+ if isinstance(palette, (bytes, bytearray, list)):
518
+ source_palette = bytearray(palette[:768])
519
+ if isinstance(palette, ImagePalette.ImagePalette):
520
+ source_palette = bytearray(palette.palette)
521
+
522
+ if im.mode == "P":
523
+ if not source_palette:
524
+ source_palette = im.im.getpalette("RGB")[:768]
525
+ else: # L-mode
526
+ if not source_palette:
527
+ source_palette = bytearray(i // 3 for i in range(768))
528
+ im.palette = ImagePalette.ImagePalette("RGB", palette=source_palette)
529
+
530
+ if palette:
531
+ used_palette_colors = []
532
+ for i in range(0, len(source_palette), 3):
533
+ source_color = tuple(source_palette[i : i + 3])
534
+ index = im.palette.colors.get(source_color)
535
+ if index in used_palette_colors:
536
+ index = None
537
+ used_palette_colors.append(index)
538
+ for i, index in enumerate(used_palette_colors):
539
+ if index is None:
540
+ for j in range(len(used_palette_colors)):
541
+ if j not in used_palette_colors:
542
+ used_palette_colors[i] = j
543
+ break
544
+ im = im.remap_palette(used_palette_colors)
545
+ else:
546
+ used_palette_colors = _get_optimize(im, info)
547
+ if used_palette_colors is not None:
548
+ im = im.remap_palette(used_palette_colors, source_palette)
549
+ if "transparency" in info:
550
+ try:
551
+ info["transparency"] = used_palette_colors.index(
552
+ info["transparency"]
553
+ )
554
+ except ValueError:
555
+ del info["transparency"]
556
+ return im
557
+
558
+ im.palette.palette = source_palette
559
+ return im
560
+
561
+
562
+ def _write_single_frame(im, fp, palette):
563
+ im_out = _normalize_mode(im)
564
+ for k, v in im_out.info.items():
565
+ im.encoderinfo.setdefault(k, v)
566
+ im_out = _normalize_palette(im_out, palette, im.encoderinfo)
567
+
568
+ for s in _get_global_header(im_out, im.encoderinfo):
569
+ fp.write(s)
570
+
571
+ # local image header
572
+ flags = 0
573
+ if get_interlace(im):
574
+ flags = flags | 64
575
+ _write_local_header(fp, im, (0, 0), flags)
576
+
577
+ im_out.encoderconfig = (8, get_interlace(im))
578
+ ImageFile._save(im_out, fp, [("gif", (0, 0) + im.size, 0, RAWMODE[im_out.mode])])
579
+
580
+ fp.write(b"\0") # end of image data
581
+
582
+
583
+ def _getbbox(base_im, im_frame):
584
+ if _get_palette_bytes(im_frame) != _get_palette_bytes(base_im):
585
+ im_frame = im_frame.convert("RGBA")
586
+ base_im = base_im.convert("RGBA")
587
+ delta = ImageChops.subtract_modulo(im_frame, base_im)
588
+ return delta, delta.getbbox(alpha_only=False)
589
+
590
+
591
+ def _write_multiple_frames(im, fp, palette):
592
+ duration = im.encoderinfo.get("duration")
593
+ disposal = im.encoderinfo.get("disposal", im.info.get("disposal"))
594
+
595
+ im_frames = []
596
+ previous_im = None
597
+ frame_count = 0
598
+ background_im = None
599
+ for imSequence in itertools.chain([im], im.encoderinfo.get("append_images", [])):
600
+ for im_frame in ImageSequence.Iterator(imSequence):
601
+ # a copy is required here since seek can still mutate the image
602
+ im_frame = _normalize_mode(im_frame.copy())
603
+ if frame_count == 0:
604
+ for k, v in im_frame.info.items():
605
+ if k == "transparency":
606
+ continue
607
+ im.encoderinfo.setdefault(k, v)
608
+
609
+ encoderinfo = im.encoderinfo.copy()
610
+ if "transparency" in im_frame.info:
611
+ encoderinfo.setdefault("transparency", im_frame.info["transparency"])
612
+ im_frame = _normalize_palette(im_frame, palette, encoderinfo)
613
+ if isinstance(duration, (list, tuple)):
614
+ encoderinfo["duration"] = duration[frame_count]
615
+ elif duration is None and "duration" in im_frame.info:
616
+ encoderinfo["duration"] = im_frame.info["duration"]
617
+ if isinstance(disposal, (list, tuple)):
618
+ encoderinfo["disposal"] = disposal[frame_count]
619
+ frame_count += 1
620
+
621
+ diff_frame = None
622
+ if im_frames:
623
+ # delta frame
624
+ delta, bbox = _getbbox(previous_im, im_frame)
625
+ if not bbox:
626
+ # This frame is identical to the previous frame
627
+ if encoderinfo.get("duration"):
628
+ im_frames[-1]["encoderinfo"]["duration"] += encoderinfo[
629
+ "duration"
630
+ ]
631
+ continue
632
+ if im_frames[-1]["encoderinfo"].get("disposal") == 2:
633
+ if background_im is None:
634
+ color = im.encoderinfo.get(
635
+ "transparency", im.info.get("transparency", (0, 0, 0))
636
+ )
637
+ background = _get_background(im_frame, color)
638
+ background_im = Image.new("P", im_frame.size, background)
639
+ background_im.putpalette(im_frames[0]["im"].palette)
640
+ bbox = _getbbox(background_im, im_frame)[1]
641
+ elif encoderinfo.get("optimize") and im_frame.mode != "1":
642
+ if "transparency" not in encoderinfo:
643
+ try:
644
+ encoderinfo["transparency"] = (
645
+ im_frame.palette._new_color_index(im_frame)
646
+ )
647
+ except ValueError:
648
+ pass
649
+ if "transparency" in encoderinfo:
650
+ # When the delta is zero, fill the image with transparency
651
+ diff_frame = im_frame.copy()
652
+ fill = Image.new("P", delta.size, encoderinfo["transparency"])
653
+ if delta.mode == "RGBA":
654
+ r, g, b, a = delta.split()
655
+ mask = ImageMath.lambda_eval(
656
+ lambda args: args["convert"](
657
+ args["max"](
658
+ args["max"](
659
+ args["max"](args["r"], args["g"]), args["b"]
660
+ ),
661
+ args["a"],
662
+ )
663
+ * 255,
664
+ "1",
665
+ ),
666
+ r=r,
667
+ g=g,
668
+ b=b,
669
+ a=a,
670
+ )
671
+ else:
672
+ if delta.mode == "P":
673
+ # Convert to L without considering palette
674
+ delta_l = Image.new("L", delta.size)
675
+ delta_l.putdata(delta.getdata())
676
+ delta = delta_l
677
+ mask = ImageMath.lambda_eval(
678
+ lambda args: args["convert"](args["im"] * 255, "1"),
679
+ im=delta,
680
+ )
681
+ diff_frame.paste(fill, mask=ImageOps.invert(mask))
682
+ else:
683
+ bbox = None
684
+ previous_im = im_frame
685
+ im_frames.append(
686
+ {"im": diff_frame or im_frame, "bbox": bbox, "encoderinfo": encoderinfo}
687
+ )
688
+
689
+ if len(im_frames) == 1:
690
+ if "duration" in im.encoderinfo:
691
+ # Since multiple frames will not be written, use the combined duration
692
+ im.encoderinfo["duration"] = im_frames[0]["encoderinfo"]["duration"]
693
+ return
694
+
695
+ for frame_data in im_frames:
696
+ im_frame = frame_data["im"]
697
+ if not frame_data["bbox"]:
698
+ # global header
699
+ for s in _get_global_header(im_frame, frame_data["encoderinfo"]):
700
+ fp.write(s)
701
+ offset = (0, 0)
702
+ else:
703
+ # compress difference
704
+ if not palette:
705
+ frame_data["encoderinfo"]["include_color_table"] = True
706
+
707
+ im_frame = im_frame.crop(frame_data["bbox"])
708
+ offset = frame_data["bbox"][:2]
709
+ _write_frame_data(fp, im_frame, offset, frame_data["encoderinfo"])
710
+ return True
711
+
712
+
713
+ def _save_all(im, fp, filename):
714
+ _save(im, fp, filename, save_all=True)
715
+
716
+
717
+ def _save(im, fp, filename, save_all=False):
718
+ # header
719
+ if "palette" in im.encoderinfo or "palette" in im.info:
720
+ palette = im.encoderinfo.get("palette", im.info.get("palette"))
721
+ else:
722
+ palette = None
723
+ im.encoderinfo.setdefault("optimize", True)
724
+
725
+ if not save_all or not _write_multiple_frames(im, fp, palette):
726
+ _write_single_frame(im, fp, palette)
727
+
728
+ fp.write(b";") # end of file
729
+
730
+ if hasattr(fp, "flush"):
731
+ fp.flush()
732
+
733
+
734
+ def get_interlace(im):
735
+ interlace = im.encoderinfo.get("interlace", 1)
736
+
737
+ # workaround for @PIL153
738
+ if min(im.size) < 16:
739
+ interlace = 0
740
+
741
+ return interlace
742
+
743
+
744
+ def _write_local_header(fp, im, offset, flags):
745
+ try:
746
+ transparency = im.encoderinfo["transparency"]
747
+ except KeyError:
748
+ transparency = None
749
+
750
+ if "duration" in im.encoderinfo:
751
+ duration = int(im.encoderinfo["duration"] / 10)
752
+ else:
753
+ duration = 0
754
+
755
+ disposal = int(im.encoderinfo.get("disposal", 0))
756
+
757
+ if transparency is not None or duration != 0 or disposal:
758
+ packed_flag = 1 if transparency is not None else 0
759
+ packed_flag |= disposal << 2
760
+
761
+ fp.write(
762
+ b"!"
763
+ + o8(249) # extension intro
764
+ + o8(4) # length
765
+ + o8(packed_flag) # packed fields
766
+ + o16(duration) # duration
767
+ + o8(transparency or 0) # transparency index
768
+ + o8(0)
769
+ )
770
+
771
+ include_color_table = im.encoderinfo.get("include_color_table")
772
+ if include_color_table:
773
+ palette_bytes = _get_palette_bytes(im)
774
+ color_table_size = _get_color_table_size(palette_bytes)
775
+ if color_table_size:
776
+ flags = flags | 128 # local color table flag
777
+ flags = flags | color_table_size
778
+
779
+ fp.write(
780
+ b","
781
+ + o16(offset[0]) # offset
782
+ + o16(offset[1])
783
+ + o16(im.size[0]) # size
784
+ + o16(im.size[1])
785
+ + o8(flags) # flags
786
+ )
787
+ if include_color_table and color_table_size:
788
+ fp.write(_get_header_palette(palette_bytes))
789
+ fp.write(o8(8)) # bits
790
+
791
+
792
+ def _save_netpbm(im, fp, filename):
793
+ # Unused by default.
794
+ # To use, uncomment the register_save call at the end of the file.
795
+ #
796
+ # If you need real GIF compression and/or RGB quantization, you
797
+ # can use the external NETPBM/PBMPLUS utilities. See comments
798
+ # below for information on how to enable this.
799
+ tempfile = im._dump()
800
+
801
+ try:
802
+ with open(filename, "wb") as f:
803
+ if im.mode != "RGB":
804
+ subprocess.check_call(
805
+ ["ppmtogif", tempfile], stdout=f, stderr=subprocess.DEVNULL
806
+ )
807
+ else:
808
+ # Pipe ppmquant output into ppmtogif
809
+ # "ppmquant 256 %s | ppmtogif > %s" % (tempfile, filename)
810
+ quant_cmd = ["ppmquant", "256", tempfile]
811
+ togif_cmd = ["ppmtogif"]
812
+ quant_proc = subprocess.Popen(
813
+ quant_cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL
814
+ )
815
+ togif_proc = subprocess.Popen(
816
+ togif_cmd,
817
+ stdin=quant_proc.stdout,
818
+ stdout=f,
819
+ stderr=subprocess.DEVNULL,
820
+ )
821
+
822
+ # Allow ppmquant to receive SIGPIPE if ppmtogif exits
823
+ quant_proc.stdout.close()
824
+
825
+ retcode = quant_proc.wait()
826
+ if retcode:
827
+ raise subprocess.CalledProcessError(retcode, quant_cmd)
828
+
829
+ retcode = togif_proc.wait()
830
+ if retcode:
831
+ raise subprocess.CalledProcessError(retcode, togif_cmd)
832
+ finally:
833
+ try:
834
+ os.unlink(tempfile)
835
+ except OSError:
836
+ pass
837
+
838
+
839
+ # Force optimization so that we can test performance against
840
+ # cases where it took lots of memory and time previously.
841
+ _FORCE_OPTIMIZE = False
842
+
843
+
844
+ def _get_optimize(im, info):
845
+ """
846
+ Palette optimization is a potentially expensive operation.
847
+
848
+ This function determines if the palette should be optimized using
849
+ some heuristics, then returns the list of palette entries in use.
850
+
851
+ :param im: Image object
852
+ :param info: encoderinfo
853
+ :returns: list of indexes of palette entries in use, or None
854
+ """
855
+ if im.mode in ("P", "L") and info and info.get("optimize"):
856
+ # Potentially expensive operation.
857
+
858
+ # The palette saves 3 bytes per color not used, but palette
859
+ # lengths are restricted to 3*(2**N) bytes. Max saving would
860
+ # be 768 -> 6 bytes if we went all the way down to 2 colors.
861
+ # * If we're over 128 colors, we can't save any space.
862
+ # * If there aren't any holes, it's not worth collapsing.
863
+ # * If we have a 'large' image, the palette is in the noise.
864
+
865
+ # create the new palette if not every color is used
866
+ optimise = _FORCE_OPTIMIZE or im.mode == "L"
867
+ if optimise or im.width * im.height < 512 * 512:
868
+ # check which colors are used
869
+ used_palette_colors = []
870
+ for i, count in enumerate(im.histogram()):
871
+ if count:
872
+ used_palette_colors.append(i)
873
+
874
+ if optimise or max(used_palette_colors) >= len(used_palette_colors):
875
+ return used_palette_colors
876
+
877
+ num_palette_colors = len(im.palette.palette) // Image.getmodebands(
878
+ im.palette.mode
879
+ )
880
+ current_palette_size = 1 << (num_palette_colors - 1).bit_length()
881
+ if (
882
+ # check that the palette would become smaller when saved
883
+ len(used_palette_colors) <= current_palette_size // 2
884
+ # check that the palette is not already the smallest possible size
885
+ and current_palette_size > 2
886
+ ):
887
+ return used_palette_colors
888
+
889
+
890
+ def _get_color_table_size(palette_bytes):
891
+ # calculate the palette size for the header
892
+ if not palette_bytes:
893
+ return 0
894
+ elif len(palette_bytes) < 9:
895
+ return 1
896
+ else:
897
+ return math.ceil(math.log(len(palette_bytes) // 3, 2)) - 1
898
+
899
+
900
+ def _get_header_palette(palette_bytes):
901
+ """
902
+ Returns the palette, null padded to the next power of 2 (*3) bytes
903
+ suitable for direct inclusion in the GIF header
904
+
905
+ :param palette_bytes: Unpadded palette bytes, in RGBRGB form
906
+ :returns: Null padded palette
907
+ """
908
+ color_table_size = _get_color_table_size(palette_bytes)
909
+
910
+ # add the missing amount of bytes
911
+ # the palette has to be 2<<n in size
912
+ actual_target_size_diff = (2 << color_table_size) - len(palette_bytes) // 3
913
+ if actual_target_size_diff > 0:
914
+ palette_bytes += o8(0) * 3 * actual_target_size_diff
915
+ return palette_bytes
916
+
917
+
918
+ def _get_palette_bytes(im):
919
+ """
920
+ Gets the palette for inclusion in the gif header
921
+
922
+ :param im: Image object
923
+ :returns: Bytes, len<=768 suitable for inclusion in gif header
924
+ """
925
+ return im.palette.palette if im.palette else b""
926
+
927
+
928
+ def _get_background(im, info_background):
929
+ background = 0
930
+ if info_background:
931
+ if isinstance(info_background, tuple):
932
+ # WebPImagePlugin stores an RGBA value in info["background"]
933
+ # So it must be converted to the same format as GifImagePlugin's
934
+ # info["background"] - a global color table index
935
+ try:
936
+ background = im.palette.getcolor(info_background, im)
937
+ except ValueError as e:
938
+ if str(e) not in (
939
+ # If all 256 colors are in use,
940
+ # then there is no need for the background color
941
+ "cannot allocate more than 256 colors",
942
+ # Ignore non-opaque WebP background
943
+ "cannot add non-opaque RGBA color to RGB palette",
944
+ ):
945
+ raise
946
+ else:
947
+ background = info_background
948
+ return background
949
+
950
+
951
+ def _get_global_header(im, info):
952
+ """Return a list of strings representing a GIF header"""
953
+
954
+ # Header Block
955
+ # https://www.matthewflickinger.com/lab/whatsinagif/bits_and_bytes.asp
956
+
957
+ version = b"87a"
958
+ if im.info.get("version") == b"89a" or (
959
+ info
960
+ and (
961
+ "transparency" in info
962
+ or info.get("loop") is not None
963
+ or info.get("duration")
964
+ or info.get("comment")
965
+ )
966
+ ):
967
+ version = b"89a"
968
+
969
+ background = _get_background(im, info.get("background"))
970
+
971
+ palette_bytes = _get_palette_bytes(im)
972
+ color_table_size = _get_color_table_size(palette_bytes)
973
+
974
+ header = [
975
+ b"GIF" # signature
976
+ + version # version
977
+ + o16(im.size[0]) # canvas width
978
+ + o16(im.size[1]), # canvas height
979
+ # Logical Screen Descriptor
980
+ # size of global color table + global color table flag
981
+ o8(color_table_size + 128), # packed fields
982
+ # background + reserved/aspect
983
+ o8(background) + o8(0),
984
+ # Global Color Table
985
+ _get_header_palette(palette_bytes),
986
+ ]
987
+ if info.get("loop") is not None:
988
+ header.append(
989
+ b"!"
990
+ + o8(255) # extension intro
991
+ + o8(11)
992
+ + b"NETSCAPE2.0"
993
+ + o8(3)
994
+ + o8(1)
995
+ + o16(info["loop"]) # number of loops
996
+ + o8(0)
997
+ )
998
+ if info.get("comment"):
999
+ comment_block = b"!" + o8(254) # extension intro
1000
+
1001
+ comment = info["comment"]
1002
+ if isinstance(comment, str):
1003
+ comment = comment.encode()
1004
+ for i in range(0, len(comment), 255):
1005
+ subblock = comment[i : i + 255]
1006
+ comment_block += o8(len(subblock)) + subblock
1007
+
1008
+ comment_block += o8(0)
1009
+ header.append(comment_block)
1010
+ return header
1011
+
1012
+
1013
+ def _write_frame_data(fp, im_frame, offset, params):
1014
+ try:
1015
+ im_frame.encoderinfo = params
1016
+
1017
+ # local image header
1018
+ _write_local_header(fp, im_frame, offset, 0)
1019
+
1020
+ ImageFile._save(
1021
+ im_frame, fp, [("gif", (0, 0) + im_frame.size, 0, RAWMODE[im_frame.mode])]
1022
+ )
1023
+
1024
+ fp.write(b"\0") # end of image data
1025
+ finally:
1026
+ del im_frame.encoderinfo
1027
+
1028
+
1029
+ # --------------------------------------------------------------------
1030
+ # Legacy GIF utilities
1031
+
1032
+
1033
+ def getheader(im, palette=None, info=None):
1034
+ """
1035
+ Legacy Method to get Gif data from image.
1036
+
1037
+ Warning:: May modify image data.
1038
+
1039
+ :param im: Image object
1040
+ :param palette: bytes object containing the source palette, or ....
1041
+ :param info: encoderinfo
1042
+ :returns: tuple of(list of header items, optimized palette)
1043
+
1044
+ """
1045
+ used_palette_colors = _get_optimize(im, info)
1046
+
1047
+ if info is None:
1048
+ info = {}
1049
+
1050
+ if "background" not in info and "background" in im.info:
1051
+ info["background"] = im.info["background"]
1052
+
1053
+ im_mod = _normalize_palette(im, palette, info)
1054
+ im.palette = im_mod.palette
1055
+ im.im = im_mod.im
1056
+ header = _get_global_header(im, info)
1057
+
1058
+ return header, used_palette_colors
1059
+
1060
+
1061
+ def getdata(im, offset=(0, 0), **params):
1062
+ """
1063
+ Legacy Method
1064
+
1065
+ Return a list of strings representing this image.
1066
+ The first string is a local image header, the rest contains
1067
+ encoded image data.
1068
+
1069
+ To specify duration, add the time in milliseconds,
1070
+ e.g. ``getdata(im_frame, duration=1000)``
1071
+
1072
+ :param im: Image object
1073
+ :param offset: Tuple of (x, y) pixels. Defaults to (0, 0)
1074
+ :param \\**params: e.g. duration or other encoder info parameters
1075
+ :returns: List of bytes containing GIF encoded frame data
1076
+
1077
+ """
1078
+
1079
+ class Collector:
1080
+ data = []
1081
+
1082
+ def write(self, data):
1083
+ self.data.append(data)
1084
+
1085
+ im.load() # make sure raster data is available
1086
+
1087
+ fp = Collector()
1088
+
1089
+ _write_frame_data(fp, im, offset, params)
1090
+
1091
+ return fp.data
1092
+
1093
+
1094
+ # --------------------------------------------------------------------
1095
+ # Registry
1096
+
1097
+ Image.register_open(GifImageFile.format, GifImageFile, _accept)
1098
+ Image.register_save(GifImageFile.format, _save)
1099
+ Image.register_save_all(GifImageFile.format, _save_all)
1100
+ Image.register_extension(GifImageFile.format, ".gif")
1101
+ Image.register_mime(GifImageFile.format, "image/gif")
1102
+
1103
+ #
1104
+ # Uncomment the following line if you wish to use NETPBM/PBMPLUS
1105
+ # instead of the built-in "uncompressed" GIF encoder
1106
+
1107
+ # Image.register_save(GifImageFile.format, _save_netpbm)
.venv/Lib/site-packages/PIL/GimpGradientFile.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Python Imaging Library
3
+ # $Id$
4
+ #
5
+ # stuff to read (and render) GIMP gradient files
6
+ #
7
+ # History:
8
+ # 97-08-23 fl Created
9
+ #
10
+ # Copyright (c) Secret Labs AB 1997.
11
+ # Copyright (c) Fredrik Lundh 1997.
12
+ #
13
+ # See the README file for information on usage and redistribution.
14
+ #
15
+
16
+ """
17
+ Stuff to translate curve segments to palette values (derived from
18
+ the corresponding code in GIMP, written by Federico Mena Quintero.
19
+ See the GIMP distribution for more information.)
20
+ """
21
+ from __future__ import annotations
22
+
23
+ from math import log, pi, sin, sqrt
24
+
25
+ from ._binary import o8
26
+
27
+ EPSILON = 1e-10
28
+ """""" # Enable auto-doc for data member
29
+
30
+
31
+ def linear(middle, pos):
32
+ if pos <= middle:
33
+ if middle < EPSILON:
34
+ return 0.0
35
+ else:
36
+ return 0.5 * pos / middle
37
+ else:
38
+ pos = pos - middle
39
+ middle = 1.0 - middle
40
+ if middle < EPSILON:
41
+ return 1.0
42
+ else:
43
+ return 0.5 + 0.5 * pos / middle
44
+
45
+
46
+ def curved(middle, pos):
47
+ return pos ** (log(0.5) / log(max(middle, EPSILON)))
48
+
49
+
50
+ def sine(middle, pos):
51
+ return (sin((-pi / 2.0) + pi * linear(middle, pos)) + 1.0) / 2.0
52
+
53
+
54
+ def sphere_increasing(middle, pos):
55
+ return sqrt(1.0 - (linear(middle, pos) - 1.0) ** 2)
56
+
57
+
58
+ def sphere_decreasing(middle, pos):
59
+ return 1.0 - sqrt(1.0 - linear(middle, pos) ** 2)
60
+
61
+
62
+ SEGMENTS = [linear, curved, sine, sphere_increasing, sphere_decreasing]
63
+ """""" # Enable auto-doc for data member
64
+
65
+
66
+ class GradientFile:
67
+ gradient = None
68
+
69
+ def getpalette(self, entries=256):
70
+ palette = []
71
+
72
+ ix = 0
73
+ x0, x1, xm, rgb0, rgb1, segment = self.gradient[ix]
74
+
75
+ for i in range(entries):
76
+ x = i / (entries - 1)
77
+
78
+ while x1 < x:
79
+ ix += 1
80
+ x0, x1, xm, rgb0, rgb1, segment = self.gradient[ix]
81
+
82
+ w = x1 - x0
83
+
84
+ if w < EPSILON:
85
+ scale = segment(0.5, 0.5)
86
+ else:
87
+ scale = segment((xm - x0) / w, (x - x0) / w)
88
+
89
+ # expand to RGBA
90
+ r = o8(int(255 * ((rgb1[0] - rgb0[0]) * scale + rgb0[0]) + 0.5))
91
+ g = o8(int(255 * ((rgb1[1] - rgb0[1]) * scale + rgb0[1]) + 0.5))
92
+ b = o8(int(255 * ((rgb1[2] - rgb0[2]) * scale + rgb0[2]) + 0.5))
93
+ a = o8(int(255 * ((rgb1[3] - rgb0[3]) * scale + rgb0[3]) + 0.5))
94
+
95
+ # add to palette
96
+ palette.append(r + g + b + a)
97
+
98
+ return b"".join(palette), "RGBA"
99
+
100
+
101
+ class GimpGradientFile(GradientFile):
102
+ """File handler for GIMP's gradient format."""
103
+
104
+ def __init__(self, fp):
105
+ if fp.readline()[:13] != b"GIMP Gradient":
106
+ msg = "not a GIMP gradient file"
107
+ raise SyntaxError(msg)
108
+
109
+ line = fp.readline()
110
+
111
+ # GIMP 1.2 gradient files don't contain a name, but GIMP 1.3 files do
112
+ if line.startswith(b"Name: "):
113
+ line = fp.readline().strip()
114
+
115
+ count = int(line)
116
+
117
+ gradient = []
118
+
119
+ for i in range(count):
120
+ s = fp.readline().split()
121
+ w = [float(x) for x in s[:11]]
122
+
123
+ x0, x1 = w[0], w[2]
124
+ xm = w[1]
125
+ rgb0 = w[3:7]
126
+ rgb1 = w[7:11]
127
+
128
+ segment = SEGMENTS[int(s[11])]
129
+ cspace = int(s[12])
130
+
131
+ if cspace != 0:
132
+ msg = "cannot handle HSV colour space"
133
+ raise OSError(msg)
134
+
135
+ gradient.append((x0, x1, xm, rgb0, rgb1, segment))
136
+
137
+ self.gradient = gradient
.venv/Lib/site-packages/PIL/GimpPaletteFile.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Python Imaging Library
3
+ # $Id$
4
+ #
5
+ # stuff to read GIMP palette files
6
+ #
7
+ # History:
8
+ # 1997-08-23 fl Created
9
+ # 2004-09-07 fl Support GIMP 2.0 palette files.
10
+ #
11
+ # Copyright (c) Secret Labs AB 1997-2004. All rights reserved.
12
+ # Copyright (c) Fredrik Lundh 1997-2004.
13
+ #
14
+ # See the README file for information on usage and redistribution.
15
+ #
16
+ from __future__ import annotations
17
+
18
+ import re
19
+
20
+ from ._binary import o8
21
+
22
+
23
+ class GimpPaletteFile:
24
+ """File handler for GIMP's palette format."""
25
+
26
+ rawmode = "RGB"
27
+
28
+ def __init__(self, fp):
29
+ self.palette = [o8(i) * 3 for i in range(256)]
30
+
31
+ if fp.readline()[:12] != b"GIMP Palette":
32
+ msg = "not a GIMP palette file"
33
+ raise SyntaxError(msg)
34
+
35
+ for i in range(256):
36
+ s = fp.readline()
37
+ if not s:
38
+ break
39
+
40
+ # skip fields and comment lines
41
+ if re.match(rb"\w+:|#", s):
42
+ continue
43
+ if len(s) > 100:
44
+ msg = "bad palette file"
45
+ raise SyntaxError(msg)
46
+
47
+ v = tuple(map(int, s.split()[:3]))
48
+ if len(v) != 3:
49
+ msg = "bad palette entry"
50
+ raise ValueError(msg)
51
+
52
+ self.palette[i] = o8(v[0]) + o8(v[1]) + o8(v[2])
53
+
54
+ self.palette = b"".join(self.palette)
55
+
56
+ def getpalette(self):
57
+ return self.palette, self.rawmode
.venv/Lib/site-packages/PIL/GribStubImagePlugin.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library
3
+ # $Id$
4
+ #
5
+ # GRIB stub adapter
6
+ #
7
+ # Copyright (c) 1996-2003 by Fredrik Lundh
8
+ #
9
+ # See the README file for information on usage and redistribution.
10
+ #
11
+ from __future__ import annotations
12
+
13
+ from . import Image, ImageFile
14
+
15
+ _handler = None
16
+
17
+
18
+ def register_handler(handler):
19
+ """
20
+ Install application-specific GRIB image handler.
21
+
22
+ :param handler: Handler object.
23
+ """
24
+ global _handler
25
+ _handler = handler
26
+
27
+
28
+ # --------------------------------------------------------------------
29
+ # Image adapter
30
+
31
+
32
+ def _accept(prefix):
33
+ return prefix[:4] == b"GRIB" and prefix[7] == 1
34
+
35
+
36
+ class GribStubImageFile(ImageFile.StubImageFile):
37
+ format = "GRIB"
38
+ format_description = "GRIB"
39
+
40
+ def _open(self):
41
+ offset = self.fp.tell()
42
+
43
+ if not _accept(self.fp.read(8)):
44
+ msg = "Not a GRIB file"
45
+ raise SyntaxError(msg)
46
+
47
+ self.fp.seek(offset)
48
+
49
+ # make something up
50
+ self._mode = "F"
51
+ self._size = 1, 1
52
+
53
+ loader = self._load()
54
+ if loader:
55
+ loader.open(self)
56
+
57
+ def _load(self):
58
+ return _handler
59
+
60
+
61
+ def _save(im, fp, filename):
62
+ if _handler is None or not hasattr(_handler, "save"):
63
+ msg = "GRIB save handler not installed"
64
+ raise OSError(msg)
65
+ _handler.save(im, fp, filename)
66
+
67
+
68
+ # --------------------------------------------------------------------
69
+ # Registry
70
+
71
+ Image.register_open(GribStubImageFile.format, GribStubImageFile, _accept)
72
+ Image.register_save(GribStubImageFile.format, _save)
73
+
74
+ Image.register_extension(GribStubImageFile.format, ".grib")
.venv/Lib/site-packages/PIL/Hdf5StubImagePlugin.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library
3
+ # $Id$
4
+ #
5
+ # HDF5 stub adapter
6
+ #
7
+ # Copyright (c) 2000-2003 by Fredrik Lundh
8
+ #
9
+ # See the README file for information on usage and redistribution.
10
+ #
11
+ from __future__ import annotations
12
+
13
+ from . import Image, ImageFile
14
+
15
+ _handler = None
16
+
17
+
18
+ def register_handler(handler):
19
+ """
20
+ Install application-specific HDF5 image handler.
21
+
22
+ :param handler: Handler object.
23
+ """
24
+ global _handler
25
+ _handler = handler
26
+
27
+
28
+ # --------------------------------------------------------------------
29
+ # Image adapter
30
+
31
+
32
+ def _accept(prefix):
33
+ return prefix[:8] == b"\x89HDF\r\n\x1a\n"
34
+
35
+
36
+ class HDF5StubImageFile(ImageFile.StubImageFile):
37
+ format = "HDF5"
38
+ format_description = "HDF5"
39
+
40
+ def _open(self):
41
+ offset = self.fp.tell()
42
+
43
+ if not _accept(self.fp.read(8)):
44
+ msg = "Not an HDF file"
45
+ raise SyntaxError(msg)
46
+
47
+ self.fp.seek(offset)
48
+
49
+ # make something up
50
+ self._mode = "F"
51
+ self._size = 1, 1
52
+
53
+ loader = self._load()
54
+ if loader:
55
+ loader.open(self)
56
+
57
+ def _load(self):
58
+ return _handler
59
+
60
+
61
+ def _save(im, fp, filename):
62
+ if _handler is None or not hasattr(_handler, "save"):
63
+ msg = "HDF5 save handler not installed"
64
+ raise OSError(msg)
65
+ _handler.save(im, fp, filename)
66
+
67
+
68
+ # --------------------------------------------------------------------
69
+ # Registry
70
+
71
+ Image.register_open(HDF5StubImageFile.format, HDF5StubImageFile, _accept)
72
+ Image.register_save(HDF5StubImageFile.format, _save)
73
+
74
+ Image.register_extensions(HDF5StubImageFile.format, [".h5", ".hdf"])
.venv/Lib/site-packages/PIL/IcnsImagePlugin.py ADDED
@@ -0,0 +1,400 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # macOS icns file decoder, based on icns.py by Bob Ippolito.
6
+ #
7
+ # history:
8
+ # 2004-10-09 fl Turned into a PIL plugin; removed 2.3 dependencies.
9
+ # 2020-04-04 Allow saving on all operating systems.
10
+ #
11
+ # Copyright (c) 2004 by Bob Ippolito.
12
+ # Copyright (c) 2004 by Secret Labs.
13
+ # Copyright (c) 2004 by Fredrik Lundh.
14
+ # Copyright (c) 2014 by Alastair Houghton.
15
+ # Copyright (c) 2020 by Pan Jing.
16
+ #
17
+ # See the README file for information on usage and redistribution.
18
+ #
19
+ from __future__ import annotations
20
+
21
+ import io
22
+ import os
23
+ import struct
24
+ import sys
25
+
26
+ from . import Image, ImageFile, PngImagePlugin, features
27
+
28
+ enable_jpeg2k = features.check_codec("jpg_2000")
29
+ if enable_jpeg2k:
30
+ from . import Jpeg2KImagePlugin
31
+
32
+ MAGIC = b"icns"
33
+ HEADERSIZE = 8
34
+
35
+
36
+ def nextheader(fobj):
37
+ return struct.unpack(">4sI", fobj.read(HEADERSIZE))
38
+
39
+
40
+ def read_32t(fobj, start_length, size):
41
+ # The 128x128 icon seems to have an extra header for some reason.
42
+ (start, length) = start_length
43
+ fobj.seek(start)
44
+ sig = fobj.read(4)
45
+ if sig != b"\x00\x00\x00\x00":
46
+ msg = "Unknown signature, expecting 0x00000000"
47
+ raise SyntaxError(msg)
48
+ return read_32(fobj, (start + 4, length - 4), size)
49
+
50
+
51
+ def read_32(fobj, start_length, size):
52
+ """
53
+ Read a 32bit RGB icon resource. Seems to be either uncompressed or
54
+ an RLE packbits-like scheme.
55
+ """
56
+ (start, length) = start_length
57
+ fobj.seek(start)
58
+ pixel_size = (size[0] * size[2], size[1] * size[2])
59
+ sizesq = pixel_size[0] * pixel_size[1]
60
+ if length == sizesq * 3:
61
+ # uncompressed ("RGBRGBGB")
62
+ indata = fobj.read(length)
63
+ im = Image.frombuffer("RGB", pixel_size, indata, "raw", "RGB", 0, 1)
64
+ else:
65
+ # decode image
66
+ im = Image.new("RGB", pixel_size, None)
67
+ for band_ix in range(3):
68
+ data = []
69
+ bytesleft = sizesq
70
+ while bytesleft > 0:
71
+ byte = fobj.read(1)
72
+ if not byte:
73
+ break
74
+ byte = byte[0]
75
+ if byte & 0x80:
76
+ blocksize = byte - 125
77
+ byte = fobj.read(1)
78
+ for i in range(blocksize):
79
+ data.append(byte)
80
+ else:
81
+ blocksize = byte + 1
82
+ data.append(fobj.read(blocksize))
83
+ bytesleft -= blocksize
84
+ if bytesleft <= 0:
85
+ break
86
+ if bytesleft != 0:
87
+ msg = f"Error reading channel [{repr(bytesleft)} left]"
88
+ raise SyntaxError(msg)
89
+ band = Image.frombuffer("L", pixel_size, b"".join(data), "raw", "L", 0, 1)
90
+ im.im.putband(band.im, band_ix)
91
+ return {"RGB": im}
92
+
93
+
94
+ def read_mk(fobj, start_length, size):
95
+ # Alpha masks seem to be uncompressed
96
+ start = start_length[0]
97
+ fobj.seek(start)
98
+ pixel_size = (size[0] * size[2], size[1] * size[2])
99
+ sizesq = pixel_size[0] * pixel_size[1]
100
+ band = Image.frombuffer("L", pixel_size, fobj.read(sizesq), "raw", "L", 0, 1)
101
+ return {"A": band}
102
+
103
+
104
+ def read_png_or_jpeg2000(fobj, start_length, size):
105
+ (start, length) = start_length
106
+ fobj.seek(start)
107
+ sig = fobj.read(12)
108
+ if sig[:8] == b"\x89PNG\x0d\x0a\x1a\x0a":
109
+ fobj.seek(start)
110
+ im = PngImagePlugin.PngImageFile(fobj)
111
+ Image._decompression_bomb_check(im.size)
112
+ return {"RGBA": im}
113
+ elif (
114
+ sig[:4] == b"\xff\x4f\xff\x51"
115
+ or sig[:4] == b"\x0d\x0a\x87\x0a"
116
+ or sig == b"\x00\x00\x00\x0cjP \x0d\x0a\x87\x0a"
117
+ ):
118
+ if not enable_jpeg2k:
119
+ msg = (
120
+ "Unsupported icon subimage format (rebuild PIL "
121
+ "with JPEG 2000 support to fix this)"
122
+ )
123
+ raise ValueError(msg)
124
+ # j2k, jpc or j2c
125
+ fobj.seek(start)
126
+ jp2kstream = fobj.read(length)
127
+ f = io.BytesIO(jp2kstream)
128
+ im = Jpeg2KImagePlugin.Jpeg2KImageFile(f)
129
+ Image._decompression_bomb_check(im.size)
130
+ if im.mode != "RGBA":
131
+ im = im.convert("RGBA")
132
+ return {"RGBA": im}
133
+ else:
134
+ msg = "Unsupported icon subimage format"
135
+ raise ValueError(msg)
136
+
137
+
138
+ class IcnsFile:
139
+ SIZES = {
140
+ (512, 512, 2): [(b"ic10", read_png_or_jpeg2000)],
141
+ (512, 512, 1): [(b"ic09", read_png_or_jpeg2000)],
142
+ (256, 256, 2): [(b"ic14", read_png_or_jpeg2000)],
143
+ (256, 256, 1): [(b"ic08", read_png_or_jpeg2000)],
144
+ (128, 128, 2): [(b"ic13", read_png_or_jpeg2000)],
145
+ (128, 128, 1): [
146
+ (b"ic07", read_png_or_jpeg2000),
147
+ (b"it32", read_32t),
148
+ (b"t8mk", read_mk),
149
+ ],
150
+ (64, 64, 1): [(b"icp6", read_png_or_jpeg2000)],
151
+ (32, 32, 2): [(b"ic12", read_png_or_jpeg2000)],
152
+ (48, 48, 1): [(b"ih32", read_32), (b"h8mk", read_mk)],
153
+ (32, 32, 1): [
154
+ (b"icp5", read_png_or_jpeg2000),
155
+ (b"il32", read_32),
156
+ (b"l8mk", read_mk),
157
+ ],
158
+ (16, 16, 2): [(b"ic11", read_png_or_jpeg2000)],
159
+ (16, 16, 1): [
160
+ (b"icp4", read_png_or_jpeg2000),
161
+ (b"is32", read_32),
162
+ (b"s8mk", read_mk),
163
+ ],
164
+ }
165
+
166
+ def __init__(self, fobj):
167
+ """
168
+ fobj is a file-like object as an icns resource
169
+ """
170
+ # signature : (start, length)
171
+ self.dct = dct = {}
172
+ self.fobj = fobj
173
+ sig, filesize = nextheader(fobj)
174
+ if not _accept(sig):
175
+ msg = "not an icns file"
176
+ raise SyntaxError(msg)
177
+ i = HEADERSIZE
178
+ while i < filesize:
179
+ sig, blocksize = nextheader(fobj)
180
+ if blocksize <= 0:
181
+ msg = "invalid block header"
182
+ raise SyntaxError(msg)
183
+ i += HEADERSIZE
184
+ blocksize -= HEADERSIZE
185
+ dct[sig] = (i, blocksize)
186
+ fobj.seek(blocksize, io.SEEK_CUR)
187
+ i += blocksize
188
+
189
+ def itersizes(self):
190
+ sizes = []
191
+ for size, fmts in self.SIZES.items():
192
+ for fmt, reader in fmts:
193
+ if fmt in self.dct:
194
+ sizes.append(size)
195
+ break
196
+ return sizes
197
+
198
+ def bestsize(self):
199
+ sizes = self.itersizes()
200
+ if not sizes:
201
+ msg = "No 32bit icon resources found"
202
+ raise SyntaxError(msg)
203
+ return max(sizes)
204
+
205
+ def dataforsize(self, size):
206
+ """
207
+ Get an icon resource as {channel: array}. Note that
208
+ the arrays are bottom-up like windows bitmaps and will likely
209
+ need to be flipped or transposed in some way.
210
+ """
211
+ dct = {}
212
+ for code, reader in self.SIZES[size]:
213
+ desc = self.dct.get(code)
214
+ if desc is not None:
215
+ dct.update(reader(self.fobj, desc, size))
216
+ return dct
217
+
218
+ def getimage(self, size=None):
219
+ if size is None:
220
+ size = self.bestsize()
221
+ if len(size) == 2:
222
+ size = (size[0], size[1], 1)
223
+ channels = self.dataforsize(size)
224
+
225
+ im = channels.get("RGBA", None)
226
+ if im:
227
+ return im
228
+
229
+ im = channels.get("RGB").copy()
230
+ try:
231
+ im.putalpha(channels["A"])
232
+ except KeyError:
233
+ pass
234
+ return im
235
+
236
+
237
+ ##
238
+ # Image plugin for Mac OS icons.
239
+
240
+
241
+ class IcnsImageFile(ImageFile.ImageFile):
242
+ """
243
+ PIL image support for Mac OS .icns files.
244
+ Chooses the best resolution, but will possibly load
245
+ a different size image if you mutate the size attribute
246
+ before calling 'load'.
247
+
248
+ The info dictionary has a key 'sizes' that is a list
249
+ of sizes that the icns file has.
250
+ """
251
+
252
+ format = "ICNS"
253
+ format_description = "Mac OS icns resource"
254
+
255
+ def _open(self):
256
+ self.icns = IcnsFile(self.fp)
257
+ self._mode = "RGBA"
258
+ self.info["sizes"] = self.icns.itersizes()
259
+ self.best_size = self.icns.bestsize()
260
+ self.size = (
261
+ self.best_size[0] * self.best_size[2],
262
+ self.best_size[1] * self.best_size[2],
263
+ )
264
+
265
+ @property
266
+ def size(self):
267
+ return self._size
268
+
269
+ @size.setter
270
+ def size(self, value):
271
+ info_size = value
272
+ if info_size not in self.info["sizes"] and len(info_size) == 2:
273
+ info_size = (info_size[0], info_size[1], 1)
274
+ if (
275
+ info_size not in self.info["sizes"]
276
+ and len(info_size) == 3
277
+ and info_size[2] == 1
278
+ ):
279
+ simple_sizes = [
280
+ (size[0] * size[2], size[1] * size[2]) for size in self.info["sizes"]
281
+ ]
282
+ if value in simple_sizes:
283
+ info_size = self.info["sizes"][simple_sizes.index(value)]
284
+ if info_size not in self.info["sizes"]:
285
+ msg = "This is not one of the allowed sizes of this image"
286
+ raise ValueError(msg)
287
+ self._size = value
288
+
289
+ def load(self):
290
+ if len(self.size) == 3:
291
+ self.best_size = self.size
292
+ self.size = (
293
+ self.best_size[0] * self.best_size[2],
294
+ self.best_size[1] * self.best_size[2],
295
+ )
296
+
297
+ px = Image.Image.load(self)
298
+ if self.im is not None and self.im.size == self.size:
299
+ # Already loaded
300
+ return px
301
+ self.load_prepare()
302
+ # This is likely NOT the best way to do it, but whatever.
303
+ im = self.icns.getimage(self.best_size)
304
+
305
+ # If this is a PNG or JPEG 2000, it won't be loaded yet
306
+ px = im.load()
307
+
308
+ self.im = im.im
309
+ self._mode = im.mode
310
+ self.size = im.size
311
+
312
+ return px
313
+
314
+
315
+ def _save(im, fp, filename):
316
+ """
317
+ Saves the image as a series of PNG files,
318
+ that are then combined into a .icns file.
319
+ """
320
+ if hasattr(fp, "flush"):
321
+ fp.flush()
322
+
323
+ sizes = {
324
+ b"ic07": 128,
325
+ b"ic08": 256,
326
+ b"ic09": 512,
327
+ b"ic10": 1024,
328
+ b"ic11": 32,
329
+ b"ic12": 64,
330
+ b"ic13": 256,
331
+ b"ic14": 512,
332
+ }
333
+ provided_images = {im.width: im for im in im.encoderinfo.get("append_images", [])}
334
+ size_streams = {}
335
+ for size in set(sizes.values()):
336
+ image = (
337
+ provided_images[size]
338
+ if size in provided_images
339
+ else im.resize((size, size))
340
+ )
341
+
342
+ temp = io.BytesIO()
343
+ image.save(temp, "png")
344
+ size_streams[size] = temp.getvalue()
345
+
346
+ entries = []
347
+ for type, size in sizes.items():
348
+ stream = size_streams[size]
349
+ entries.append(
350
+ {"type": type, "size": HEADERSIZE + len(stream), "stream": stream}
351
+ )
352
+
353
+ # Header
354
+ fp.write(MAGIC)
355
+ file_length = HEADERSIZE # Header
356
+ file_length += HEADERSIZE + 8 * len(entries) # TOC
357
+ file_length += sum(entry["size"] for entry in entries)
358
+ fp.write(struct.pack(">i", file_length))
359
+
360
+ # TOC
361
+ fp.write(b"TOC ")
362
+ fp.write(struct.pack(">i", HEADERSIZE + len(entries) * HEADERSIZE))
363
+ for entry in entries:
364
+ fp.write(entry["type"])
365
+ fp.write(struct.pack(">i", entry["size"]))
366
+
367
+ # Data
368
+ for entry in entries:
369
+ fp.write(entry["type"])
370
+ fp.write(struct.pack(">i", entry["size"]))
371
+ fp.write(entry["stream"])
372
+
373
+ if hasattr(fp, "flush"):
374
+ fp.flush()
375
+
376
+
377
+ def _accept(prefix):
378
+ return prefix[:4] == MAGIC
379
+
380
+
381
+ Image.register_open(IcnsImageFile.format, IcnsImageFile, _accept)
382
+ Image.register_extension(IcnsImageFile.format, ".icns")
383
+
384
+ Image.register_save(IcnsImageFile.format, _save)
385
+ Image.register_mime(IcnsImageFile.format, "image/icns")
386
+
387
+ if __name__ == "__main__":
388
+ if len(sys.argv) < 2:
389
+ print("Syntax: python3 IcnsImagePlugin.py [file]")
390
+ sys.exit()
391
+
392
+ with open(sys.argv[1], "rb") as fp:
393
+ imf = IcnsImageFile(fp)
394
+ for size in imf.info["sizes"]:
395
+ width, height, scale = imf.size = size
396
+ imf.save(f"out-{width}-{height}-{scale}.png")
397
+ with Image.open(sys.argv[1]) as im:
398
+ im.save("out.png")
399
+ if sys.platform == "windows":
400
+ os.startfile("out.png")
.venv/Lib/site-packages/PIL/IcoImagePlugin.py ADDED
@@ -0,0 +1,358 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # Windows Icon support for PIL
6
+ #
7
+ # History:
8
+ # 96-05-27 fl Created
9
+ #
10
+ # Copyright (c) Secret Labs AB 1997.
11
+ # Copyright (c) Fredrik Lundh 1996.
12
+ #
13
+ # See the README file for information on usage and redistribution.
14
+ #
15
+
16
+ # This plugin is a refactored version of Win32IconImagePlugin by Bryan Davis
17
+ # <casadebender@gmail.com>.
18
+ # https://code.google.com/archive/p/casadebender/wikis/Win32IconImagePlugin.wiki
19
+ #
20
+ # Icon format references:
21
+ # * https://en.wikipedia.org/wiki/ICO_(file_format)
22
+ # * https://msdn.microsoft.com/en-us/library/ms997538.aspx
23
+ from __future__ import annotations
24
+
25
+ import warnings
26
+ from io import BytesIO
27
+ from math import ceil, log
28
+
29
+ from . import BmpImagePlugin, Image, ImageFile, PngImagePlugin
30
+ from ._binary import i16le as i16
31
+ from ._binary import i32le as i32
32
+ from ._binary import o8
33
+ from ._binary import o16le as o16
34
+ from ._binary import o32le as o32
35
+
36
+ #
37
+ # --------------------------------------------------------------------
38
+
39
+ _MAGIC = b"\0\0\1\0"
40
+
41
+
42
+ def _save(im, fp, filename):
43
+ fp.write(_MAGIC) # (2+2)
44
+ bmp = im.encoderinfo.get("bitmap_format") == "bmp"
45
+ sizes = im.encoderinfo.get(
46
+ "sizes",
47
+ [(16, 16), (24, 24), (32, 32), (48, 48), (64, 64), (128, 128), (256, 256)],
48
+ )
49
+ frames = []
50
+ provided_ims = [im] + im.encoderinfo.get("append_images", [])
51
+ width, height = im.size
52
+ for size in sorted(set(sizes)):
53
+ if size[0] > width or size[1] > height or size[0] > 256 or size[1] > 256:
54
+ continue
55
+
56
+ for provided_im in provided_ims:
57
+ if provided_im.size != size:
58
+ continue
59
+ frames.append(provided_im)
60
+ if bmp:
61
+ bits = BmpImagePlugin.SAVE[provided_im.mode][1]
62
+ bits_used = [bits]
63
+ for other_im in provided_ims:
64
+ if other_im.size != size:
65
+ continue
66
+ bits = BmpImagePlugin.SAVE[other_im.mode][1]
67
+ if bits not in bits_used:
68
+ # Another image has been supplied for this size
69
+ # with a different bit depth
70
+ frames.append(other_im)
71
+ bits_used.append(bits)
72
+ break
73
+ else:
74
+ # TODO: invent a more convenient method for proportional scalings
75
+ frame = provided_im.copy()
76
+ frame.thumbnail(size, Image.Resampling.LANCZOS, reducing_gap=None)
77
+ frames.append(frame)
78
+ fp.write(o16(len(frames))) # idCount(2)
79
+ offset = fp.tell() + len(frames) * 16
80
+ for frame in frames:
81
+ width, height = frame.size
82
+ # 0 means 256
83
+ fp.write(o8(width if width < 256 else 0)) # bWidth(1)
84
+ fp.write(o8(height if height < 256 else 0)) # bHeight(1)
85
+
86
+ bits, colors = BmpImagePlugin.SAVE[frame.mode][1:] if bmp else (32, 0)
87
+ fp.write(o8(colors)) # bColorCount(1)
88
+ fp.write(b"\0") # bReserved(1)
89
+ fp.write(b"\0\0") # wPlanes(2)
90
+ fp.write(o16(bits)) # wBitCount(2)
91
+
92
+ image_io = BytesIO()
93
+ if bmp:
94
+ frame.save(image_io, "dib")
95
+
96
+ if bits != 32:
97
+ and_mask = Image.new("1", size)
98
+ ImageFile._save(
99
+ and_mask, image_io, [("raw", (0, 0) + size, 0, ("1", 0, -1))]
100
+ )
101
+ else:
102
+ frame.save(image_io, "png")
103
+ image_io.seek(0)
104
+ image_bytes = image_io.read()
105
+ if bmp:
106
+ image_bytes = image_bytes[:8] + o32(height * 2) + image_bytes[12:]
107
+ bytes_len = len(image_bytes)
108
+ fp.write(o32(bytes_len)) # dwBytesInRes(4)
109
+ fp.write(o32(offset)) # dwImageOffset(4)
110
+ current = fp.tell()
111
+ fp.seek(offset)
112
+ fp.write(image_bytes)
113
+ offset = offset + bytes_len
114
+ fp.seek(current)
115
+
116
+
117
+ def _accept(prefix):
118
+ return prefix[:4] == _MAGIC
119
+
120
+
121
+ class IcoFile:
122
+ def __init__(self, buf):
123
+ """
124
+ Parse image from file-like object containing ico file data
125
+ """
126
+
127
+ # check magic
128
+ s = buf.read(6)
129
+ if not _accept(s):
130
+ msg = "not an ICO file"
131
+ raise SyntaxError(msg)
132
+
133
+ self.buf = buf
134
+ self.entry = []
135
+
136
+ # Number of items in file
137
+ self.nb_items = i16(s, 4)
138
+
139
+ # Get headers for each item
140
+ for i in range(self.nb_items):
141
+ s = buf.read(16)
142
+
143
+ icon_header = {
144
+ "width": s[0],
145
+ "height": s[1],
146
+ "nb_color": s[2], # No. of colors in image (0 if >=8bpp)
147
+ "reserved": s[3],
148
+ "planes": i16(s, 4),
149
+ "bpp": i16(s, 6),
150
+ "size": i32(s, 8),
151
+ "offset": i32(s, 12),
152
+ }
153
+
154
+ # See Wikipedia
155
+ for j in ("width", "height"):
156
+ if not icon_header[j]:
157
+ icon_header[j] = 256
158
+
159
+ # See Wikipedia notes about color depth.
160
+ # We need this just to differ images with equal sizes
161
+ icon_header["color_depth"] = (
162
+ icon_header["bpp"]
163
+ or (
164
+ icon_header["nb_color"] != 0
165
+ and ceil(log(icon_header["nb_color"], 2))
166
+ )
167
+ or 256
168
+ )
169
+
170
+ icon_header["dim"] = (icon_header["width"], icon_header["height"])
171
+ icon_header["square"] = icon_header["width"] * icon_header["height"]
172
+
173
+ self.entry.append(icon_header)
174
+
175
+ self.entry = sorted(self.entry, key=lambda x: x["color_depth"])
176
+ # ICO images are usually squares
177
+ self.entry = sorted(self.entry, key=lambda x: x["square"], reverse=True)
178
+
179
+ def sizes(self):
180
+ """
181
+ Get a list of all available icon sizes and color depths.
182
+ """
183
+ return {(h["width"], h["height"]) for h in self.entry}
184
+
185
+ def getentryindex(self, size, bpp=False):
186
+ for i, h in enumerate(self.entry):
187
+ if size == h["dim"] and (bpp is False or bpp == h["color_depth"]):
188
+ return i
189
+ return 0
190
+
191
+ def getimage(self, size, bpp=False):
192
+ """
193
+ Get an image from the icon
194
+ """
195
+ return self.frame(self.getentryindex(size, bpp))
196
+
197
+ def frame(self, idx):
198
+ """
199
+ Get an image from frame idx
200
+ """
201
+
202
+ header = self.entry[idx]
203
+
204
+ self.buf.seek(header["offset"])
205
+ data = self.buf.read(8)
206
+ self.buf.seek(header["offset"])
207
+
208
+ if data[:8] == PngImagePlugin._MAGIC:
209
+ # png frame
210
+ im = PngImagePlugin.PngImageFile(self.buf)
211
+ Image._decompression_bomb_check(im.size)
212
+ else:
213
+ # XOR + AND mask bmp frame
214
+ im = BmpImagePlugin.DibImageFile(self.buf)
215
+ Image._decompression_bomb_check(im.size)
216
+
217
+ # change tile dimension to only encompass XOR image
218
+ im._size = (im.size[0], int(im.size[1] / 2))
219
+ d, e, o, a = im.tile[0]
220
+ im.tile[0] = d, (0, 0) + im.size, o, a
221
+
222
+ # figure out where AND mask image starts
223
+ bpp = header["bpp"]
224
+ if 32 == bpp:
225
+ # 32-bit color depth icon image allows semitransparent areas
226
+ # PIL's DIB format ignores transparency bits, recover them.
227
+ # The DIB is packed in BGRX byte order where X is the alpha
228
+ # channel.
229
+
230
+ # Back up to start of bmp data
231
+ self.buf.seek(o)
232
+ # extract every 4th byte (eg. 3,7,11,15,...)
233
+ alpha_bytes = self.buf.read(im.size[0] * im.size[1] * 4)[3::4]
234
+
235
+ # convert to an 8bpp grayscale image
236
+ mask = Image.frombuffer(
237
+ "L", # 8bpp
238
+ im.size, # (w, h)
239
+ alpha_bytes, # source chars
240
+ "raw", # raw decoder
241
+ ("L", 0, -1), # 8bpp inverted, unpadded, reversed
242
+ )
243
+ else:
244
+ # get AND image from end of bitmap
245
+ w = im.size[0]
246
+ if (w % 32) > 0:
247
+ # bitmap row data is aligned to word boundaries
248
+ w += 32 - (im.size[0] % 32)
249
+
250
+ # the total mask data is
251
+ # padded row size * height / bits per char
252
+
253
+ total_bytes = int((w * im.size[1]) / 8)
254
+ and_mask_offset = header["offset"] + header["size"] - total_bytes
255
+
256
+ self.buf.seek(and_mask_offset)
257
+ mask_data = self.buf.read(total_bytes)
258
+
259
+ # convert raw data to image
260
+ mask = Image.frombuffer(
261
+ "1", # 1 bpp
262
+ im.size, # (w, h)
263
+ mask_data, # source chars
264
+ "raw", # raw decoder
265
+ ("1;I", int(w / 8), -1), # 1bpp inverted, padded, reversed
266
+ )
267
+
268
+ # now we have two images, im is XOR image and mask is AND image
269
+
270
+ # apply mask image as alpha channel
271
+ im = im.convert("RGBA")
272
+ im.putalpha(mask)
273
+
274
+ return im
275
+
276
+
277
+ ##
278
+ # Image plugin for Windows Icon files.
279
+
280
+
281
+ class IcoImageFile(ImageFile.ImageFile):
282
+ """
283
+ PIL read-only image support for Microsoft Windows .ico files.
284
+
285
+ By default the largest resolution image in the file will be loaded. This
286
+ can be changed by altering the 'size' attribute before calling 'load'.
287
+
288
+ The info dictionary has a key 'sizes' that is a list of the sizes available
289
+ in the icon file.
290
+
291
+ Handles classic, XP and Vista icon formats.
292
+
293
+ When saving, PNG compression is used. Support for this was only added in
294
+ Windows Vista. If you are unable to view the icon in Windows, convert the
295
+ image to "RGBA" mode before saving.
296
+
297
+ This plugin is a refactored version of Win32IconImagePlugin by Bryan Davis
298
+ <casadebender@gmail.com>.
299
+ https://code.google.com/archive/p/casadebender/wikis/Win32IconImagePlugin.wiki
300
+ """
301
+
302
+ format = "ICO"
303
+ format_description = "Windows Icon"
304
+
305
+ def _open(self):
306
+ self.ico = IcoFile(self.fp)
307
+ self.info["sizes"] = self.ico.sizes()
308
+ self.size = self.ico.entry[0]["dim"]
309
+ self.load()
310
+
311
+ @property
312
+ def size(self):
313
+ return self._size
314
+
315
+ @size.setter
316
+ def size(self, value):
317
+ if value not in self.info["sizes"]:
318
+ msg = "This is not one of the allowed sizes of this image"
319
+ raise ValueError(msg)
320
+ self._size = value
321
+
322
+ def load(self):
323
+ if self.im is not None and self.im.size == self.size:
324
+ # Already loaded
325
+ return Image.Image.load(self)
326
+ im = self.ico.getimage(self.size)
327
+ # if tile is PNG, it won't really be loaded yet
328
+ im.load()
329
+ self.im = im.im
330
+ self.pyaccess = None
331
+ self._mode = im.mode
332
+ if im.palette:
333
+ self.palette = im.palette
334
+ if im.size != self.size:
335
+ warnings.warn("Image was not the expected size")
336
+
337
+ index = self.ico.getentryindex(self.size)
338
+ sizes = list(self.info["sizes"])
339
+ sizes[index] = im.size
340
+ self.info["sizes"] = set(sizes)
341
+
342
+ self.size = im.size
343
+
344
+ def load_seek(self, pos):
345
+ # Flag the ImageFile.Parser so that it
346
+ # just does all the decode at the end.
347
+ pass
348
+
349
+
350
+ #
351
+ # --------------------------------------------------------------------
352
+
353
+
354
+ Image.register_open(IcoImageFile.format, IcoImageFile, _accept)
355
+ Image.register_save(IcoImageFile.format, _save)
356
+ Image.register_extension(IcoImageFile.format, ".ico")
357
+
358
+ Image.register_mime(IcoImageFile.format, "image/x-icon")
.venv/Lib/site-packages/PIL/ImImagePlugin.py ADDED
@@ -0,0 +1,371 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # IFUNC IM file handling for PIL
6
+ #
7
+ # history:
8
+ # 1995-09-01 fl Created.
9
+ # 1997-01-03 fl Save palette images
10
+ # 1997-01-08 fl Added sequence support
11
+ # 1997-01-23 fl Added P and RGB save support
12
+ # 1997-05-31 fl Read floating point images
13
+ # 1997-06-22 fl Save floating point images
14
+ # 1997-08-27 fl Read and save 1-bit images
15
+ # 1998-06-25 fl Added support for RGB+LUT images
16
+ # 1998-07-02 fl Added support for YCC images
17
+ # 1998-07-15 fl Renamed offset attribute to avoid name clash
18
+ # 1998-12-29 fl Added I;16 support
19
+ # 2001-02-17 fl Use 're' instead of 'regex' (Python 2.1) (0.7)
20
+ # 2003-09-26 fl Added LA/PA support
21
+ #
22
+ # Copyright (c) 1997-2003 by Secret Labs AB.
23
+ # Copyright (c) 1995-2001 by Fredrik Lundh.
24
+ #
25
+ # See the README file for information on usage and redistribution.
26
+ #
27
+ from __future__ import annotations
28
+
29
+ import os
30
+ import re
31
+
32
+ from . import Image, ImageFile, ImagePalette
33
+
34
+ # --------------------------------------------------------------------
35
+ # Standard tags
36
+
37
+ COMMENT = "Comment"
38
+ DATE = "Date"
39
+ EQUIPMENT = "Digitalization equipment"
40
+ FRAMES = "File size (no of images)"
41
+ LUT = "Lut"
42
+ NAME = "Name"
43
+ SCALE = "Scale (x,y)"
44
+ SIZE = "Image size (x*y)"
45
+ MODE = "Image type"
46
+
47
+ TAGS = {
48
+ COMMENT: 0,
49
+ DATE: 0,
50
+ EQUIPMENT: 0,
51
+ FRAMES: 0,
52
+ LUT: 0,
53
+ NAME: 0,
54
+ SCALE: 0,
55
+ SIZE: 0,
56
+ MODE: 0,
57
+ }
58
+
59
+ OPEN = {
60
+ # ifunc93/p3cfunc formats
61
+ "0 1 image": ("1", "1"),
62
+ "L 1 image": ("1", "1"),
63
+ "Greyscale image": ("L", "L"),
64
+ "Grayscale image": ("L", "L"),
65
+ "RGB image": ("RGB", "RGB;L"),
66
+ "RLB image": ("RGB", "RLB"),
67
+ "RYB image": ("RGB", "RLB"),
68
+ "B1 image": ("1", "1"),
69
+ "B2 image": ("P", "P;2"),
70
+ "B4 image": ("P", "P;4"),
71
+ "X 24 image": ("RGB", "RGB"),
72
+ "L 32 S image": ("I", "I;32"),
73
+ "L 32 F image": ("F", "F;32"),
74
+ # old p3cfunc formats
75
+ "RGB3 image": ("RGB", "RGB;T"),
76
+ "RYB3 image": ("RGB", "RYB;T"),
77
+ # extensions
78
+ "LA image": ("LA", "LA;L"),
79
+ "PA image": ("LA", "PA;L"),
80
+ "RGBA image": ("RGBA", "RGBA;L"),
81
+ "RGBX image": ("RGBX", "RGBX;L"),
82
+ "CMYK image": ("CMYK", "CMYK;L"),
83
+ "YCC image": ("YCbCr", "YCbCr;L"),
84
+ }
85
+
86
+ # ifunc95 extensions
87
+ for i in ["8", "8S", "16", "16S", "32", "32F"]:
88
+ OPEN[f"L {i} image"] = ("F", f"F;{i}")
89
+ OPEN[f"L*{i} image"] = ("F", f"F;{i}")
90
+ for i in ["16", "16L", "16B"]:
91
+ OPEN[f"L {i} image"] = (f"I;{i}", f"I;{i}")
92
+ OPEN[f"L*{i} image"] = (f"I;{i}", f"I;{i}")
93
+ for i in ["32S"]:
94
+ OPEN[f"L {i} image"] = ("I", f"I;{i}")
95
+ OPEN[f"L*{i} image"] = ("I", f"I;{i}")
96
+ for j in range(2, 33):
97
+ OPEN[f"L*{j} image"] = ("F", f"F;{j}")
98
+
99
+
100
+ # --------------------------------------------------------------------
101
+ # Read IM directory
102
+
103
+ split = re.compile(rb"^([A-Za-z][^:]*):[ \t]*(.*)[ \t]*$")
104
+
105
+
106
+ def number(s):
107
+ try:
108
+ return int(s)
109
+ except ValueError:
110
+ return float(s)
111
+
112
+
113
+ ##
114
+ # Image plugin for the IFUNC IM file format.
115
+
116
+
117
+ class ImImageFile(ImageFile.ImageFile):
118
+ format = "IM"
119
+ format_description = "IFUNC Image Memory"
120
+ _close_exclusive_fp_after_loading = False
121
+
122
+ def _open(self):
123
+ # Quick rejection: if there's not an LF among the first
124
+ # 100 bytes, this is (probably) not a text header.
125
+
126
+ if b"\n" not in self.fp.read(100):
127
+ msg = "not an IM file"
128
+ raise SyntaxError(msg)
129
+ self.fp.seek(0)
130
+
131
+ n = 0
132
+
133
+ # Default values
134
+ self.info[MODE] = "L"
135
+ self.info[SIZE] = (512, 512)
136
+ self.info[FRAMES] = 1
137
+
138
+ self.rawmode = "L"
139
+
140
+ while True:
141
+ s = self.fp.read(1)
142
+
143
+ # Some versions of IFUNC uses \n\r instead of \r\n...
144
+ if s == b"\r":
145
+ continue
146
+
147
+ if not s or s == b"\0" or s == b"\x1A":
148
+ break
149
+
150
+ # FIXME: this may read whole file if not a text file
151
+ s = s + self.fp.readline()
152
+
153
+ if len(s) > 100:
154
+ msg = "not an IM file"
155
+ raise SyntaxError(msg)
156
+
157
+ if s[-2:] == b"\r\n":
158
+ s = s[:-2]
159
+ elif s[-1:] == b"\n":
160
+ s = s[:-1]
161
+
162
+ try:
163
+ m = split.match(s)
164
+ except re.error as e:
165
+ msg = "not an IM file"
166
+ raise SyntaxError(msg) from e
167
+
168
+ if m:
169
+ k, v = m.group(1, 2)
170
+
171
+ # Don't know if this is the correct encoding,
172
+ # but a decent guess (I guess)
173
+ k = k.decode("latin-1", "replace")
174
+ v = v.decode("latin-1", "replace")
175
+
176
+ # Convert value as appropriate
177
+ if k in [FRAMES, SCALE, SIZE]:
178
+ v = v.replace("*", ",")
179
+ v = tuple(map(number, v.split(",")))
180
+ if len(v) == 1:
181
+ v = v[0]
182
+ elif k == MODE and v in OPEN:
183
+ v, self.rawmode = OPEN[v]
184
+
185
+ # Add to dictionary. Note that COMMENT tags are
186
+ # combined into a list of strings.
187
+ if k == COMMENT:
188
+ if k in self.info:
189
+ self.info[k].append(v)
190
+ else:
191
+ self.info[k] = [v]
192
+ else:
193
+ self.info[k] = v
194
+
195
+ if k in TAGS:
196
+ n += 1
197
+
198
+ else:
199
+ msg = "Syntax error in IM header: " + s.decode("ascii", "replace")
200
+ raise SyntaxError(msg)
201
+
202
+ if not n:
203
+ msg = "Not an IM file"
204
+ raise SyntaxError(msg)
205
+
206
+ # Basic attributes
207
+ self._size = self.info[SIZE]
208
+ self._mode = self.info[MODE]
209
+
210
+ # Skip forward to start of image data
211
+ while s and s[:1] != b"\x1A":
212
+ s = self.fp.read(1)
213
+ if not s:
214
+ msg = "File truncated"
215
+ raise SyntaxError(msg)
216
+
217
+ if LUT in self.info:
218
+ # convert lookup table to palette or lut attribute
219
+ palette = self.fp.read(768)
220
+ greyscale = 1 # greyscale palette
221
+ linear = 1 # linear greyscale palette
222
+ for i in range(256):
223
+ if palette[i] == palette[i + 256] == palette[i + 512]:
224
+ if palette[i] != i:
225
+ linear = 0
226
+ else:
227
+ greyscale = 0
228
+ if self.mode in ["L", "LA", "P", "PA"]:
229
+ if greyscale:
230
+ if not linear:
231
+ self.lut = list(palette[:256])
232
+ else:
233
+ if self.mode in ["L", "P"]:
234
+ self._mode = self.rawmode = "P"
235
+ elif self.mode in ["LA", "PA"]:
236
+ self._mode = "PA"
237
+ self.rawmode = "PA;L"
238
+ self.palette = ImagePalette.raw("RGB;L", palette)
239
+ elif self.mode == "RGB":
240
+ if not greyscale or not linear:
241
+ self.lut = list(palette)
242
+
243
+ self.frame = 0
244
+
245
+ self.__offset = offs = self.fp.tell()
246
+
247
+ self._fp = self.fp # FIXME: hack
248
+
249
+ if self.rawmode[:2] == "F;":
250
+ # ifunc95 formats
251
+ try:
252
+ # use bit decoder (if necessary)
253
+ bits = int(self.rawmode[2:])
254
+ if bits not in [8, 16, 32]:
255
+ self.tile = [("bit", (0, 0) + self.size, offs, (bits, 8, 3, 0, -1))]
256
+ return
257
+ except ValueError:
258
+ pass
259
+
260
+ if self.rawmode in ["RGB;T", "RYB;T"]:
261
+ # Old LabEye/3PC files. Would be very surprised if anyone
262
+ # ever stumbled upon such a file ;-)
263
+ size = self.size[0] * self.size[1]
264
+ self.tile = [
265
+ ("raw", (0, 0) + self.size, offs, ("G", 0, -1)),
266
+ ("raw", (0, 0) + self.size, offs + size, ("R", 0, -1)),
267
+ ("raw", (0, 0) + self.size, offs + 2 * size, ("B", 0, -1)),
268
+ ]
269
+ else:
270
+ # LabEye/IFUNC files
271
+ self.tile = [("raw", (0, 0) + self.size, offs, (self.rawmode, 0, -1))]
272
+
273
+ @property
274
+ def n_frames(self):
275
+ return self.info[FRAMES]
276
+
277
+ @property
278
+ def is_animated(self):
279
+ return self.info[FRAMES] > 1
280
+
281
+ def seek(self, frame):
282
+ if not self._seek_check(frame):
283
+ return
284
+
285
+ self.frame = frame
286
+
287
+ if self.mode == "1":
288
+ bits = 1
289
+ else:
290
+ bits = 8 * len(self.mode)
291
+
292
+ size = ((self.size[0] * bits + 7) // 8) * self.size[1]
293
+ offs = self.__offset + frame * size
294
+
295
+ self.fp = self._fp
296
+
297
+ self.tile = [("raw", (0, 0) + self.size, offs, (self.rawmode, 0, -1))]
298
+
299
+ def tell(self):
300
+ return self.frame
301
+
302
+
303
+ #
304
+ # --------------------------------------------------------------------
305
+ # Save IM files
306
+
307
+
308
+ SAVE = {
309
+ # mode: (im type, raw mode)
310
+ "1": ("0 1", "1"),
311
+ "L": ("Greyscale", "L"),
312
+ "LA": ("LA", "LA;L"),
313
+ "P": ("Greyscale", "P"),
314
+ "PA": ("LA", "PA;L"),
315
+ "I": ("L 32S", "I;32S"),
316
+ "I;16": ("L 16", "I;16"),
317
+ "I;16L": ("L 16L", "I;16L"),
318
+ "I;16B": ("L 16B", "I;16B"),
319
+ "F": ("L 32F", "F;32F"),
320
+ "RGB": ("RGB", "RGB;L"),
321
+ "RGBA": ("RGBA", "RGBA;L"),
322
+ "RGBX": ("RGBX", "RGBX;L"),
323
+ "CMYK": ("CMYK", "CMYK;L"),
324
+ "YCbCr": ("YCC", "YCbCr;L"),
325
+ }
326
+
327
+
328
+ def _save(im, fp, filename):
329
+ try:
330
+ image_type, rawmode = SAVE[im.mode]
331
+ except KeyError as e:
332
+ msg = f"Cannot save {im.mode} images as IM"
333
+ raise ValueError(msg) from e
334
+
335
+ frames = im.encoderinfo.get("frames", 1)
336
+
337
+ fp.write(f"Image type: {image_type} image\r\n".encode("ascii"))
338
+ if filename:
339
+ # Each line must be 100 characters or less,
340
+ # or: SyntaxError("not an IM file")
341
+ # 8 characters are used for "Name: " and "\r\n"
342
+ # Keep just the filename, ditch the potentially overlong path
343
+ name, ext = os.path.splitext(os.path.basename(filename))
344
+ name = "".join([name[: 92 - len(ext)], ext])
345
+
346
+ fp.write(f"Name: {name}\r\n".encode("ascii"))
347
+ fp.write(("Image size (x*y): %d*%d\r\n" % im.size).encode("ascii"))
348
+ fp.write(f"File size (no of images): {frames}\r\n".encode("ascii"))
349
+ if im.mode in ["P", "PA"]:
350
+ fp.write(b"Lut: 1\r\n")
351
+ fp.write(b"\000" * (511 - fp.tell()) + b"\032")
352
+ if im.mode in ["P", "PA"]:
353
+ im_palette = im.im.getpalette("RGB", "RGB;L")
354
+ colors = len(im_palette) // 3
355
+ palette = b""
356
+ for i in range(3):
357
+ palette += im_palette[colors * i : colors * (i + 1)]
358
+ palette += b"\x00" * (256 - colors)
359
+ fp.write(palette) # 768 bytes
360
+ ImageFile._save(im, fp, [("raw", (0, 0) + im.size, 0, (rawmode, 0, -1))])
361
+
362
+
363
+ #
364
+ # --------------------------------------------------------------------
365
+ # Registry
366
+
367
+
368
+ Image.register_open(ImImageFile.format, ImImageFile)
369
+ Image.register_save(ImImageFile.format, _save)
370
+
371
+ Image.register_extension(ImImageFile.format, ".im")
.venv/Lib/site-packages/PIL/Image.py ADDED
The diff for this file is too large to render. See raw diff
 
.venv/Lib/site-packages/PIL/ImageChops.py ADDED
@@ -0,0 +1,311 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # standard channel operations
6
+ #
7
+ # History:
8
+ # 1996-03-24 fl Created
9
+ # 1996-08-13 fl Added logical operations (for "1" images)
10
+ # 2000-10-12 fl Added offset method (from Image.py)
11
+ #
12
+ # Copyright (c) 1997-2000 by Secret Labs AB
13
+ # Copyright (c) 1996-2000 by Fredrik Lundh
14
+ #
15
+ # See the README file for information on usage and redistribution.
16
+ #
17
+
18
+ from __future__ import annotations
19
+
20
+ from . import Image
21
+
22
+
23
+ def constant(image: Image.Image, value: int) -> Image.Image:
24
+ """Fill a channel with a given gray level.
25
+
26
+ :rtype: :py:class:`~PIL.Image.Image`
27
+ """
28
+
29
+ return Image.new("L", image.size, value)
30
+
31
+
32
+ def duplicate(image: Image.Image) -> Image.Image:
33
+ """Copy a channel. Alias for :py:meth:`PIL.Image.Image.copy`.
34
+
35
+ :rtype: :py:class:`~PIL.Image.Image`
36
+ """
37
+
38
+ return image.copy()
39
+
40
+
41
+ def invert(image: Image.Image) -> Image.Image:
42
+ """
43
+ Invert an image (channel). ::
44
+
45
+ out = MAX - image
46
+
47
+ :rtype: :py:class:`~PIL.Image.Image`
48
+ """
49
+
50
+ image.load()
51
+ return image._new(image.im.chop_invert())
52
+
53
+
54
+ def lighter(image1: Image.Image, image2: Image.Image) -> Image.Image:
55
+ """
56
+ Compares the two images, pixel by pixel, and returns a new image containing
57
+ the lighter values. ::
58
+
59
+ out = max(image1, image2)
60
+
61
+ :rtype: :py:class:`~PIL.Image.Image`
62
+ """
63
+
64
+ image1.load()
65
+ image2.load()
66
+ return image1._new(image1.im.chop_lighter(image2.im))
67
+
68
+
69
+ def darker(image1: Image.Image, image2: Image.Image) -> Image.Image:
70
+ """
71
+ Compares the two images, pixel by pixel, and returns a new image containing
72
+ the darker values. ::
73
+
74
+ out = min(image1, image2)
75
+
76
+ :rtype: :py:class:`~PIL.Image.Image`
77
+ """
78
+
79
+ image1.load()
80
+ image2.load()
81
+ return image1._new(image1.im.chop_darker(image2.im))
82
+
83
+
84
+ def difference(image1: Image.Image, image2: Image.Image) -> Image.Image:
85
+ """
86
+ Returns the absolute value of the pixel-by-pixel difference between the two
87
+ images. ::
88
+
89
+ out = abs(image1 - image2)
90
+
91
+ :rtype: :py:class:`~PIL.Image.Image`
92
+ """
93
+
94
+ image1.load()
95
+ image2.load()
96
+ return image1._new(image1.im.chop_difference(image2.im))
97
+
98
+
99
+ def multiply(image1: Image.Image, image2: Image.Image) -> Image.Image:
100
+ """
101
+ Superimposes two images on top of each other.
102
+
103
+ If you multiply an image with a solid black image, the result is black. If
104
+ you multiply with a solid white image, the image is unaffected. ::
105
+
106
+ out = image1 * image2 / MAX
107
+
108
+ :rtype: :py:class:`~PIL.Image.Image`
109
+ """
110
+
111
+ image1.load()
112
+ image2.load()
113
+ return image1._new(image1.im.chop_multiply(image2.im))
114
+
115
+
116
+ def screen(image1: Image.Image, image2: Image.Image) -> Image.Image:
117
+ """
118
+ Superimposes two inverted images on top of each other. ::
119
+
120
+ out = MAX - ((MAX - image1) * (MAX - image2) / MAX)
121
+
122
+ :rtype: :py:class:`~PIL.Image.Image`
123
+ """
124
+
125
+ image1.load()
126
+ image2.load()
127
+ return image1._new(image1.im.chop_screen(image2.im))
128
+
129
+
130
+ def soft_light(image1: Image.Image, image2: Image.Image) -> Image.Image:
131
+ """
132
+ Superimposes two images on top of each other using the Soft Light algorithm
133
+
134
+ :rtype: :py:class:`~PIL.Image.Image`
135
+ """
136
+
137
+ image1.load()
138
+ image2.load()
139
+ return image1._new(image1.im.chop_soft_light(image2.im))
140
+
141
+
142
+ def hard_light(image1: Image.Image, image2: Image.Image) -> Image.Image:
143
+ """
144
+ Superimposes two images on top of each other using the Hard Light algorithm
145
+
146
+ :rtype: :py:class:`~PIL.Image.Image`
147
+ """
148
+
149
+ image1.load()
150
+ image2.load()
151
+ return image1._new(image1.im.chop_hard_light(image2.im))
152
+
153
+
154
+ def overlay(image1: Image.Image, image2: Image.Image) -> Image.Image:
155
+ """
156
+ Superimposes two images on top of each other using the Overlay algorithm
157
+
158
+ :rtype: :py:class:`~PIL.Image.Image`
159
+ """
160
+
161
+ image1.load()
162
+ image2.load()
163
+ return image1._new(image1.im.chop_overlay(image2.im))
164
+
165
+
166
+ def add(
167
+ image1: Image.Image, image2: Image.Image, scale: float = 1.0, offset: float = 0
168
+ ) -> Image.Image:
169
+ """
170
+ Adds two images, dividing the result by scale and adding the
171
+ offset. If omitted, scale defaults to 1.0, and offset to 0.0. ::
172
+
173
+ out = ((image1 + image2) / scale + offset)
174
+
175
+ :rtype: :py:class:`~PIL.Image.Image`
176
+ """
177
+
178
+ image1.load()
179
+ image2.load()
180
+ return image1._new(image1.im.chop_add(image2.im, scale, offset))
181
+
182
+
183
+ def subtract(
184
+ image1: Image.Image, image2: Image.Image, scale: float = 1.0, offset: float = 0
185
+ ) -> Image.Image:
186
+ """
187
+ Subtracts two images, dividing the result by scale and adding the offset.
188
+ If omitted, scale defaults to 1.0, and offset to 0.0. ::
189
+
190
+ out = ((image1 - image2) / scale + offset)
191
+
192
+ :rtype: :py:class:`~PIL.Image.Image`
193
+ """
194
+
195
+ image1.load()
196
+ image2.load()
197
+ return image1._new(image1.im.chop_subtract(image2.im, scale, offset))
198
+
199
+
200
+ def add_modulo(image1: Image.Image, image2: Image.Image) -> Image.Image:
201
+ """Add two images, without clipping the result. ::
202
+
203
+ out = ((image1 + image2) % MAX)
204
+
205
+ :rtype: :py:class:`~PIL.Image.Image`
206
+ """
207
+
208
+ image1.load()
209
+ image2.load()
210
+ return image1._new(image1.im.chop_add_modulo(image2.im))
211
+
212
+
213
+ def subtract_modulo(image1: Image.Image, image2: Image.Image) -> Image.Image:
214
+ """Subtract two images, without clipping the result. ::
215
+
216
+ out = ((image1 - image2) % MAX)
217
+
218
+ :rtype: :py:class:`~PIL.Image.Image`
219
+ """
220
+
221
+ image1.load()
222
+ image2.load()
223
+ return image1._new(image1.im.chop_subtract_modulo(image2.im))
224
+
225
+
226
+ def logical_and(image1: Image.Image, image2: Image.Image) -> Image.Image:
227
+ """Logical AND between two images.
228
+
229
+ Both of the images must have mode "1". If you would like to perform a
230
+ logical AND on an image with a mode other than "1", try
231
+ :py:meth:`~PIL.ImageChops.multiply` instead, using a black-and-white mask
232
+ as the second image. ::
233
+
234
+ out = ((image1 and image2) % MAX)
235
+
236
+ :rtype: :py:class:`~PIL.Image.Image`
237
+ """
238
+
239
+ image1.load()
240
+ image2.load()
241
+ return image1._new(image1.im.chop_and(image2.im))
242
+
243
+
244
+ def logical_or(image1: Image.Image, image2: Image.Image) -> Image.Image:
245
+ """Logical OR between two images.
246
+
247
+ Both of the images must have mode "1". ::
248
+
249
+ out = ((image1 or image2) % MAX)
250
+
251
+ :rtype: :py:class:`~PIL.Image.Image`
252
+ """
253
+
254
+ image1.load()
255
+ image2.load()
256
+ return image1._new(image1.im.chop_or(image2.im))
257
+
258
+
259
+ def logical_xor(image1: Image.Image, image2: Image.Image) -> Image.Image:
260
+ """Logical XOR between two images.
261
+
262
+ Both of the images must have mode "1". ::
263
+
264
+ out = ((bool(image1) != bool(image2)) % MAX)
265
+
266
+ :rtype: :py:class:`~PIL.Image.Image`
267
+ """
268
+
269
+ image1.load()
270
+ image2.load()
271
+ return image1._new(image1.im.chop_xor(image2.im))
272
+
273
+
274
+ def blend(image1: Image.Image, image2: Image.Image, alpha: float) -> Image.Image:
275
+ """Blend images using constant transparency weight. Alias for
276
+ :py:func:`PIL.Image.blend`.
277
+
278
+ :rtype: :py:class:`~PIL.Image.Image`
279
+ """
280
+
281
+ return Image.blend(image1, image2, alpha)
282
+
283
+
284
+ def composite(
285
+ image1: Image.Image, image2: Image.Image, mask: Image.Image
286
+ ) -> Image.Image:
287
+ """Create composite using transparency mask. Alias for
288
+ :py:func:`PIL.Image.composite`.
289
+
290
+ :rtype: :py:class:`~PIL.Image.Image`
291
+ """
292
+
293
+ return Image.composite(image1, image2, mask)
294
+
295
+
296
+ def offset(image: Image.Image, xoffset: int, yoffset: int | None = None) -> Image.Image:
297
+ """Returns a copy of the image where data has been offset by the given
298
+ distances. Data wraps around the edges. If ``yoffset`` is omitted, it
299
+ is assumed to be equal to ``xoffset``.
300
+
301
+ :param image: Input image.
302
+ :param xoffset: The horizontal distance.
303
+ :param yoffset: The vertical distance. If omitted, both
304
+ distances are set to the same value.
305
+ :rtype: :py:class:`~PIL.Image.Image`
306
+ """
307
+
308
+ if yoffset is None:
309
+ yoffset = xoffset
310
+ image.load()
311
+ return image._new(image.im.offset(xoffset, yoffset))
.venv/Lib/site-packages/PIL/ImageCms.py ADDED
@@ -0,0 +1,1102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # The Python Imaging Library.
2
+ # $Id$
3
+
4
+ # Optional color management support, based on Kevin Cazabon's PyCMS
5
+ # library.
6
+
7
+ # Originally released under LGPL. Graciously donated to PIL in
8
+ # March 2009, for distribution under the standard PIL license
9
+
10
+ # History:
11
+
12
+ # 2009-03-08 fl Added to PIL.
13
+
14
+ # Copyright (C) 2002-2003 Kevin Cazabon
15
+ # Copyright (c) 2009 by Fredrik Lundh
16
+ # Copyright (c) 2013 by Eric Soroos
17
+
18
+ # See the README file for information on usage and redistribution. See
19
+ # below for the original description.
20
+ from __future__ import annotations
21
+
22
+ import operator
23
+ import sys
24
+ from enum import IntEnum, IntFlag
25
+ from functools import reduce
26
+ from typing import Any, Literal, SupportsFloat, SupportsInt, Union
27
+
28
+ from . import Image, __version__
29
+ from ._deprecate import deprecate
30
+ from ._typing import SupportsRead
31
+
32
+ try:
33
+ from . import _imagingcms as core
34
+ except ImportError as ex:
35
+ # Allow error import for doc purposes, but error out when accessing
36
+ # anything in core.
37
+ from ._util import DeferredError
38
+
39
+ core = DeferredError.new(ex)
40
+
41
+ _DESCRIPTION = """
42
+ pyCMS
43
+
44
+ a Python / PIL interface to the littleCMS ICC Color Management System
45
+ Copyright (C) 2002-2003 Kevin Cazabon
46
+ kevin@cazabon.com
47
+ https://www.cazabon.com
48
+
49
+ pyCMS home page: https://www.cazabon.com/pyCMS
50
+ littleCMS home page: https://www.littlecms.com
51
+ (littleCMS is Copyright (C) 1998-2001 Marti Maria)
52
+
53
+ Originally released under LGPL. Graciously donated to PIL in
54
+ March 2009, for distribution under the standard PIL license
55
+
56
+ The pyCMS.py module provides a "clean" interface between Python/PIL and
57
+ pyCMSdll, taking care of some of the more complex handling of the direct
58
+ pyCMSdll functions, as well as error-checking and making sure that all
59
+ relevant data is kept together.
60
+
61
+ While it is possible to call pyCMSdll functions directly, it's not highly
62
+ recommended.
63
+
64
+ Version History:
65
+
66
+ 1.0.0 pil Oct 2013 Port to LCMS 2.
67
+
68
+ 0.1.0 pil mod March 10, 2009
69
+
70
+ Renamed display profile to proof profile. The proof
71
+ profile is the profile of the device that is being
72
+ simulated, not the profile of the device which is
73
+ actually used to display/print the final simulation
74
+ (that'd be the output profile) - also see LCMSAPI.txt
75
+ input colorspace -> using 'renderingIntent' -> proof
76
+ colorspace -> using 'proofRenderingIntent' -> output
77
+ colorspace
78
+
79
+ Added LCMS FLAGS support.
80
+ Added FLAGS["SOFTPROOFING"] as default flag for
81
+ buildProofTransform (otherwise the proof profile/intent
82
+ would be ignored).
83
+
84
+ 0.1.0 pil March 2009 - added to PIL, as PIL.ImageCms
85
+
86
+ 0.0.2 alpha Jan 6, 2002
87
+
88
+ Added try/except statements around type() checks of
89
+ potential CObjects... Python won't let you use type()
90
+ on them, and raises a TypeError (stupid, if you ask
91
+ me!)
92
+
93
+ Added buildProofTransformFromOpenProfiles() function.
94
+ Additional fixes in DLL, see DLL code for details.
95
+
96
+ 0.0.1 alpha first public release, Dec. 26, 2002
97
+
98
+ Known to-do list with current version (of Python interface, not pyCMSdll):
99
+
100
+ none
101
+
102
+ """
103
+
104
+ _VERSION = "1.0.0 pil"
105
+
106
+
107
+ def __getattr__(name: str) -> Any:
108
+ if name == "DESCRIPTION":
109
+ deprecate("PIL.ImageCms.DESCRIPTION", 12)
110
+ return _DESCRIPTION
111
+ elif name == "VERSION":
112
+ deprecate("PIL.ImageCms.VERSION", 12)
113
+ return _VERSION
114
+ elif name == "FLAGS":
115
+ deprecate("PIL.ImageCms.FLAGS", 12, "PIL.ImageCms.Flags")
116
+ return _FLAGS
117
+ msg = f"module '{__name__}' has no attribute '{name}'"
118
+ raise AttributeError(msg)
119
+
120
+
121
+ # --------------------------------------------------------------------.
122
+
123
+
124
+ #
125
+ # intent/direction values
126
+
127
+
128
+ class Intent(IntEnum):
129
+ PERCEPTUAL = 0
130
+ RELATIVE_COLORIMETRIC = 1
131
+ SATURATION = 2
132
+ ABSOLUTE_COLORIMETRIC = 3
133
+
134
+
135
+ class Direction(IntEnum):
136
+ INPUT = 0
137
+ OUTPUT = 1
138
+ PROOF = 2
139
+
140
+
141
+ #
142
+ # flags
143
+
144
+
145
+ class Flags(IntFlag):
146
+ """Flags and documentation are taken from ``lcms2.h``."""
147
+
148
+ NONE = 0
149
+ NOCACHE = 0x0040
150
+ """Inhibit 1-pixel cache"""
151
+ NOOPTIMIZE = 0x0100
152
+ """Inhibit optimizations"""
153
+ NULLTRANSFORM = 0x0200
154
+ """Don't transform anyway"""
155
+ GAMUTCHECK = 0x1000
156
+ """Out of Gamut alarm"""
157
+ SOFTPROOFING = 0x4000
158
+ """Do softproofing"""
159
+ BLACKPOINTCOMPENSATION = 0x2000
160
+ NOWHITEONWHITEFIXUP = 0x0004
161
+ """Don't fix scum dot"""
162
+ HIGHRESPRECALC = 0x0400
163
+ """Use more memory to give better accuracy"""
164
+ LOWRESPRECALC = 0x0800
165
+ """Use less memory to minimize resources"""
166
+ # this should be 8BITS_DEVICELINK, but that is not a valid name in Python:
167
+ USE_8BITS_DEVICELINK = 0x0008
168
+ """Create 8 bits devicelinks"""
169
+ GUESSDEVICECLASS = 0x0020
170
+ """Guess device class (for ``transform2devicelink``)"""
171
+ KEEP_SEQUENCE = 0x0080
172
+ """Keep profile sequence for devicelink creation"""
173
+ FORCE_CLUT = 0x0002
174
+ """Force CLUT optimization"""
175
+ CLUT_POST_LINEARIZATION = 0x0001
176
+ """create postlinearization tables if possible"""
177
+ CLUT_PRE_LINEARIZATION = 0x0010
178
+ """create prelinearization tables if possible"""
179
+ NONEGATIVES = 0x8000
180
+ """Prevent negative numbers in floating point transforms"""
181
+ COPY_ALPHA = 0x04000000
182
+ """Alpha channels are copied on ``cmsDoTransform()``"""
183
+ NODEFAULTRESOURCEDEF = 0x01000000
184
+
185
+ _GRIDPOINTS_1 = 1 << 16
186
+ _GRIDPOINTS_2 = 2 << 16
187
+ _GRIDPOINTS_4 = 4 << 16
188
+ _GRIDPOINTS_8 = 8 << 16
189
+ _GRIDPOINTS_16 = 16 << 16
190
+ _GRIDPOINTS_32 = 32 << 16
191
+ _GRIDPOINTS_64 = 64 << 16
192
+ _GRIDPOINTS_128 = 128 << 16
193
+
194
+ @staticmethod
195
+ def GRIDPOINTS(n: int) -> Flags:
196
+ """
197
+ Fine-tune control over number of gridpoints
198
+
199
+ :param n: :py:class:`int` in range ``0 <= n <= 255``
200
+ """
201
+ return Flags.NONE | ((n & 0xFF) << 16)
202
+
203
+
204
+ _MAX_FLAG = reduce(operator.or_, Flags)
205
+
206
+
207
+ _FLAGS = {
208
+ "MATRIXINPUT": 1,
209
+ "MATRIXOUTPUT": 2,
210
+ "MATRIXONLY": (1 | 2),
211
+ "NOWHITEONWHITEFIXUP": 4, # Don't hot fix scum dot
212
+ # Don't create prelinearization tables on precalculated transforms
213
+ # (internal use):
214
+ "NOPRELINEARIZATION": 16,
215
+ "GUESSDEVICECLASS": 32, # Guess device class (for transform2devicelink)
216
+ "NOTCACHE": 64, # Inhibit 1-pixel cache
217
+ "NOTPRECALC": 256,
218
+ "NULLTRANSFORM": 512, # Don't transform anyway
219
+ "HIGHRESPRECALC": 1024, # Use more memory to give better accuracy
220
+ "LOWRESPRECALC": 2048, # Use less memory to minimize resources
221
+ "WHITEBLACKCOMPENSATION": 8192,
222
+ "BLACKPOINTCOMPENSATION": 8192,
223
+ "GAMUTCHECK": 4096, # Out of Gamut alarm
224
+ "SOFTPROOFING": 16384, # Do softproofing
225
+ "PRESERVEBLACK": 32768, # Black preservation
226
+ "NODEFAULTRESOURCEDEF": 16777216, # CRD special
227
+ "GRIDPOINTS": lambda n: (n & 0xFF) << 16, # Gridpoints
228
+ }
229
+
230
+
231
+ # --------------------------------------------------------------------.
232
+ # Experimental PIL-level API
233
+ # --------------------------------------------------------------------.
234
+
235
+ ##
236
+ # Profile.
237
+
238
+
239
+ class ImageCmsProfile:
240
+ def __init__(self, profile: str | SupportsRead[bytes] | core.CmsProfile) -> None:
241
+ """
242
+ :param profile: Either a string representing a filename,
243
+ a file like object containing a profile or a
244
+ low-level profile object
245
+
246
+ """
247
+
248
+ if isinstance(profile, str):
249
+ if sys.platform == "win32":
250
+ profile_bytes_path = profile.encode()
251
+ try:
252
+ profile_bytes_path.decode("ascii")
253
+ except UnicodeDecodeError:
254
+ with open(profile, "rb") as f:
255
+ self._set(core.profile_frombytes(f.read()))
256
+ return
257
+ self._set(core.profile_open(profile), profile)
258
+ elif hasattr(profile, "read"):
259
+ self._set(core.profile_frombytes(profile.read()))
260
+ elif isinstance(profile, core.CmsProfile):
261
+ self._set(profile)
262
+ else:
263
+ msg = "Invalid type for Profile" # type: ignore[unreachable]
264
+ raise TypeError(msg)
265
+
266
+ def _set(self, profile: core.CmsProfile, filename: str | None = None) -> None:
267
+ self.profile = profile
268
+ self.filename = filename
269
+ self.product_name = None # profile.product_name
270
+ self.product_info = None # profile.product_info
271
+
272
+ def tobytes(self) -> bytes:
273
+ """
274
+ Returns the profile in a format suitable for embedding in
275
+ saved images.
276
+
277
+ :returns: a bytes object containing the ICC profile.
278
+ """
279
+
280
+ return core.profile_tobytes(self.profile)
281
+
282
+
283
+ class ImageCmsTransform(Image.ImagePointHandler):
284
+ """
285
+ Transform. This can be used with the procedural API, or with the standard
286
+ :py:func:`~PIL.Image.Image.point` method.
287
+
288
+ Will return the output profile in the ``output.info['icc_profile']``.
289
+ """
290
+
291
+ def __init__(
292
+ self,
293
+ input: ImageCmsProfile,
294
+ output: ImageCmsProfile,
295
+ input_mode: str,
296
+ output_mode: str,
297
+ intent: Intent = Intent.PERCEPTUAL,
298
+ proof: ImageCmsProfile | None = None,
299
+ proof_intent: Intent = Intent.ABSOLUTE_COLORIMETRIC,
300
+ flags: Flags = Flags.NONE,
301
+ ):
302
+ if proof is None:
303
+ self.transform = core.buildTransform(
304
+ input.profile, output.profile, input_mode, output_mode, intent, flags
305
+ )
306
+ else:
307
+ self.transform = core.buildProofTransform(
308
+ input.profile,
309
+ output.profile,
310
+ proof.profile,
311
+ input_mode,
312
+ output_mode,
313
+ intent,
314
+ proof_intent,
315
+ flags,
316
+ )
317
+ # Note: inputMode and outputMode are for pyCMS compatibility only
318
+ self.input_mode = self.inputMode = input_mode
319
+ self.output_mode = self.outputMode = output_mode
320
+
321
+ self.output_profile = output
322
+
323
+ def point(self, im: Image.Image) -> Image.Image:
324
+ return self.apply(im)
325
+
326
+ def apply(self, im: Image.Image, imOut: Image.Image | None = None) -> Image.Image:
327
+ im.load()
328
+ if imOut is None:
329
+ imOut = Image.new(self.output_mode, im.size, None)
330
+ self.transform.apply(im.im.id, imOut.im.id)
331
+ imOut.info["icc_profile"] = self.output_profile.tobytes()
332
+ return imOut
333
+
334
+ def apply_in_place(self, im: Image.Image) -> Image.Image:
335
+ im.load()
336
+ if im.mode != self.output_mode:
337
+ msg = "mode mismatch"
338
+ raise ValueError(msg) # wrong output mode
339
+ self.transform.apply(im.im.id, im.im.id)
340
+ im.info["icc_profile"] = self.output_profile.tobytes()
341
+ return im
342
+
343
+
344
+ def get_display_profile(handle: SupportsInt | None = None) -> ImageCmsProfile | None:
345
+ """
346
+ (experimental) Fetches the profile for the current display device.
347
+
348
+ :returns: ``None`` if the profile is not known.
349
+ """
350
+
351
+ if sys.platform != "win32":
352
+ return None
353
+
354
+ from . import ImageWin # type: ignore[unused-ignore, unreachable]
355
+
356
+ if isinstance(handle, ImageWin.HDC):
357
+ profile = core.get_display_profile_win32(int(handle), 1)
358
+ else:
359
+ profile = core.get_display_profile_win32(int(handle or 0))
360
+ if profile is None:
361
+ return None
362
+ return ImageCmsProfile(profile)
363
+
364
+
365
+ # --------------------------------------------------------------------.
366
+ # pyCMS compatible layer
367
+ # --------------------------------------------------------------------.
368
+
369
+ _CmsProfileCompatible = Union[
370
+ str, SupportsRead[bytes], core.CmsProfile, ImageCmsProfile
371
+ ]
372
+
373
+
374
+ class PyCMSError(Exception):
375
+ """(pyCMS) Exception class.
376
+ This is used for all errors in the pyCMS API."""
377
+
378
+ pass
379
+
380
+
381
+ def profileToProfile(
382
+ im: Image.Image,
383
+ inputProfile: _CmsProfileCompatible,
384
+ outputProfile: _CmsProfileCompatible,
385
+ renderingIntent: Intent = Intent.PERCEPTUAL,
386
+ outputMode: str | None = None,
387
+ inPlace: bool = False,
388
+ flags: Flags = Flags.NONE,
389
+ ) -> Image.Image | None:
390
+ """
391
+ (pyCMS) Applies an ICC transformation to a given image, mapping from
392
+ ``inputProfile`` to ``outputProfile``.
393
+
394
+ If the input or output profiles specified are not valid filenames, a
395
+ :exc:`PyCMSError` will be raised. If ``inPlace`` is ``True`` and
396
+ ``outputMode != im.mode``, a :exc:`PyCMSError` will be raised.
397
+ If an error occurs during application of the profiles,
398
+ a :exc:`PyCMSError` will be raised.
399
+ If ``outputMode`` is not a mode supported by the ``outputProfile`` (or by pyCMS),
400
+ a :exc:`PyCMSError` will be raised.
401
+
402
+ This function applies an ICC transformation to im from ``inputProfile``'s
403
+ color space to ``outputProfile``'s color space using the specified rendering
404
+ intent to decide how to handle out-of-gamut colors.
405
+
406
+ ``outputMode`` can be used to specify that a color mode conversion is to
407
+ be done using these profiles, but the specified profiles must be able
408
+ to handle that mode. I.e., if converting im from RGB to CMYK using
409
+ profiles, the input profile must handle RGB data, and the output
410
+ profile must handle CMYK data.
411
+
412
+ :param im: An open :py:class:`~PIL.Image.Image` object (i.e. Image.new(...)
413
+ or Image.open(...), etc.)
414
+ :param inputProfile: String, as a valid filename path to the ICC input
415
+ profile you wish to use for this image, or a profile object
416
+ :param outputProfile: String, as a valid filename path to the ICC output
417
+ profile you wish to use for this image, or a profile object
418
+ :param renderingIntent: Integer (0-3) specifying the rendering intent you
419
+ wish to use for the transform
420
+
421
+ ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
422
+ ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
423
+ ImageCms.Intent.SATURATION = 2
424
+ ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
425
+
426
+ see the pyCMS documentation for details on rendering intents and what
427
+ they do.
428
+ :param outputMode: A valid PIL mode for the output image (i.e. "RGB",
429
+ "CMYK", etc.). Note: if rendering the image "inPlace", outputMode
430
+ MUST be the same mode as the input, or omitted completely. If
431
+ omitted, the outputMode will be the same as the mode of the input
432
+ image (im.mode)
433
+ :param inPlace: Boolean. If ``True``, the original image is modified in-place,
434
+ and ``None`` is returned. If ``False`` (default), a new
435
+ :py:class:`~PIL.Image.Image` object is returned with the transform applied.
436
+ :param flags: Integer (0-...) specifying additional flags
437
+ :returns: Either None or a new :py:class:`~PIL.Image.Image` object, depending on
438
+ the value of ``inPlace``
439
+ :exception PyCMSError:
440
+ """
441
+
442
+ if outputMode is None:
443
+ outputMode = im.mode
444
+
445
+ if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3):
446
+ msg = "renderingIntent must be an integer between 0 and 3"
447
+ raise PyCMSError(msg)
448
+
449
+ if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
450
+ msg = f"flags must be an integer between 0 and {_MAX_FLAG}"
451
+ raise PyCMSError(msg)
452
+
453
+ try:
454
+ if not isinstance(inputProfile, ImageCmsProfile):
455
+ inputProfile = ImageCmsProfile(inputProfile)
456
+ if not isinstance(outputProfile, ImageCmsProfile):
457
+ outputProfile = ImageCmsProfile(outputProfile)
458
+ transform = ImageCmsTransform(
459
+ inputProfile,
460
+ outputProfile,
461
+ im.mode,
462
+ outputMode,
463
+ renderingIntent,
464
+ flags=flags,
465
+ )
466
+ if inPlace:
467
+ transform.apply_in_place(im)
468
+ imOut = None
469
+ else:
470
+ imOut = transform.apply(im)
471
+ except (OSError, TypeError, ValueError) as v:
472
+ raise PyCMSError(v) from v
473
+
474
+ return imOut
475
+
476
+
477
+ def getOpenProfile(
478
+ profileFilename: str | SupportsRead[bytes] | core.CmsProfile,
479
+ ) -> ImageCmsProfile:
480
+ """
481
+ (pyCMS) Opens an ICC profile file.
482
+
483
+ The PyCMSProfile object can be passed back into pyCMS for use in creating
484
+ transforms and such (as in ImageCms.buildTransformFromOpenProfiles()).
485
+
486
+ If ``profileFilename`` is not a valid filename for an ICC profile,
487
+ a :exc:`PyCMSError` will be raised.
488
+
489
+ :param profileFilename: String, as a valid filename path to the ICC profile
490
+ you wish to open, or a file-like object.
491
+ :returns: A CmsProfile class object.
492
+ :exception PyCMSError:
493
+ """
494
+
495
+ try:
496
+ return ImageCmsProfile(profileFilename)
497
+ except (OSError, TypeError, ValueError) as v:
498
+ raise PyCMSError(v) from v
499
+
500
+
501
+ def buildTransform(
502
+ inputProfile: _CmsProfileCompatible,
503
+ outputProfile: _CmsProfileCompatible,
504
+ inMode: str,
505
+ outMode: str,
506
+ renderingIntent: Intent = Intent.PERCEPTUAL,
507
+ flags: Flags = Flags.NONE,
508
+ ) -> ImageCmsTransform:
509
+ """
510
+ (pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the
511
+ ``outputProfile``. Use applyTransform to apply the transform to a given
512
+ image.
513
+
514
+ If the input or output profiles specified are not valid filenames, a
515
+ :exc:`PyCMSError` will be raised. If an error occurs during creation
516
+ of the transform, a :exc:`PyCMSError` will be raised.
517
+
518
+ If ``inMode`` or ``outMode`` are not a mode supported by the ``outputProfile``
519
+ (or by pyCMS), a :exc:`PyCMSError` will be raised.
520
+
521
+ This function builds and returns an ICC transform from the ``inputProfile``
522
+ to the ``outputProfile`` using the ``renderingIntent`` to determine what to do
523
+ with out-of-gamut colors. It will ONLY work for converting images that
524
+ are in ``inMode`` to images that are in ``outMode`` color format (PIL mode,
525
+ i.e. "RGB", "RGBA", "CMYK", etc.).
526
+
527
+ Building the transform is a fair part of the overhead in
528
+ ImageCms.profileToProfile(), so if you're planning on converting multiple
529
+ images using the same input/output settings, this can save you time.
530
+ Once you have a transform object, it can be used with
531
+ ImageCms.applyProfile() to convert images without the need to re-compute
532
+ the lookup table for the transform.
533
+
534
+ The reason pyCMS returns a class object rather than a handle directly
535
+ to the transform is that it needs to keep track of the PIL input/output
536
+ modes that the transform is meant for. These attributes are stored in
537
+ the ``inMode`` and ``outMode`` attributes of the object (which can be
538
+ manually overridden if you really want to, but I don't know of any
539
+ time that would be of use, or would even work).
540
+
541
+ :param inputProfile: String, as a valid filename path to the ICC input
542
+ profile you wish to use for this transform, or a profile object
543
+ :param outputProfile: String, as a valid filename path to the ICC output
544
+ profile you wish to use for this transform, or a profile object
545
+ :param inMode: String, as a valid PIL mode that the appropriate profile
546
+ also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
547
+ :param outMode: String, as a valid PIL mode that the appropriate profile
548
+ also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
549
+ :param renderingIntent: Integer (0-3) specifying the rendering intent you
550
+ wish to use for the transform
551
+
552
+ ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
553
+ ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
554
+ ImageCms.Intent.SATURATION = 2
555
+ ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
556
+
557
+ see the pyCMS documentation for details on rendering intents and what
558
+ they do.
559
+ :param flags: Integer (0-...) specifying additional flags
560
+ :returns: A CmsTransform class object.
561
+ :exception PyCMSError:
562
+ """
563
+
564
+ if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3):
565
+ msg = "renderingIntent must be an integer between 0 and 3"
566
+ raise PyCMSError(msg)
567
+
568
+ if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
569
+ msg = f"flags must be an integer between 0 and {_MAX_FLAG}"
570
+ raise PyCMSError(msg)
571
+
572
+ try:
573
+ if not isinstance(inputProfile, ImageCmsProfile):
574
+ inputProfile = ImageCmsProfile(inputProfile)
575
+ if not isinstance(outputProfile, ImageCmsProfile):
576
+ outputProfile = ImageCmsProfile(outputProfile)
577
+ return ImageCmsTransform(
578
+ inputProfile, outputProfile, inMode, outMode, renderingIntent, flags=flags
579
+ )
580
+ except (OSError, TypeError, ValueError) as v:
581
+ raise PyCMSError(v) from v
582
+
583
+
584
+ def buildProofTransform(
585
+ inputProfile: _CmsProfileCompatible,
586
+ outputProfile: _CmsProfileCompatible,
587
+ proofProfile: _CmsProfileCompatible,
588
+ inMode: str,
589
+ outMode: str,
590
+ renderingIntent: Intent = Intent.PERCEPTUAL,
591
+ proofRenderingIntent: Intent = Intent.ABSOLUTE_COLORIMETRIC,
592
+ flags: Flags = Flags.SOFTPROOFING,
593
+ ) -> ImageCmsTransform:
594
+ """
595
+ (pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the
596
+ ``outputProfile``, but tries to simulate the result that would be
597
+ obtained on the ``proofProfile`` device.
598
+
599
+ If the input, output, or proof profiles specified are not valid
600
+ filenames, a :exc:`PyCMSError` will be raised.
601
+
602
+ If an error occurs during creation of the transform,
603
+ a :exc:`PyCMSError` will be raised.
604
+
605
+ If ``inMode`` or ``outMode`` are not a mode supported by the ``outputProfile``
606
+ (or by pyCMS), a :exc:`PyCMSError` will be raised.
607
+
608
+ This function builds and returns an ICC transform from the ``inputProfile``
609
+ to the ``outputProfile``, but tries to simulate the result that would be
610
+ obtained on the ``proofProfile`` device using ``renderingIntent`` and
611
+ ``proofRenderingIntent`` to determine what to do with out-of-gamut
612
+ colors. This is known as "soft-proofing". It will ONLY work for
613
+ converting images that are in ``inMode`` to images that are in outMode
614
+ color format (PIL mode, i.e. "RGB", "RGBA", "CMYK", etc.).
615
+
616
+ Usage of the resulting transform object is exactly the same as with
617
+ ImageCms.buildTransform().
618
+
619
+ Proof profiling is generally used when using an output device to get a
620
+ good idea of what the final printed/displayed image would look like on
621
+ the ``proofProfile`` device when it's quicker and easier to use the
622
+ output device for judging color. Generally, this means that the
623
+ output device is a monitor, or a dye-sub printer (etc.), and the simulated
624
+ device is something more expensive, complicated, or time consuming
625
+ (making it difficult to make a real print for color judgement purposes).
626
+
627
+ Soft-proofing basically functions by adjusting the colors on the
628
+ output device to match the colors of the device being simulated. However,
629
+ when the simulated device has a much wider gamut than the output
630
+ device, you may obtain marginal results.
631
+
632
+ :param inputProfile: String, as a valid filename path to the ICC input
633
+ profile you wish to use for this transform, or a profile object
634
+ :param outputProfile: String, as a valid filename path to the ICC output
635
+ (monitor, usually) profile you wish to use for this transform, or a
636
+ profile object
637
+ :param proofProfile: String, as a valid filename path to the ICC proof
638
+ profile you wish to use for this transform, or a profile object
639
+ :param inMode: String, as a valid PIL mode that the appropriate profile
640
+ also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
641
+ :param outMode: String, as a valid PIL mode that the appropriate profile
642
+ also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
643
+ :param renderingIntent: Integer (0-3) specifying the rendering intent you
644
+ wish to use for the input->proof (simulated) transform
645
+
646
+ ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
647
+ ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
648
+ ImageCms.Intent.SATURATION = 2
649
+ ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
650
+
651
+ see the pyCMS documentation for details on rendering intents and what
652
+ they do.
653
+ :param proofRenderingIntent: Integer (0-3) specifying the rendering intent
654
+ you wish to use for proof->output transform
655
+
656
+ ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
657
+ ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
658
+ ImageCms.Intent.SATURATION = 2
659
+ ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
660
+
661
+ see the pyCMS documentation for details on rendering intents and what
662
+ they do.
663
+ :param flags: Integer (0-...) specifying additional flags
664
+ :returns: A CmsTransform class object.
665
+ :exception PyCMSError:
666
+ """
667
+
668
+ if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3):
669
+ msg = "renderingIntent must be an integer between 0 and 3"
670
+ raise PyCMSError(msg)
671
+
672
+ if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
673
+ msg = f"flags must be an integer between 0 and {_MAX_FLAG}"
674
+ raise PyCMSError(msg)
675
+
676
+ try:
677
+ if not isinstance(inputProfile, ImageCmsProfile):
678
+ inputProfile = ImageCmsProfile(inputProfile)
679
+ if not isinstance(outputProfile, ImageCmsProfile):
680
+ outputProfile = ImageCmsProfile(outputProfile)
681
+ if not isinstance(proofProfile, ImageCmsProfile):
682
+ proofProfile = ImageCmsProfile(proofProfile)
683
+ return ImageCmsTransform(
684
+ inputProfile,
685
+ outputProfile,
686
+ inMode,
687
+ outMode,
688
+ renderingIntent,
689
+ proofProfile,
690
+ proofRenderingIntent,
691
+ flags,
692
+ )
693
+ except (OSError, TypeError, ValueError) as v:
694
+ raise PyCMSError(v) from v
695
+
696
+
697
+ buildTransformFromOpenProfiles = buildTransform
698
+ buildProofTransformFromOpenProfiles = buildProofTransform
699
+
700
+
701
+ def applyTransform(
702
+ im: Image.Image, transform: ImageCmsTransform, inPlace: bool = False
703
+ ) -> Image.Image | None:
704
+ """
705
+ (pyCMS) Applies a transform to a given image.
706
+
707
+ If ``im.mode != transform.inMode``, a :exc:`PyCMSError` is raised.
708
+
709
+ If ``inPlace`` is ``True`` and ``transform.inMode != transform.outMode``, a
710
+ :exc:`PyCMSError` is raised.
711
+
712
+ If ``im.mode``, ``transform.inMode`` or ``transform.outMode`` is not
713
+ supported by pyCMSdll or the profiles you used for the transform, a
714
+ :exc:`PyCMSError` is raised.
715
+
716
+ If an error occurs while the transform is being applied,
717
+ a :exc:`PyCMSError` is raised.
718
+
719
+ This function applies a pre-calculated transform (from
720
+ ImageCms.buildTransform() or ImageCms.buildTransformFromOpenProfiles())
721
+ to an image. The transform can be used for multiple images, saving
722
+ considerable calculation time if doing the same conversion multiple times.
723
+
724
+ If you want to modify im in-place instead of receiving a new image as
725
+ the return value, set ``inPlace`` to ``True``. This can only be done if
726
+ ``transform.inMode`` and ``transform.outMode`` are the same, because we can't
727
+ change the mode in-place (the buffer sizes for some modes are
728
+ different). The default behavior is to return a new :py:class:`~PIL.Image.Image`
729
+ object of the same dimensions in mode ``transform.outMode``.
730
+
731
+ :param im: An :py:class:`~PIL.Image.Image` object, and im.mode must be the same
732
+ as the ``inMode`` supported by the transform.
733
+ :param transform: A valid CmsTransform class object
734
+ :param inPlace: Bool. If ``True``, ``im`` is modified in place and ``None`` is
735
+ returned, if ``False``, a new :py:class:`~PIL.Image.Image` object with the
736
+ transform applied is returned (and ``im`` is not changed). The default is
737
+ ``False``.
738
+ :returns: Either ``None``, or a new :py:class:`~PIL.Image.Image` object,
739
+ depending on the value of ``inPlace``. The profile will be returned in
740
+ the image's ``info['icc_profile']``.
741
+ :exception PyCMSError:
742
+ """
743
+
744
+ try:
745
+ if inPlace:
746
+ transform.apply_in_place(im)
747
+ imOut = None
748
+ else:
749
+ imOut = transform.apply(im)
750
+ except (TypeError, ValueError) as v:
751
+ raise PyCMSError(v) from v
752
+
753
+ return imOut
754
+
755
+
756
+ def createProfile(
757
+ colorSpace: Literal["LAB", "XYZ", "sRGB"], colorTemp: SupportsFloat = -1
758
+ ) -> core.CmsProfile:
759
+ """
760
+ (pyCMS) Creates a profile.
761
+
762
+ If colorSpace not in ``["LAB", "XYZ", "sRGB"]``,
763
+ a :exc:`PyCMSError` is raised.
764
+
765
+ If using LAB and ``colorTemp`` is not a positive integer,
766
+ a :exc:`PyCMSError` is raised.
767
+
768
+ If an error occurs while creating the profile,
769
+ a :exc:`PyCMSError` is raised.
770
+
771
+ Use this function to create common profiles on-the-fly instead of
772
+ having to supply a profile on disk and knowing the path to it. It
773
+ returns a normal CmsProfile object that can be passed to
774
+ ImageCms.buildTransformFromOpenProfiles() to create a transform to apply
775
+ to images.
776
+
777
+ :param colorSpace: String, the color space of the profile you wish to
778
+ create.
779
+ Currently only "LAB", "XYZ", and "sRGB" are supported.
780
+ :param colorTemp: Positive integer for the white point for the profile, in
781
+ degrees Kelvin (i.e. 5000, 6500, 9600, etc.). The default is for D50
782
+ illuminant if omitted (5000k). colorTemp is ONLY applied to LAB
783
+ profiles, and is ignored for XYZ and sRGB.
784
+ :returns: A CmsProfile class object
785
+ :exception PyCMSError:
786
+ """
787
+
788
+ if colorSpace not in ["LAB", "XYZ", "sRGB"]:
789
+ msg = (
790
+ f"Color space not supported for on-the-fly profile creation ({colorSpace})"
791
+ )
792
+ raise PyCMSError(msg)
793
+
794
+ if colorSpace == "LAB":
795
+ try:
796
+ colorTemp = float(colorTemp)
797
+ except (TypeError, ValueError) as e:
798
+ msg = f'Color temperature must be numeric, "{colorTemp}" not valid'
799
+ raise PyCMSError(msg) from e
800
+
801
+ try:
802
+ return core.createProfile(colorSpace, colorTemp)
803
+ except (TypeError, ValueError) as v:
804
+ raise PyCMSError(v) from v
805
+
806
+
807
+ def getProfileName(profile: _CmsProfileCompatible) -> str:
808
+ """
809
+
810
+ (pyCMS) Gets the internal product name for the given profile.
811
+
812
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile,
813
+ a :exc:`PyCMSError` is raised If an error occurs while trying
814
+ to obtain the name tag, a :exc:`PyCMSError` is raised.
815
+
816
+ Use this function to obtain the INTERNAL name of the profile (stored
817
+ in an ICC tag in the profile itself), usually the one used when the
818
+ profile was originally created. Sometimes this tag also contains
819
+ additional information supplied by the creator.
820
+
821
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
822
+ filename of an ICC profile.
823
+ :returns: A string containing the internal name of the profile as stored
824
+ in an ICC tag.
825
+ :exception PyCMSError:
826
+ """
827
+
828
+ try:
829
+ # add an extra newline to preserve pyCMS compatibility
830
+ if not isinstance(profile, ImageCmsProfile):
831
+ profile = ImageCmsProfile(profile)
832
+ # do it in python, not c.
833
+ # // name was "%s - %s" (model, manufacturer) || Description ,
834
+ # // but if the Model and Manufacturer were the same or the model
835
+ # // was long, Just the model, in 1.x
836
+ model = profile.profile.model
837
+ manufacturer = profile.profile.manufacturer
838
+
839
+ if not (model or manufacturer):
840
+ return (profile.profile.profile_description or "") + "\n"
841
+ if not manufacturer or len(model) > 30: # type: ignore[arg-type]
842
+ return model + "\n" # type: ignore[operator]
843
+ return f"{model} - {manufacturer}\n"
844
+
845
+ except (AttributeError, OSError, TypeError, ValueError) as v:
846
+ raise PyCMSError(v) from v
847
+
848
+
849
+ def getProfileInfo(profile: _CmsProfileCompatible) -> str:
850
+ """
851
+ (pyCMS) Gets the internal product information for the given profile.
852
+
853
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile,
854
+ a :exc:`PyCMSError` is raised.
855
+
856
+ If an error occurs while trying to obtain the info tag,
857
+ a :exc:`PyCMSError` is raised.
858
+
859
+ Use this function to obtain the information stored in the profile's
860
+ info tag. This often contains details about the profile, and how it
861
+ was created, as supplied by the creator.
862
+
863
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
864
+ filename of an ICC profile.
865
+ :returns: A string containing the internal profile information stored in
866
+ an ICC tag.
867
+ :exception PyCMSError:
868
+ """
869
+
870
+ try:
871
+ if not isinstance(profile, ImageCmsProfile):
872
+ profile = ImageCmsProfile(profile)
873
+ # add an extra newline to preserve pyCMS compatibility
874
+ # Python, not C. the white point bits weren't working well,
875
+ # so skipping.
876
+ # info was description \r\n\r\n copyright \r\n\r\n K007 tag \r\n\r\n whitepoint
877
+ description = profile.profile.profile_description
878
+ cpright = profile.profile.copyright
879
+ elements = [element for element in (description, cpright) if element]
880
+ return "\r\n\r\n".join(elements) + "\r\n\r\n"
881
+
882
+ except (AttributeError, OSError, TypeError, ValueError) as v:
883
+ raise PyCMSError(v) from v
884
+
885
+
886
+ def getProfileCopyright(profile: _CmsProfileCompatible) -> str:
887
+ """
888
+ (pyCMS) Gets the copyright for the given profile.
889
+
890
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
891
+ :exc:`PyCMSError` is raised.
892
+
893
+ If an error occurs while trying to obtain the copyright tag,
894
+ a :exc:`PyCMSError` is raised.
895
+
896
+ Use this function to obtain the information stored in the profile's
897
+ copyright tag.
898
+
899
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
900
+ filename of an ICC profile.
901
+ :returns: A string containing the internal profile information stored in
902
+ an ICC tag.
903
+ :exception PyCMSError:
904
+ """
905
+ try:
906
+ # add an extra newline to preserve pyCMS compatibility
907
+ if not isinstance(profile, ImageCmsProfile):
908
+ profile = ImageCmsProfile(profile)
909
+ return (profile.profile.copyright or "") + "\n"
910
+ except (AttributeError, OSError, TypeError, ValueError) as v:
911
+ raise PyCMSError(v) from v
912
+
913
+
914
+ def getProfileManufacturer(profile: _CmsProfileCompatible) -> str:
915
+ """
916
+ (pyCMS) Gets the manufacturer for the given profile.
917
+
918
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
919
+ :exc:`PyCMSError` is raised.
920
+
921
+ If an error occurs while trying to obtain the manufacturer tag, a
922
+ :exc:`PyCMSError` is raised.
923
+
924
+ Use this function to obtain the information stored in the profile's
925
+ manufacturer tag.
926
+
927
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
928
+ filename of an ICC profile.
929
+ :returns: A string containing the internal profile information stored in
930
+ an ICC tag.
931
+ :exception PyCMSError:
932
+ """
933
+ try:
934
+ # add an extra newline to preserve pyCMS compatibility
935
+ if not isinstance(profile, ImageCmsProfile):
936
+ profile = ImageCmsProfile(profile)
937
+ return (profile.profile.manufacturer or "") + "\n"
938
+ except (AttributeError, OSError, TypeError, ValueError) as v:
939
+ raise PyCMSError(v) from v
940
+
941
+
942
+ def getProfileModel(profile: _CmsProfileCompatible) -> str:
943
+ """
944
+ (pyCMS) Gets the model for the given profile.
945
+
946
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
947
+ :exc:`PyCMSError` is raised.
948
+
949
+ If an error occurs while trying to obtain the model tag,
950
+ a :exc:`PyCMSError` is raised.
951
+
952
+ Use this function to obtain the information stored in the profile's
953
+ model tag.
954
+
955
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
956
+ filename of an ICC profile.
957
+ :returns: A string containing the internal profile information stored in
958
+ an ICC tag.
959
+ :exception PyCMSError:
960
+ """
961
+
962
+ try:
963
+ # add an extra newline to preserve pyCMS compatibility
964
+ if not isinstance(profile, ImageCmsProfile):
965
+ profile = ImageCmsProfile(profile)
966
+ return (profile.profile.model or "") + "\n"
967
+ except (AttributeError, OSError, TypeError, ValueError) as v:
968
+ raise PyCMSError(v) from v
969
+
970
+
971
+ def getProfileDescription(profile: _CmsProfileCompatible) -> str:
972
+ """
973
+ (pyCMS) Gets the description for the given profile.
974
+
975
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
976
+ :exc:`PyCMSError` is raised.
977
+
978
+ If an error occurs while trying to obtain the description tag,
979
+ a :exc:`PyCMSError` is raised.
980
+
981
+ Use this function to obtain the information stored in the profile's
982
+ description tag.
983
+
984
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
985
+ filename of an ICC profile.
986
+ :returns: A string containing the internal profile information stored in an
987
+ ICC tag.
988
+ :exception PyCMSError:
989
+ """
990
+
991
+ try:
992
+ # add an extra newline to preserve pyCMS compatibility
993
+ if not isinstance(profile, ImageCmsProfile):
994
+ profile = ImageCmsProfile(profile)
995
+ return (profile.profile.profile_description or "") + "\n"
996
+ except (AttributeError, OSError, TypeError, ValueError) as v:
997
+ raise PyCMSError(v) from v
998
+
999
+
1000
+ def getDefaultIntent(profile: _CmsProfileCompatible) -> int:
1001
+ """
1002
+ (pyCMS) Gets the default intent name for the given profile.
1003
+
1004
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
1005
+ :exc:`PyCMSError` is raised.
1006
+
1007
+ If an error occurs while trying to obtain the default intent, a
1008
+ :exc:`PyCMSError` is raised.
1009
+
1010
+ Use this function to determine the default (and usually best optimized)
1011
+ rendering intent for this profile. Most profiles support multiple
1012
+ rendering intents, but are intended mostly for one type of conversion.
1013
+ If you wish to use a different intent than returned, use
1014
+ ImageCms.isIntentSupported() to verify it will work first.
1015
+
1016
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
1017
+ filename of an ICC profile.
1018
+ :returns: Integer 0-3 specifying the default rendering intent for this
1019
+ profile.
1020
+
1021
+ ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
1022
+ ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
1023
+ ImageCms.Intent.SATURATION = 2
1024
+ ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
1025
+
1026
+ see the pyCMS documentation for details on rendering intents and what
1027
+ they do.
1028
+ :exception PyCMSError:
1029
+ """
1030
+
1031
+ try:
1032
+ if not isinstance(profile, ImageCmsProfile):
1033
+ profile = ImageCmsProfile(profile)
1034
+ return profile.profile.rendering_intent
1035
+ except (AttributeError, OSError, TypeError, ValueError) as v:
1036
+ raise PyCMSError(v) from v
1037
+
1038
+
1039
+ def isIntentSupported(
1040
+ profile: _CmsProfileCompatible, intent: Intent, direction: Direction
1041
+ ) -> Literal[-1, 1]:
1042
+ """
1043
+ (pyCMS) Checks if a given intent is supported.
1044
+
1045
+ Use this function to verify that you can use your desired
1046
+ ``intent`` with ``profile``, and that ``profile`` can be used for the
1047
+ input/output/proof profile as you desire.
1048
+
1049
+ Some profiles are created specifically for one "direction", can cannot
1050
+ be used for others. Some profiles can only be used for certain
1051
+ rendering intents, so it's best to either verify this before trying
1052
+ to create a transform with them (using this function), or catch the
1053
+ potential :exc:`PyCMSError` that will occur if they don't
1054
+ support the modes you select.
1055
+
1056
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
1057
+ filename of an ICC profile.
1058
+ :param intent: Integer (0-3) specifying the rendering intent you wish to
1059
+ use with this profile
1060
+
1061
+ ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
1062
+ ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
1063
+ ImageCms.Intent.SATURATION = 2
1064
+ ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
1065
+
1066
+ see the pyCMS documentation for details on rendering intents and what
1067
+ they do.
1068
+ :param direction: Integer specifying if the profile is to be used for
1069
+ input, output, or proof
1070
+
1071
+ INPUT = 0 (or use ImageCms.Direction.INPUT)
1072
+ OUTPUT = 1 (or use ImageCms.Direction.OUTPUT)
1073
+ PROOF = 2 (or use ImageCms.Direction.PROOF)
1074
+
1075
+ :returns: 1 if the intent/direction are supported, -1 if they are not.
1076
+ :exception PyCMSError:
1077
+ """
1078
+
1079
+ try:
1080
+ if not isinstance(profile, ImageCmsProfile):
1081
+ profile = ImageCmsProfile(profile)
1082
+ # FIXME: I get different results for the same data w. different
1083
+ # compilers. Bug in LittleCMS or in the binding?
1084
+ if profile.profile.is_intent_supported(intent, direction):
1085
+ return 1
1086
+ else:
1087
+ return -1
1088
+ except (AttributeError, OSError, TypeError, ValueError) as v:
1089
+ raise PyCMSError(v) from v
1090
+
1091
+
1092
+ def versions() -> tuple[str, str, str, str]:
1093
+ """
1094
+ (pyCMS) Fetches versions.
1095
+ """
1096
+
1097
+ deprecate(
1098
+ "PIL.ImageCms.versions()",
1099
+ 12,
1100
+ '(PIL.features.version("littlecms2"), sys.version, PIL.__version__)',
1101
+ )
1102
+ return _VERSION, core.littlecms_version, sys.version.split()[0], __version__
.venv/Lib/site-packages/PIL/ImageColor.py ADDED
@@ -0,0 +1,317 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library
3
+ # $Id$
4
+ #
5
+ # map CSS3-style colour description strings to RGB
6
+ #
7
+ # History:
8
+ # 2002-10-24 fl Added support for CSS-style color strings
9
+ # 2002-12-15 fl Added RGBA support
10
+ # 2004-03-27 fl Fixed remaining int() problems for Python 1.5.2
11
+ # 2004-07-19 fl Fixed gray/grey spelling issues
12
+ # 2009-03-05 fl Fixed rounding error in grayscale calculation
13
+ #
14
+ # Copyright (c) 2002-2004 by Secret Labs AB
15
+ # Copyright (c) 2002-2004 by Fredrik Lundh
16
+ #
17
+ # See the README file for information on usage and redistribution.
18
+ #
19
+ from __future__ import annotations
20
+
21
+ import re
22
+ from functools import lru_cache
23
+
24
+ from . import Image
25
+
26
+
27
+ @lru_cache
28
+ def getrgb(color):
29
+ """
30
+ Convert a color string to an RGB or RGBA tuple. If the string cannot be
31
+ parsed, this function raises a :py:exc:`ValueError` exception.
32
+
33
+ .. versionadded:: 1.1.4
34
+
35
+ :param color: A color string
36
+ :return: ``(red, green, blue[, alpha])``
37
+ """
38
+ if len(color) > 100:
39
+ msg = "color specifier is too long"
40
+ raise ValueError(msg)
41
+ color = color.lower()
42
+
43
+ rgb = colormap.get(color, None)
44
+ if rgb:
45
+ if isinstance(rgb, tuple):
46
+ return rgb
47
+ colormap[color] = rgb = getrgb(rgb)
48
+ return rgb
49
+
50
+ # check for known string formats
51
+ if re.match("#[a-f0-9]{3}$", color):
52
+ return int(color[1] * 2, 16), int(color[2] * 2, 16), int(color[3] * 2, 16)
53
+
54
+ if re.match("#[a-f0-9]{4}$", color):
55
+ return (
56
+ int(color[1] * 2, 16),
57
+ int(color[2] * 2, 16),
58
+ int(color[3] * 2, 16),
59
+ int(color[4] * 2, 16),
60
+ )
61
+
62
+ if re.match("#[a-f0-9]{6}$", color):
63
+ return int(color[1:3], 16), int(color[3:5], 16), int(color[5:7], 16)
64
+
65
+ if re.match("#[a-f0-9]{8}$", color):
66
+ return (
67
+ int(color[1:3], 16),
68
+ int(color[3:5], 16),
69
+ int(color[5:7], 16),
70
+ int(color[7:9], 16),
71
+ )
72
+
73
+ m = re.match(r"rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$", color)
74
+ if m:
75
+ return int(m.group(1)), int(m.group(2)), int(m.group(3))
76
+
77
+ m = re.match(r"rgb\(\s*(\d+)%\s*,\s*(\d+)%\s*,\s*(\d+)%\s*\)$", color)
78
+ if m:
79
+ return (
80
+ int((int(m.group(1)) * 255) / 100.0 + 0.5),
81
+ int((int(m.group(2)) * 255) / 100.0 + 0.5),
82
+ int((int(m.group(3)) * 255) / 100.0 + 0.5),
83
+ )
84
+
85
+ m = re.match(
86
+ r"hsl\(\s*(\d+\.?\d*)\s*,\s*(\d+\.?\d*)%\s*,\s*(\d+\.?\d*)%\s*\)$", color
87
+ )
88
+ if m:
89
+ from colorsys import hls_to_rgb
90
+
91
+ rgb = hls_to_rgb(
92
+ float(m.group(1)) / 360.0,
93
+ float(m.group(3)) / 100.0,
94
+ float(m.group(2)) / 100.0,
95
+ )
96
+ return (
97
+ int(rgb[0] * 255 + 0.5),
98
+ int(rgb[1] * 255 + 0.5),
99
+ int(rgb[2] * 255 + 0.5),
100
+ )
101
+
102
+ m = re.match(
103
+ r"hs[bv]\(\s*(\d+\.?\d*)\s*,\s*(\d+\.?\d*)%\s*,\s*(\d+\.?\d*)%\s*\)$", color
104
+ )
105
+ if m:
106
+ from colorsys import hsv_to_rgb
107
+
108
+ rgb = hsv_to_rgb(
109
+ float(m.group(1)) / 360.0,
110
+ float(m.group(2)) / 100.0,
111
+ float(m.group(3)) / 100.0,
112
+ )
113
+ return (
114
+ int(rgb[0] * 255 + 0.5),
115
+ int(rgb[1] * 255 + 0.5),
116
+ int(rgb[2] * 255 + 0.5),
117
+ )
118
+
119
+ m = re.match(r"rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$", color)
120
+ if m:
121
+ return int(m.group(1)), int(m.group(2)), int(m.group(3)), int(m.group(4))
122
+ msg = f"unknown color specifier: {repr(color)}"
123
+ raise ValueError(msg)
124
+
125
+
126
+ @lru_cache
127
+ def getcolor(color, mode: str) -> tuple[int, ...]:
128
+ """
129
+ Same as :py:func:`~PIL.ImageColor.getrgb` for most modes. However, if
130
+ ``mode`` is HSV, converts the RGB value to a HSV value, or if ``mode`` is
131
+ not color or a palette image, converts the RGB value to a grayscale value.
132
+ If the string cannot be parsed, this function raises a :py:exc:`ValueError`
133
+ exception.
134
+
135
+ .. versionadded:: 1.1.4
136
+
137
+ :param color: A color string
138
+ :param mode: Convert result to this mode
139
+ :return: ``(graylevel[, alpha]) or (red, green, blue[, alpha])``
140
+ """
141
+ # same as getrgb, but converts the result to the given mode
142
+ color, alpha = getrgb(color), 255
143
+ if len(color) == 4:
144
+ color, alpha = color[:3], color[3]
145
+
146
+ if mode == "HSV":
147
+ from colorsys import rgb_to_hsv
148
+
149
+ r, g, b = color
150
+ h, s, v = rgb_to_hsv(r / 255, g / 255, b / 255)
151
+ return int(h * 255), int(s * 255), int(v * 255)
152
+ elif Image.getmodebase(mode) == "L":
153
+ r, g, b = color
154
+ # ITU-R Recommendation 601-2 for nonlinear RGB
155
+ # scaled to 24 bits to match the convert's implementation.
156
+ color = (r * 19595 + g * 38470 + b * 7471 + 0x8000) >> 16
157
+ if mode[-1] == "A":
158
+ return color, alpha
159
+ else:
160
+ if mode[-1] == "A":
161
+ return color + (alpha,)
162
+ return color
163
+
164
+
165
+ colormap = {
166
+ # X11 colour table from https://drafts.csswg.org/css-color-4/, with
167
+ # gray/grey spelling issues fixed. This is a superset of HTML 4.0
168
+ # colour names used in CSS 1.
169
+ "aliceblue": "#f0f8ff",
170
+ "antiquewhite": "#faebd7",
171
+ "aqua": "#00ffff",
172
+ "aquamarine": "#7fffd4",
173
+ "azure": "#f0ffff",
174
+ "beige": "#f5f5dc",
175
+ "bisque": "#ffe4c4",
176
+ "black": "#000000",
177
+ "blanchedalmond": "#ffebcd",
178
+ "blue": "#0000ff",
179
+ "blueviolet": "#8a2be2",
180
+ "brown": "#a52a2a",
181
+ "burlywood": "#deb887",
182
+ "cadetblue": "#5f9ea0",
183
+ "chartreuse": "#7fff00",
184
+ "chocolate": "#d2691e",
185
+ "coral": "#ff7f50",
186
+ "cornflowerblue": "#6495ed",
187
+ "cornsilk": "#fff8dc",
188
+ "crimson": "#dc143c",
189
+ "cyan": "#00ffff",
190
+ "darkblue": "#00008b",
191
+ "darkcyan": "#008b8b",
192
+ "darkgoldenrod": "#b8860b",
193
+ "darkgray": "#a9a9a9",
194
+ "darkgrey": "#a9a9a9",
195
+ "darkgreen": "#006400",
196
+ "darkkhaki": "#bdb76b",
197
+ "darkmagenta": "#8b008b",
198
+ "darkolivegreen": "#556b2f",
199
+ "darkorange": "#ff8c00",
200
+ "darkorchid": "#9932cc",
201
+ "darkred": "#8b0000",
202
+ "darksalmon": "#e9967a",
203
+ "darkseagreen": "#8fbc8f",
204
+ "darkslateblue": "#483d8b",
205
+ "darkslategray": "#2f4f4f",
206
+ "darkslategrey": "#2f4f4f",
207
+ "darkturquoise": "#00ced1",
208
+ "darkviolet": "#9400d3",
209
+ "deeppink": "#ff1493",
210
+ "deepskyblue": "#00bfff",
211
+ "dimgray": "#696969",
212
+ "dimgrey": "#696969",
213
+ "dodgerblue": "#1e90ff",
214
+ "firebrick": "#b22222",
215
+ "floralwhite": "#fffaf0",
216
+ "forestgreen": "#228b22",
217
+ "fuchsia": "#ff00ff",
218
+ "gainsboro": "#dcdcdc",
219
+ "ghostwhite": "#f8f8ff",
220
+ "gold": "#ffd700",
221
+ "goldenrod": "#daa520",
222
+ "gray": "#808080",
223
+ "grey": "#808080",
224
+ "green": "#008000",
225
+ "greenyellow": "#adff2f",
226
+ "honeydew": "#f0fff0",
227
+ "hotpink": "#ff69b4",
228
+ "indianred": "#cd5c5c",
229
+ "indigo": "#4b0082",
230
+ "ivory": "#fffff0",
231
+ "khaki": "#f0e68c",
232
+ "lavender": "#e6e6fa",
233
+ "lavenderblush": "#fff0f5",
234
+ "lawngreen": "#7cfc00",
235
+ "lemonchiffon": "#fffacd",
236
+ "lightblue": "#add8e6",
237
+ "lightcoral": "#f08080",
238
+ "lightcyan": "#e0ffff",
239
+ "lightgoldenrodyellow": "#fafad2",
240
+ "lightgreen": "#90ee90",
241
+ "lightgray": "#d3d3d3",
242
+ "lightgrey": "#d3d3d3",
243
+ "lightpink": "#ffb6c1",
244
+ "lightsalmon": "#ffa07a",
245
+ "lightseagreen": "#20b2aa",
246
+ "lightskyblue": "#87cefa",
247
+ "lightslategray": "#778899",
248
+ "lightslategrey": "#778899",
249
+ "lightsteelblue": "#b0c4de",
250
+ "lightyellow": "#ffffe0",
251
+ "lime": "#00ff00",
252
+ "limegreen": "#32cd32",
253
+ "linen": "#faf0e6",
254
+ "magenta": "#ff00ff",
255
+ "maroon": "#800000",
256
+ "mediumaquamarine": "#66cdaa",
257
+ "mediumblue": "#0000cd",
258
+ "mediumorchid": "#ba55d3",
259
+ "mediumpurple": "#9370db",
260
+ "mediumseagreen": "#3cb371",
261
+ "mediumslateblue": "#7b68ee",
262
+ "mediumspringgreen": "#00fa9a",
263
+ "mediumturquoise": "#48d1cc",
264
+ "mediumvioletred": "#c71585",
265
+ "midnightblue": "#191970",
266
+ "mintcream": "#f5fffa",
267
+ "mistyrose": "#ffe4e1",
268
+ "moccasin": "#ffe4b5",
269
+ "navajowhite": "#ffdead",
270
+ "navy": "#000080",
271
+ "oldlace": "#fdf5e6",
272
+ "olive": "#808000",
273
+ "olivedrab": "#6b8e23",
274
+ "orange": "#ffa500",
275
+ "orangered": "#ff4500",
276
+ "orchid": "#da70d6",
277
+ "palegoldenrod": "#eee8aa",
278
+ "palegreen": "#98fb98",
279
+ "paleturquoise": "#afeeee",
280
+ "palevioletred": "#db7093",
281
+ "papayawhip": "#ffefd5",
282
+ "peachpuff": "#ffdab9",
283
+ "peru": "#cd853f",
284
+ "pink": "#ffc0cb",
285
+ "plum": "#dda0dd",
286
+ "powderblue": "#b0e0e6",
287
+ "purple": "#800080",
288
+ "rebeccapurple": "#663399",
289
+ "red": "#ff0000",
290
+ "rosybrown": "#bc8f8f",
291
+ "royalblue": "#4169e1",
292
+ "saddlebrown": "#8b4513",
293
+ "salmon": "#fa8072",
294
+ "sandybrown": "#f4a460",
295
+ "seagreen": "#2e8b57",
296
+ "seashell": "#fff5ee",
297
+ "sienna": "#a0522d",
298
+ "silver": "#c0c0c0",
299
+ "skyblue": "#87ceeb",
300
+ "slateblue": "#6a5acd",
301
+ "slategray": "#708090",
302
+ "slategrey": "#708090",
303
+ "snow": "#fffafa",
304
+ "springgreen": "#00ff7f",
305
+ "steelblue": "#4682b4",
306
+ "tan": "#d2b48c",
307
+ "teal": "#008080",
308
+ "thistle": "#d8bfd8",
309
+ "tomato": "#ff6347",
310
+ "turquoise": "#40e0d0",
311
+ "violet": "#ee82ee",
312
+ "wheat": "#f5deb3",
313
+ "white": "#ffffff",
314
+ "whitesmoke": "#f5f5f5",
315
+ "yellow": "#ffff00",
316
+ "yellowgreen": "#9acd32",
317
+ }
.venv/Lib/site-packages/PIL/ImageDraw.py ADDED
@@ -0,0 +1,1087 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library
3
+ # $Id$
4
+ #
5
+ # drawing interface operations
6
+ #
7
+ # History:
8
+ # 1996-04-13 fl Created (experimental)
9
+ # 1996-08-07 fl Filled polygons, ellipses.
10
+ # 1996-08-13 fl Added text support
11
+ # 1998-06-28 fl Handle I and F images
12
+ # 1998-12-29 fl Added arc; use arc primitive to draw ellipses
13
+ # 1999-01-10 fl Added shape stuff (experimental)
14
+ # 1999-02-06 fl Added bitmap support
15
+ # 1999-02-11 fl Changed all primitives to take options
16
+ # 1999-02-20 fl Fixed backwards compatibility
17
+ # 2000-10-12 fl Copy on write, when necessary
18
+ # 2001-02-18 fl Use default ink for bitmap/text also in fill mode
19
+ # 2002-10-24 fl Added support for CSS-style color strings
20
+ # 2002-12-10 fl Added experimental support for RGBA-on-RGB drawing
21
+ # 2002-12-11 fl Refactored low-level drawing API (work in progress)
22
+ # 2004-08-26 fl Made Draw() a factory function, added getdraw() support
23
+ # 2004-09-04 fl Added width support to line primitive
24
+ # 2004-09-10 fl Added font mode handling
25
+ # 2006-06-19 fl Added font bearing support (getmask2)
26
+ #
27
+ # Copyright (c) 1997-2006 by Secret Labs AB
28
+ # Copyright (c) 1996-2006 by Fredrik Lundh
29
+ #
30
+ # See the README file for information on usage and redistribution.
31
+ #
32
+ from __future__ import annotations
33
+
34
+ import math
35
+ import numbers
36
+ import struct
37
+ from typing import Sequence, cast
38
+
39
+ from . import Image, ImageColor
40
+ from ._typing import Coords
41
+
42
+ """
43
+ A simple 2D drawing interface for PIL images.
44
+ <p>
45
+ Application code should use the <b>Draw</b> factory, instead of
46
+ directly.
47
+ """
48
+
49
+
50
+ class ImageDraw:
51
+ font = None
52
+
53
+ def __init__(self, im: Image.Image, mode: str | None = None) -> None:
54
+ """
55
+ Create a drawing instance.
56
+
57
+ :param im: The image to draw in.
58
+ :param mode: Optional mode to use for color values. For RGB
59
+ images, this argument can be RGB or RGBA (to blend the
60
+ drawing into the image). For all other modes, this argument
61
+ must be the same as the image mode. If omitted, the mode
62
+ defaults to the mode of the image.
63
+ """
64
+ im.load()
65
+ if im.readonly:
66
+ im._copy() # make it writeable
67
+ blend = 0
68
+ if mode is None:
69
+ mode = im.mode
70
+ if mode != im.mode:
71
+ if mode == "RGBA" and im.mode == "RGB":
72
+ blend = 1
73
+ else:
74
+ msg = "mode mismatch"
75
+ raise ValueError(msg)
76
+ if mode == "P":
77
+ self.palette = im.palette
78
+ else:
79
+ self.palette = None
80
+ self._image = im
81
+ self.im = im.im
82
+ self.draw = Image.core.draw(self.im, blend)
83
+ self.mode = mode
84
+ if mode in ("I", "F"):
85
+ self.ink = self.draw.draw_ink(1)
86
+ else:
87
+ self.ink = self.draw.draw_ink(-1)
88
+ if mode in ("1", "P", "I", "F"):
89
+ # FIXME: fix Fill2 to properly support matte for I+F images
90
+ self.fontmode = "1"
91
+ else:
92
+ self.fontmode = "L" # aliasing is okay for other modes
93
+ self.fill = False
94
+
95
+ def getfont(self):
96
+ """
97
+ Get the current default font.
98
+
99
+ To set the default font for this ImageDraw instance::
100
+
101
+ from PIL import ImageDraw, ImageFont
102
+ draw.font = ImageFont.truetype("Tests/fonts/FreeMono.ttf")
103
+
104
+ To set the default font for all future ImageDraw instances::
105
+
106
+ from PIL import ImageDraw, ImageFont
107
+ ImageDraw.ImageDraw.font = ImageFont.truetype("Tests/fonts/FreeMono.ttf")
108
+
109
+ If the current default font is ``None``,
110
+ it is initialized with ``ImageFont.load_default()``.
111
+
112
+ :returns: An image font."""
113
+ if not self.font:
114
+ # FIXME: should add a font repository
115
+ from . import ImageFont
116
+
117
+ self.font = ImageFont.load_default()
118
+ return self.font
119
+
120
+ def _getfont(self, font_size: float | None):
121
+ if font_size is not None:
122
+ from . import ImageFont
123
+
124
+ font = ImageFont.load_default(font_size)
125
+ else:
126
+ font = self.getfont()
127
+ return font
128
+
129
+ def _getink(self, ink, fill=None) -> tuple[int | None, int | None]:
130
+ if ink is None and fill is None:
131
+ if self.fill:
132
+ fill = self.ink
133
+ else:
134
+ ink = self.ink
135
+ else:
136
+ if ink is not None:
137
+ if isinstance(ink, str):
138
+ ink = ImageColor.getcolor(ink, self.mode)
139
+ if self.palette and not isinstance(ink, numbers.Number):
140
+ ink = self.palette.getcolor(ink, self._image)
141
+ ink = self.draw.draw_ink(ink)
142
+ if fill is not None:
143
+ if isinstance(fill, str):
144
+ fill = ImageColor.getcolor(fill, self.mode)
145
+ if self.palette and not isinstance(fill, numbers.Number):
146
+ fill = self.palette.getcolor(fill, self._image)
147
+ fill = self.draw.draw_ink(fill)
148
+ return ink, fill
149
+
150
+ def arc(self, xy: Coords, start, end, fill=None, width=1) -> None:
151
+ """Draw an arc."""
152
+ ink, fill = self._getink(fill)
153
+ if ink is not None:
154
+ self.draw.draw_arc(xy, start, end, ink, width)
155
+
156
+ def bitmap(self, xy: Sequence[int], bitmap, fill=None) -> None:
157
+ """Draw a bitmap."""
158
+ bitmap.load()
159
+ ink, fill = self._getink(fill)
160
+ if ink is None:
161
+ ink = fill
162
+ if ink is not None:
163
+ self.draw.draw_bitmap(xy, bitmap.im, ink)
164
+
165
+ def chord(self, xy: Coords, start, end, fill=None, outline=None, width=1) -> None:
166
+ """Draw a chord."""
167
+ ink, fill = self._getink(outline, fill)
168
+ if fill is not None:
169
+ self.draw.draw_chord(xy, start, end, fill, 1)
170
+ if ink is not None and ink != fill and width != 0:
171
+ self.draw.draw_chord(xy, start, end, ink, 0, width)
172
+
173
+ def ellipse(self, xy: Coords, fill=None, outline=None, width=1) -> None:
174
+ """Draw an ellipse."""
175
+ ink, fill = self._getink(outline, fill)
176
+ if fill is not None:
177
+ self.draw.draw_ellipse(xy, fill, 1)
178
+ if ink is not None and ink != fill and width != 0:
179
+ self.draw.draw_ellipse(xy, ink, 0, width)
180
+
181
+ def line(self, xy: Coords, fill=None, width=0, joint=None) -> None:
182
+ """Draw a line, or a connected sequence of line segments."""
183
+ ink = self._getink(fill)[0]
184
+ if ink is not None:
185
+ self.draw.draw_lines(xy, ink, width)
186
+ if joint == "curve" and width > 4:
187
+ points: Sequence[Sequence[float]]
188
+ if isinstance(xy[0], (list, tuple)):
189
+ points = cast(Sequence[Sequence[float]], xy)
190
+ else:
191
+ points = [
192
+ cast(Sequence[float], tuple(xy[i : i + 2]))
193
+ for i in range(0, len(xy), 2)
194
+ ]
195
+ for i in range(1, len(points) - 1):
196
+ point = points[i]
197
+ angles = [
198
+ math.degrees(math.atan2(end[0] - start[0], start[1] - end[1]))
199
+ % 360
200
+ for start, end in (
201
+ (points[i - 1], point),
202
+ (point, points[i + 1]),
203
+ )
204
+ ]
205
+ if angles[0] == angles[1]:
206
+ # This is a straight line, so no joint is required
207
+ continue
208
+
209
+ def coord_at_angle(coord, angle):
210
+ x, y = coord
211
+ angle -= 90
212
+ distance = width / 2 - 1
213
+ return tuple(
214
+ p + (math.floor(p_d) if p_d > 0 else math.ceil(p_d))
215
+ for p, p_d in (
216
+ (x, distance * math.cos(math.radians(angle))),
217
+ (y, distance * math.sin(math.radians(angle))),
218
+ )
219
+ )
220
+
221
+ flipped = (
222
+ angles[1] > angles[0] and angles[1] - 180 > angles[0]
223
+ ) or (angles[1] < angles[0] and angles[1] + 180 > angles[0])
224
+ coords = [
225
+ (point[0] - width / 2 + 1, point[1] - width / 2 + 1),
226
+ (point[0] + width / 2 - 1, point[1] + width / 2 - 1),
227
+ ]
228
+ if flipped:
229
+ start, end = (angles[1] + 90, angles[0] + 90)
230
+ else:
231
+ start, end = (angles[0] - 90, angles[1] - 90)
232
+ self.pieslice(coords, start - 90, end - 90, fill)
233
+
234
+ if width > 8:
235
+ # Cover potential gaps between the line and the joint
236
+ if flipped:
237
+ gap_coords = [
238
+ coord_at_angle(point, angles[0] + 90),
239
+ point,
240
+ coord_at_angle(point, angles[1] + 90),
241
+ ]
242
+ else:
243
+ gap_coords = [
244
+ coord_at_angle(point, angles[0] - 90),
245
+ point,
246
+ coord_at_angle(point, angles[1] - 90),
247
+ ]
248
+ self.line(gap_coords, fill, width=3)
249
+
250
+ def shape(self, shape, fill=None, outline=None) -> None:
251
+ """(Experimental) Draw a shape."""
252
+ shape.close()
253
+ ink, fill = self._getink(outline, fill)
254
+ if fill is not None:
255
+ self.draw.draw_outline(shape, fill, 1)
256
+ if ink is not None and ink != fill:
257
+ self.draw.draw_outline(shape, ink, 0)
258
+
259
+ def pieslice(
260
+ self, xy: Coords, start, end, fill=None, outline=None, width=1
261
+ ) -> None:
262
+ """Draw a pieslice."""
263
+ ink, fill = self._getink(outline, fill)
264
+ if fill is not None:
265
+ self.draw.draw_pieslice(xy, start, end, fill, 1)
266
+ if ink is not None and ink != fill and width != 0:
267
+ self.draw.draw_pieslice(xy, start, end, ink, 0, width)
268
+
269
+ def point(self, xy: Coords, fill=None) -> None:
270
+ """Draw one or more individual pixels."""
271
+ ink, fill = self._getink(fill)
272
+ if ink is not None:
273
+ self.draw.draw_points(xy, ink)
274
+
275
+ def polygon(self, xy: Coords, fill=None, outline=None, width=1) -> None:
276
+ """Draw a polygon."""
277
+ ink, fill = self._getink(outline, fill)
278
+ if fill is not None:
279
+ self.draw.draw_polygon(xy, fill, 1)
280
+ if ink is not None and ink != fill and width != 0:
281
+ if width == 1:
282
+ self.draw.draw_polygon(xy, ink, 0, width)
283
+ elif self.im is not None:
284
+ # To avoid expanding the polygon outwards,
285
+ # use the fill as a mask
286
+ mask = Image.new("1", self.im.size)
287
+ mask_ink = self._getink(1)[0]
288
+
289
+ fill_im = mask.copy()
290
+ draw = Draw(fill_im)
291
+ draw.draw.draw_polygon(xy, mask_ink, 1)
292
+
293
+ ink_im = mask.copy()
294
+ draw = Draw(ink_im)
295
+ width = width * 2 - 1
296
+ draw.draw.draw_polygon(xy, mask_ink, 0, width)
297
+
298
+ mask.paste(ink_im, mask=fill_im)
299
+
300
+ im = Image.new(self.mode, self.im.size)
301
+ draw = Draw(im)
302
+ draw.draw.draw_polygon(xy, ink, 0, width)
303
+ self.im.paste(im.im, (0, 0) + im.size, mask.im)
304
+
305
+ def regular_polygon(
306
+ self, bounding_circle, n_sides, rotation=0, fill=None, outline=None, width=1
307
+ ) -> None:
308
+ """Draw a regular polygon."""
309
+ xy = _compute_regular_polygon_vertices(bounding_circle, n_sides, rotation)
310
+ self.polygon(xy, fill, outline, width)
311
+
312
+ def rectangle(self, xy: Coords, fill=None, outline=None, width=1) -> None:
313
+ """Draw a rectangle."""
314
+ ink, fill = self._getink(outline, fill)
315
+ if fill is not None:
316
+ self.draw.draw_rectangle(xy, fill, 1)
317
+ if ink is not None and ink != fill and width != 0:
318
+ self.draw.draw_rectangle(xy, ink, 0, width)
319
+
320
+ def rounded_rectangle(
321
+ self, xy: Coords, radius=0, fill=None, outline=None, width=1, *, corners=None
322
+ ) -> None:
323
+ """Draw a rounded rectangle."""
324
+ if isinstance(xy[0], (list, tuple)):
325
+ (x0, y0), (x1, y1) = cast(Sequence[Sequence[float]], xy)
326
+ else:
327
+ x0, y0, x1, y1 = cast(Sequence[float], xy)
328
+ if x1 < x0:
329
+ msg = "x1 must be greater than or equal to x0"
330
+ raise ValueError(msg)
331
+ if y1 < y0:
332
+ msg = "y1 must be greater than or equal to y0"
333
+ raise ValueError(msg)
334
+ if corners is None:
335
+ corners = (True, True, True, True)
336
+
337
+ d = radius * 2
338
+
339
+ x0 = round(x0)
340
+ y0 = round(y0)
341
+ x1 = round(x1)
342
+ y1 = round(y1)
343
+ full_x, full_y = False, False
344
+ if all(corners):
345
+ full_x = d >= x1 - x0 - 1
346
+ if full_x:
347
+ # The two left and two right corners are joined
348
+ d = x1 - x0
349
+ full_y = d >= y1 - y0 - 1
350
+ if full_y:
351
+ # The two top and two bottom corners are joined
352
+ d = y1 - y0
353
+ if full_x and full_y:
354
+ # If all corners are joined, that is a circle
355
+ return self.ellipse(xy, fill, outline, width)
356
+
357
+ if d == 0 or not any(corners):
358
+ # If the corners have no curve,
359
+ # or there are no corners,
360
+ # that is a rectangle
361
+ return self.rectangle(xy, fill, outline, width)
362
+
363
+ r = d // 2
364
+ ink, fill = self._getink(outline, fill)
365
+
366
+ def draw_corners(pieslice) -> None:
367
+ parts: tuple[tuple[tuple[float, float, float, float], int, int], ...]
368
+ if full_x:
369
+ # Draw top and bottom halves
370
+ parts = (
371
+ ((x0, y0, x0 + d, y0 + d), 180, 360),
372
+ ((x0, y1 - d, x0 + d, y1), 0, 180),
373
+ )
374
+ elif full_y:
375
+ # Draw left and right halves
376
+ parts = (
377
+ ((x0, y0, x0 + d, y0 + d), 90, 270),
378
+ ((x1 - d, y0, x1, y0 + d), 270, 90),
379
+ )
380
+ else:
381
+ # Draw four separate corners
382
+ parts = tuple(
383
+ part
384
+ for i, part in enumerate(
385
+ (
386
+ ((x0, y0, x0 + d, y0 + d), 180, 270),
387
+ ((x1 - d, y0, x1, y0 + d), 270, 360),
388
+ ((x1 - d, y1 - d, x1, y1), 0, 90),
389
+ ((x0, y1 - d, x0 + d, y1), 90, 180),
390
+ )
391
+ )
392
+ if corners[i]
393
+ )
394
+ for part in parts:
395
+ if pieslice:
396
+ self.draw.draw_pieslice(*(part + (fill, 1)))
397
+ else:
398
+ self.draw.draw_arc(*(part + (ink, width)))
399
+
400
+ if fill is not None:
401
+ draw_corners(True)
402
+
403
+ if full_x:
404
+ self.draw.draw_rectangle((x0, y0 + r + 1, x1, y1 - r - 1), fill, 1)
405
+ else:
406
+ self.draw.draw_rectangle((x0 + r + 1, y0, x1 - r - 1, y1), fill, 1)
407
+ if not full_x and not full_y:
408
+ left = [x0, y0, x0 + r, y1]
409
+ if corners[0]:
410
+ left[1] += r + 1
411
+ if corners[3]:
412
+ left[3] -= r + 1
413
+ self.draw.draw_rectangle(left, fill, 1)
414
+
415
+ right = [x1 - r, y0, x1, y1]
416
+ if corners[1]:
417
+ right[1] += r + 1
418
+ if corners[2]:
419
+ right[3] -= r + 1
420
+ self.draw.draw_rectangle(right, fill, 1)
421
+ if ink is not None and ink != fill and width != 0:
422
+ draw_corners(False)
423
+
424
+ if not full_x:
425
+ top = [x0, y0, x1, y0 + width - 1]
426
+ if corners[0]:
427
+ top[0] += r + 1
428
+ if corners[1]:
429
+ top[2] -= r + 1
430
+ self.draw.draw_rectangle(top, ink, 1)
431
+
432
+ bottom = [x0, y1 - width + 1, x1, y1]
433
+ if corners[3]:
434
+ bottom[0] += r + 1
435
+ if corners[2]:
436
+ bottom[2] -= r + 1
437
+ self.draw.draw_rectangle(bottom, ink, 1)
438
+ if not full_y:
439
+ left = [x0, y0, x0 + width - 1, y1]
440
+ if corners[0]:
441
+ left[1] += r + 1
442
+ if corners[3]:
443
+ left[3] -= r + 1
444
+ self.draw.draw_rectangle(left, ink, 1)
445
+
446
+ right = [x1 - width + 1, y0, x1, y1]
447
+ if corners[1]:
448
+ right[1] += r + 1
449
+ if corners[2]:
450
+ right[3] -= r + 1
451
+ self.draw.draw_rectangle(right, ink, 1)
452
+
453
+ def _multiline_check(self, text) -> bool:
454
+ split_character = "\n" if isinstance(text, str) else b"\n"
455
+
456
+ return split_character in text
457
+
458
+ def _multiline_split(self, text) -> list[str | bytes]:
459
+ split_character = "\n" if isinstance(text, str) else b"\n"
460
+
461
+ return text.split(split_character)
462
+
463
+ def _multiline_spacing(self, font, spacing, stroke_width):
464
+ return (
465
+ self.textbbox((0, 0), "A", font, stroke_width=stroke_width)[3]
466
+ + stroke_width
467
+ + spacing
468
+ )
469
+
470
+ def text(
471
+ self,
472
+ xy,
473
+ text,
474
+ fill=None,
475
+ font=None,
476
+ anchor=None,
477
+ spacing=4,
478
+ align="left",
479
+ direction=None,
480
+ features=None,
481
+ language=None,
482
+ stroke_width=0,
483
+ stroke_fill=None,
484
+ embedded_color=False,
485
+ *args,
486
+ **kwargs,
487
+ ) -> None:
488
+ """Draw text."""
489
+ if embedded_color and self.mode not in ("RGB", "RGBA"):
490
+ msg = "Embedded color supported only in RGB and RGBA modes"
491
+ raise ValueError(msg)
492
+
493
+ if font is None:
494
+ font = self._getfont(kwargs.get("font_size"))
495
+
496
+ if self._multiline_check(text):
497
+ return self.multiline_text(
498
+ xy,
499
+ text,
500
+ fill,
501
+ font,
502
+ anchor,
503
+ spacing,
504
+ align,
505
+ direction,
506
+ features,
507
+ language,
508
+ stroke_width,
509
+ stroke_fill,
510
+ embedded_color,
511
+ )
512
+
513
+ def getink(fill):
514
+ ink, fill = self._getink(fill)
515
+ if ink is None:
516
+ return fill
517
+ return ink
518
+
519
+ def draw_text(ink, stroke_width=0, stroke_offset=None) -> None:
520
+ mode = self.fontmode
521
+ if stroke_width == 0 and embedded_color:
522
+ mode = "RGBA"
523
+ coord = []
524
+ start = []
525
+ for i in range(2):
526
+ coord.append(int(xy[i]))
527
+ start.append(math.modf(xy[i])[0])
528
+ try:
529
+ mask, offset = font.getmask2(
530
+ text,
531
+ mode,
532
+ direction=direction,
533
+ features=features,
534
+ language=language,
535
+ stroke_width=stroke_width,
536
+ anchor=anchor,
537
+ ink=ink,
538
+ start=start,
539
+ *args,
540
+ **kwargs,
541
+ )
542
+ coord = [coord[0] + offset[0], coord[1] + offset[1]]
543
+ except AttributeError:
544
+ try:
545
+ mask = font.getmask(
546
+ text,
547
+ mode,
548
+ direction,
549
+ features,
550
+ language,
551
+ stroke_width,
552
+ anchor,
553
+ ink,
554
+ start=start,
555
+ *args,
556
+ **kwargs,
557
+ )
558
+ except TypeError:
559
+ mask = font.getmask(text)
560
+ if stroke_offset:
561
+ coord = [coord[0] + stroke_offset[0], coord[1] + stroke_offset[1]]
562
+ if mode == "RGBA":
563
+ # font.getmask2(mode="RGBA") returns color in RGB bands and mask in A
564
+ # extract mask and set text alpha
565
+ color, mask = mask, mask.getband(3)
566
+ ink_alpha = struct.pack("i", ink)[3]
567
+ color.fillband(3, ink_alpha)
568
+ x, y = coord
569
+ if self.im is not None:
570
+ self.im.paste(
571
+ color, (x, y, x + mask.size[0], y + mask.size[1]), mask
572
+ )
573
+ else:
574
+ self.draw.draw_bitmap(coord, mask, ink)
575
+
576
+ ink = getink(fill)
577
+ if ink is not None:
578
+ stroke_ink = None
579
+ if stroke_width:
580
+ stroke_ink = getink(stroke_fill) if stroke_fill is not None else ink
581
+
582
+ if stroke_ink is not None:
583
+ # Draw stroked text
584
+ draw_text(stroke_ink, stroke_width)
585
+
586
+ # Draw normal text
587
+ draw_text(ink, 0)
588
+ else:
589
+ # Only draw normal text
590
+ draw_text(ink)
591
+
592
+ def multiline_text(
593
+ self,
594
+ xy,
595
+ text,
596
+ fill=None,
597
+ font=None,
598
+ anchor=None,
599
+ spacing=4,
600
+ align="left",
601
+ direction=None,
602
+ features=None,
603
+ language=None,
604
+ stroke_width=0,
605
+ stroke_fill=None,
606
+ embedded_color=False,
607
+ *,
608
+ font_size=None,
609
+ ) -> None:
610
+ if direction == "ttb":
611
+ msg = "ttb direction is unsupported for multiline text"
612
+ raise ValueError(msg)
613
+
614
+ if anchor is None:
615
+ anchor = "la"
616
+ elif len(anchor) != 2:
617
+ msg = "anchor must be a 2 character string"
618
+ raise ValueError(msg)
619
+ elif anchor[1] in "tb":
620
+ msg = "anchor not supported for multiline text"
621
+ raise ValueError(msg)
622
+
623
+ if font is None:
624
+ font = self._getfont(font_size)
625
+
626
+ widths = []
627
+ max_width = 0
628
+ lines = self._multiline_split(text)
629
+ line_spacing = self._multiline_spacing(font, spacing, stroke_width)
630
+ for line in lines:
631
+ line_width = self.textlength(
632
+ line, font, direction=direction, features=features, language=language
633
+ )
634
+ widths.append(line_width)
635
+ max_width = max(max_width, line_width)
636
+
637
+ top = xy[1]
638
+ if anchor[1] == "m":
639
+ top -= (len(lines) - 1) * line_spacing / 2.0
640
+ elif anchor[1] == "d":
641
+ top -= (len(lines) - 1) * line_spacing
642
+
643
+ for idx, line in enumerate(lines):
644
+ left = xy[0]
645
+ width_difference = max_width - widths[idx]
646
+
647
+ # first align left by anchor
648
+ if anchor[0] == "m":
649
+ left -= width_difference / 2.0
650
+ elif anchor[0] == "r":
651
+ left -= width_difference
652
+
653
+ # then align by align parameter
654
+ if align == "left":
655
+ pass
656
+ elif align == "center":
657
+ left += width_difference / 2.0
658
+ elif align == "right":
659
+ left += width_difference
660
+ else:
661
+ msg = 'align must be "left", "center" or "right"'
662
+ raise ValueError(msg)
663
+
664
+ self.text(
665
+ (left, top),
666
+ line,
667
+ fill,
668
+ font,
669
+ anchor,
670
+ direction=direction,
671
+ features=features,
672
+ language=language,
673
+ stroke_width=stroke_width,
674
+ stroke_fill=stroke_fill,
675
+ embedded_color=embedded_color,
676
+ )
677
+ top += line_spacing
678
+
679
+ def textlength(
680
+ self,
681
+ text,
682
+ font=None,
683
+ direction=None,
684
+ features=None,
685
+ language=None,
686
+ embedded_color=False,
687
+ *,
688
+ font_size=None,
689
+ ):
690
+ """Get the length of a given string, in pixels with 1/64 precision."""
691
+ if self._multiline_check(text):
692
+ msg = "can't measure length of multiline text"
693
+ raise ValueError(msg)
694
+ if embedded_color and self.mode not in ("RGB", "RGBA"):
695
+ msg = "Embedded color supported only in RGB and RGBA modes"
696
+ raise ValueError(msg)
697
+
698
+ if font is None:
699
+ font = self._getfont(font_size)
700
+ mode = "RGBA" if embedded_color else self.fontmode
701
+ return font.getlength(text, mode, direction, features, language)
702
+
703
+ def textbbox(
704
+ self,
705
+ xy,
706
+ text,
707
+ font=None,
708
+ anchor=None,
709
+ spacing=4,
710
+ align="left",
711
+ direction=None,
712
+ features=None,
713
+ language=None,
714
+ stroke_width=0,
715
+ embedded_color=False,
716
+ *,
717
+ font_size=None,
718
+ ) -> tuple[int, int, int, int]:
719
+ """Get the bounding box of a given string, in pixels."""
720
+ if embedded_color and self.mode not in ("RGB", "RGBA"):
721
+ msg = "Embedded color supported only in RGB and RGBA modes"
722
+ raise ValueError(msg)
723
+
724
+ if font is None:
725
+ font = self._getfont(font_size)
726
+
727
+ if self._multiline_check(text):
728
+ return self.multiline_textbbox(
729
+ xy,
730
+ text,
731
+ font,
732
+ anchor,
733
+ spacing,
734
+ align,
735
+ direction,
736
+ features,
737
+ language,
738
+ stroke_width,
739
+ embedded_color,
740
+ )
741
+
742
+ mode = "RGBA" if embedded_color else self.fontmode
743
+ bbox = font.getbbox(
744
+ text, mode, direction, features, language, stroke_width, anchor
745
+ )
746
+ return bbox[0] + xy[0], bbox[1] + xy[1], bbox[2] + xy[0], bbox[3] + xy[1]
747
+
748
+ def multiline_textbbox(
749
+ self,
750
+ xy,
751
+ text,
752
+ font=None,
753
+ anchor=None,
754
+ spacing=4,
755
+ align="left",
756
+ direction=None,
757
+ features=None,
758
+ language=None,
759
+ stroke_width=0,
760
+ embedded_color=False,
761
+ *,
762
+ font_size=None,
763
+ ) -> tuple[int, int, int, int]:
764
+ if direction == "ttb":
765
+ msg = "ttb direction is unsupported for multiline text"
766
+ raise ValueError(msg)
767
+
768
+ if anchor is None:
769
+ anchor = "la"
770
+ elif len(anchor) != 2:
771
+ msg = "anchor must be a 2 character string"
772
+ raise ValueError(msg)
773
+ elif anchor[1] in "tb":
774
+ msg = "anchor not supported for multiline text"
775
+ raise ValueError(msg)
776
+
777
+ if font is None:
778
+ font = self._getfont(font_size)
779
+
780
+ widths = []
781
+ max_width = 0
782
+ lines = self._multiline_split(text)
783
+ line_spacing = self._multiline_spacing(font, spacing, stroke_width)
784
+ for line in lines:
785
+ line_width = self.textlength(
786
+ line,
787
+ font,
788
+ direction=direction,
789
+ features=features,
790
+ language=language,
791
+ embedded_color=embedded_color,
792
+ )
793
+ widths.append(line_width)
794
+ max_width = max(max_width, line_width)
795
+
796
+ top = xy[1]
797
+ if anchor[1] == "m":
798
+ top -= (len(lines) - 1) * line_spacing / 2.0
799
+ elif anchor[1] == "d":
800
+ top -= (len(lines) - 1) * line_spacing
801
+
802
+ bbox: tuple[int, int, int, int] | None = None
803
+
804
+ for idx, line in enumerate(lines):
805
+ left = xy[0]
806
+ width_difference = max_width - widths[idx]
807
+
808
+ # first align left by anchor
809
+ if anchor[0] == "m":
810
+ left -= width_difference / 2.0
811
+ elif anchor[0] == "r":
812
+ left -= width_difference
813
+
814
+ # then align by align parameter
815
+ if align == "left":
816
+ pass
817
+ elif align == "center":
818
+ left += width_difference / 2.0
819
+ elif align == "right":
820
+ left += width_difference
821
+ else:
822
+ msg = 'align must be "left", "center" or "right"'
823
+ raise ValueError(msg)
824
+
825
+ bbox_line = self.textbbox(
826
+ (left, top),
827
+ line,
828
+ font,
829
+ anchor,
830
+ direction=direction,
831
+ features=features,
832
+ language=language,
833
+ stroke_width=stroke_width,
834
+ embedded_color=embedded_color,
835
+ )
836
+ if bbox is None:
837
+ bbox = bbox_line
838
+ else:
839
+ bbox = (
840
+ min(bbox[0], bbox_line[0]),
841
+ min(bbox[1], bbox_line[1]),
842
+ max(bbox[2], bbox_line[2]),
843
+ max(bbox[3], bbox_line[3]),
844
+ )
845
+
846
+ top += line_spacing
847
+
848
+ if bbox is None:
849
+ return xy[0], xy[1], xy[0], xy[1]
850
+ return bbox
851
+
852
+
853
+ def Draw(im, mode: str | None = None) -> ImageDraw:
854
+ """
855
+ A simple 2D drawing interface for PIL images.
856
+
857
+ :param im: The image to draw in.
858
+ :param mode: Optional mode to use for color values. For RGB
859
+ images, this argument can be RGB or RGBA (to blend the
860
+ drawing into the image). For all other modes, this argument
861
+ must be the same as the image mode. If omitted, the mode
862
+ defaults to the mode of the image.
863
+ """
864
+ try:
865
+ return im.getdraw(mode)
866
+ except AttributeError:
867
+ return ImageDraw(im, mode)
868
+
869
+
870
+ # experimental access to the outline API
871
+ try:
872
+ Outline = Image.core.outline
873
+ except AttributeError:
874
+ Outline = None
875
+
876
+
877
+ def getdraw(im=None, hints=None):
878
+ """
879
+ (Experimental) A more advanced 2D drawing interface for PIL images,
880
+ based on the WCK interface.
881
+
882
+ :param im: The image to draw in.
883
+ :param hints: An optional list of hints.
884
+ :returns: A (drawing context, drawing resource factory) tuple.
885
+ """
886
+ # FIXME: this needs more work!
887
+ # FIXME: come up with a better 'hints' scheme.
888
+ handler = None
889
+ if not hints or "nicest" in hints:
890
+ try:
891
+ from . import _imagingagg as handler
892
+ except ImportError:
893
+ pass
894
+ if handler is None:
895
+ from . import ImageDraw2 as handler
896
+ if im:
897
+ im = handler.Draw(im)
898
+ return im, handler
899
+
900
+
901
+ def floodfill(image: Image.Image, xy, value, border=None, thresh=0) -> None:
902
+ """
903
+ (experimental) Fills a bounded region with a given color.
904
+
905
+ :param image: Target image.
906
+ :param xy: Seed position (a 2-item coordinate tuple). See
907
+ :ref:`coordinate-system`.
908
+ :param value: Fill color.
909
+ :param border: Optional border value. If given, the region consists of
910
+ pixels with a color different from the border color. If not given,
911
+ the region consists of pixels having the same color as the seed
912
+ pixel.
913
+ :param thresh: Optional threshold value which specifies a maximum
914
+ tolerable difference of a pixel value from the 'background' in
915
+ order for it to be replaced. Useful for filling regions of
916
+ non-homogeneous, but similar, colors.
917
+ """
918
+ # based on an implementation by Eric S. Raymond
919
+ # amended by yo1995 @20180806
920
+ pixel = image.load()
921
+ x, y = xy
922
+ try:
923
+ background = pixel[x, y]
924
+ if _color_diff(value, background) <= thresh:
925
+ return # seed point already has fill color
926
+ pixel[x, y] = value
927
+ except (ValueError, IndexError):
928
+ return # seed point outside image
929
+ edge = {(x, y)}
930
+ # use a set to keep record of current and previous edge pixels
931
+ # to reduce memory consumption
932
+ full_edge = set()
933
+ while edge:
934
+ new_edge = set()
935
+ for x, y in edge: # 4 adjacent method
936
+ for s, t in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)):
937
+ # If already processed, or if a coordinate is negative, skip
938
+ if (s, t) in full_edge or s < 0 or t < 0:
939
+ continue
940
+ try:
941
+ p = pixel[s, t]
942
+ except (ValueError, IndexError):
943
+ pass
944
+ else:
945
+ full_edge.add((s, t))
946
+ if border is None:
947
+ fill = _color_diff(p, background) <= thresh
948
+ else:
949
+ fill = p not in (value, border)
950
+ if fill:
951
+ pixel[s, t] = value
952
+ new_edge.add((s, t))
953
+ full_edge = edge # discard pixels processed
954
+ edge = new_edge
955
+
956
+
957
+ def _compute_regular_polygon_vertices(
958
+ bounding_circle, n_sides, rotation
959
+ ) -> list[tuple[float, float]]:
960
+ """
961
+ Generate a list of vertices for a 2D regular polygon.
962
+
963
+ :param bounding_circle: The bounding circle is a tuple defined
964
+ by a point and radius. The polygon is inscribed in this circle.
965
+ (e.g. ``bounding_circle=(x, y, r)`` or ``((x, y), r)``)
966
+ :param n_sides: Number of sides
967
+ (e.g. ``n_sides=3`` for a triangle, ``6`` for a hexagon)
968
+ :param rotation: Apply an arbitrary rotation to the polygon
969
+ (e.g. ``rotation=90``, applies a 90 degree rotation)
970
+ :return: List of regular polygon vertices
971
+ (e.g. ``[(25, 50), (50, 50), (50, 25), (25, 25)]``)
972
+
973
+ How are the vertices computed?
974
+ 1. Compute the following variables
975
+ - theta: Angle between the apothem & the nearest polygon vertex
976
+ - side_length: Length of each polygon edge
977
+ - centroid: Center of bounding circle (1st, 2nd elements of bounding_circle)
978
+ - polygon_radius: Polygon radius (last element of bounding_circle)
979
+ - angles: Location of each polygon vertex in polar grid
980
+ (e.g. A square with 0 degree rotation => [225.0, 315.0, 45.0, 135.0])
981
+
982
+ 2. For each angle in angles, get the polygon vertex at that angle
983
+ The vertex is computed using the equation below.
984
+ X= xcos(φ) + ysin(φ)
985
+ Y= −xsin(φ) + ycos(φ)
986
+
987
+ Note:
988
+ φ = angle in degrees
989
+ x = 0
990
+ y = polygon_radius
991
+
992
+ The formula above assumes rotation around the origin.
993
+ In our case, we are rotating around the centroid.
994
+ To account for this, we use the formula below
995
+ X = xcos(φ) + ysin(φ) + centroid_x
996
+ Y = −xsin(φ) + ycos(φ) + centroid_y
997
+ """
998
+ # 1. Error Handling
999
+ # 1.1 Check `n_sides` has an appropriate value
1000
+ if not isinstance(n_sides, int):
1001
+ msg = "n_sides should be an int"
1002
+ raise TypeError(msg)
1003
+ if n_sides < 3:
1004
+ msg = "n_sides should be an int > 2"
1005
+ raise ValueError(msg)
1006
+
1007
+ # 1.2 Check `bounding_circle` has an appropriate value
1008
+ if not isinstance(bounding_circle, (list, tuple)):
1009
+ msg = "bounding_circle should be a sequence"
1010
+ raise TypeError(msg)
1011
+
1012
+ if len(bounding_circle) == 3:
1013
+ *centroid, polygon_radius = bounding_circle
1014
+ elif len(bounding_circle) == 2:
1015
+ centroid, polygon_radius = bounding_circle
1016
+ else:
1017
+ msg = (
1018
+ "bounding_circle should contain 2D coordinates "
1019
+ "and a radius (e.g. (x, y, r) or ((x, y), r) )"
1020
+ )
1021
+ raise ValueError(msg)
1022
+
1023
+ if not all(isinstance(i, (int, float)) for i in (*centroid, polygon_radius)):
1024
+ msg = "bounding_circle should only contain numeric data"
1025
+ raise ValueError(msg)
1026
+
1027
+ if not len(centroid) == 2:
1028
+ msg = "bounding_circle centre should contain 2D coordinates (e.g. (x, y))"
1029
+ raise ValueError(msg)
1030
+
1031
+ if polygon_radius <= 0:
1032
+ msg = "bounding_circle radius should be > 0"
1033
+ raise ValueError(msg)
1034
+
1035
+ # 1.3 Check `rotation` has an appropriate value
1036
+ if not isinstance(rotation, (int, float)):
1037
+ msg = "rotation should be an int or float"
1038
+ raise ValueError(msg)
1039
+
1040
+ # 2. Define Helper Functions
1041
+ def _apply_rotation(point: list[float], degrees: float) -> tuple[int, int]:
1042
+ return (
1043
+ round(
1044
+ point[0] * math.cos(math.radians(360 - degrees))
1045
+ - point[1] * math.sin(math.radians(360 - degrees))
1046
+ + centroid[0],
1047
+ 2,
1048
+ ),
1049
+ round(
1050
+ point[1] * math.cos(math.radians(360 - degrees))
1051
+ + point[0] * math.sin(math.radians(360 - degrees))
1052
+ + centroid[1],
1053
+ 2,
1054
+ ),
1055
+ )
1056
+
1057
+ def _compute_polygon_vertex(angle: float) -> tuple[int, int]:
1058
+ start_point = [polygon_radius, 0]
1059
+ return _apply_rotation(start_point, angle)
1060
+
1061
+ def _get_angles(n_sides: int, rotation: float) -> list[float]:
1062
+ angles = []
1063
+ degrees = 360 / n_sides
1064
+ # Start with the bottom left polygon vertex
1065
+ current_angle = (270 - 0.5 * degrees) + rotation
1066
+ for _ in range(0, n_sides):
1067
+ angles.append(current_angle)
1068
+ current_angle += degrees
1069
+ if current_angle > 360:
1070
+ current_angle -= 360
1071
+ return angles
1072
+
1073
+ # 3. Variable Declarations
1074
+ angles = _get_angles(n_sides, rotation)
1075
+
1076
+ # 4. Compute Vertices
1077
+ return [_compute_polygon_vertex(angle) for angle in angles]
1078
+
1079
+
1080
+ def _color_diff(color1, color2: float | tuple[int, ...]) -> float:
1081
+ """
1082
+ Uses 1-norm distance to calculate difference between two values.
1083
+ """
1084
+ if isinstance(color2, tuple):
1085
+ return sum(abs(color1[i] - color2[i]) for i in range(0, len(color2)))
1086
+ else:
1087
+ return abs(color1 - color2)
.venv/Lib/site-packages/PIL/ImageDraw2.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library
3
+ # $Id$
4
+ #
5
+ # WCK-style drawing interface operations
6
+ #
7
+ # History:
8
+ # 2003-12-07 fl created
9
+ # 2005-05-15 fl updated; added to PIL as ImageDraw2
10
+ # 2005-05-15 fl added text support
11
+ # 2005-05-20 fl added arc/chord/pieslice support
12
+ #
13
+ # Copyright (c) 2003-2005 by Secret Labs AB
14
+ # Copyright (c) 2003-2005 by Fredrik Lundh
15
+ #
16
+ # See the README file for information on usage and redistribution.
17
+ #
18
+
19
+
20
+ """
21
+ (Experimental) WCK-style drawing interface operations
22
+
23
+ .. seealso:: :py:mod:`PIL.ImageDraw`
24
+ """
25
+ from __future__ import annotations
26
+
27
+ from . import Image, ImageColor, ImageDraw, ImageFont, ImagePath
28
+
29
+
30
+ class Pen:
31
+ """Stores an outline color and width."""
32
+
33
+ def __init__(self, color, width=1, opacity=255):
34
+ self.color = ImageColor.getrgb(color)
35
+ self.width = width
36
+
37
+
38
+ class Brush:
39
+ """Stores a fill color"""
40
+
41
+ def __init__(self, color, opacity=255):
42
+ self.color = ImageColor.getrgb(color)
43
+
44
+
45
+ class Font:
46
+ """Stores a TrueType font and color"""
47
+
48
+ def __init__(self, color, file, size=12):
49
+ # FIXME: add support for bitmap fonts
50
+ self.color = ImageColor.getrgb(color)
51
+ self.font = ImageFont.truetype(file, size)
52
+
53
+
54
+ class Draw:
55
+ """
56
+ (Experimental) WCK-style drawing interface
57
+ """
58
+
59
+ def __init__(self, image, size=None, color=None):
60
+ if not hasattr(image, "im"):
61
+ image = Image.new(image, size, color)
62
+ self.draw = ImageDraw.Draw(image)
63
+ self.image = image
64
+ self.transform = None
65
+
66
+ def flush(self):
67
+ return self.image
68
+
69
+ def render(self, op, xy, pen, brush=None):
70
+ # handle color arguments
71
+ outline = fill = None
72
+ width = 1
73
+ if isinstance(pen, Pen):
74
+ outline = pen.color
75
+ width = pen.width
76
+ elif isinstance(brush, Pen):
77
+ outline = brush.color
78
+ width = brush.width
79
+ if isinstance(brush, Brush):
80
+ fill = brush.color
81
+ elif isinstance(pen, Brush):
82
+ fill = pen.color
83
+ # handle transformation
84
+ if self.transform:
85
+ xy = ImagePath.Path(xy)
86
+ xy.transform(self.transform)
87
+ # render the item
88
+ if op == "line":
89
+ self.draw.line(xy, fill=outline, width=width)
90
+ else:
91
+ getattr(self.draw, op)(xy, fill=fill, outline=outline)
92
+
93
+ def settransform(self, offset):
94
+ """Sets a transformation offset."""
95
+ (xoffset, yoffset) = offset
96
+ self.transform = (1, 0, xoffset, 0, 1, yoffset)
97
+
98
+ def arc(self, xy, start, end, *options):
99
+ """
100
+ Draws an arc (a portion of a circle outline) between the start and end
101
+ angles, inside the given bounding box.
102
+
103
+ .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.arc`
104
+ """
105
+ self.render("arc", xy, start, end, *options)
106
+
107
+ def chord(self, xy, start, end, *options):
108
+ """
109
+ Same as :py:meth:`~PIL.ImageDraw2.Draw.arc`, but connects the end points
110
+ with a straight line.
111
+
112
+ .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.chord`
113
+ """
114
+ self.render("chord", xy, start, end, *options)
115
+
116
+ def ellipse(self, xy, *options):
117
+ """
118
+ Draws an ellipse inside the given bounding box.
119
+
120
+ .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.ellipse`
121
+ """
122
+ self.render("ellipse", xy, *options)
123
+
124
+ def line(self, xy, *options):
125
+ """
126
+ Draws a line between the coordinates in the ``xy`` list.
127
+
128
+ .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.line`
129
+ """
130
+ self.render("line", xy, *options)
131
+
132
+ def pieslice(self, xy, start, end, *options):
133
+ """
134
+ Same as arc, but also draws straight lines between the end points and the
135
+ center of the bounding box.
136
+
137
+ .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.pieslice`
138
+ """
139
+ self.render("pieslice", xy, start, end, *options)
140
+
141
+ def polygon(self, xy, *options):
142
+ """
143
+ Draws a polygon.
144
+
145
+ The polygon outline consists of straight lines between the given
146
+ coordinates, plus a straight line between the last and the first
147
+ coordinate.
148
+
149
+
150
+ .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.polygon`
151
+ """
152
+ self.render("polygon", xy, *options)
153
+
154
+ def rectangle(self, xy, *options):
155
+ """
156
+ Draws a rectangle.
157
+
158
+ .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.rectangle`
159
+ """
160
+ self.render("rectangle", xy, *options)
161
+
162
+ def text(self, xy, text, font):
163
+ """
164
+ Draws the string at the given position.
165
+
166
+ .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.text`
167
+ """
168
+ if self.transform:
169
+ xy = ImagePath.Path(xy)
170
+ xy.transform(self.transform)
171
+ self.draw.text(xy, text, font=font.font, fill=font.color)
172
+
173
+ def textbbox(self, xy, text, font):
174
+ """
175
+ Returns bounding box (in pixels) of given text.
176
+
177
+ :return: ``(left, top, right, bottom)`` bounding box
178
+
179
+ .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.textbbox`
180
+ """
181
+ if self.transform:
182
+ xy = ImagePath.Path(xy)
183
+ xy.transform(self.transform)
184
+ return self.draw.textbbox(xy, text, font=font.font)
185
+
186
+ def textlength(self, text, font):
187
+ """
188
+ Returns length (in pixels) of given text.
189
+ This is the amount by which following text should be offset.
190
+
191
+ .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.textlength`
192
+ """
193
+ return self.draw.textlength(text, font=font.font)
.venv/Lib/site-packages/PIL/ImageEnhance.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # image enhancement classes
6
+ #
7
+ # For a background, see "Image Processing By Interpolation and
8
+ # Extrapolation", Paul Haeberli and Douglas Voorhies. Available
9
+ # at http://www.graficaobscura.com/interp/index.html
10
+ #
11
+ # History:
12
+ # 1996-03-23 fl Created
13
+ # 2009-06-16 fl Fixed mean calculation
14
+ #
15
+ # Copyright (c) Secret Labs AB 1997.
16
+ # Copyright (c) Fredrik Lundh 1996.
17
+ #
18
+ # See the README file for information on usage and redistribution.
19
+ #
20
+ from __future__ import annotations
21
+
22
+ from . import Image, ImageFilter, ImageStat
23
+
24
+
25
+ class _Enhance:
26
+ def enhance(self, factor):
27
+ """
28
+ Returns an enhanced image.
29
+
30
+ :param factor: A floating point value controlling the enhancement.
31
+ Factor 1.0 always returns a copy of the original image,
32
+ lower factors mean less color (brightness, contrast,
33
+ etc), and higher values more. There are no restrictions
34
+ on this value.
35
+ :rtype: :py:class:`~PIL.Image.Image`
36
+ """
37
+ return Image.blend(self.degenerate, self.image, factor)
38
+
39
+
40
+ class Color(_Enhance):
41
+ """Adjust image color balance.
42
+
43
+ This class can be used to adjust the colour balance of an image, in
44
+ a manner similar to the controls on a colour TV set. An enhancement
45
+ factor of 0.0 gives a black and white image. A factor of 1.0 gives
46
+ the original image.
47
+ """
48
+
49
+ def __init__(self, image):
50
+ self.image = image
51
+ self.intermediate_mode = "L"
52
+ if "A" in image.getbands():
53
+ self.intermediate_mode = "LA"
54
+
55
+ self.degenerate = image.convert(self.intermediate_mode).convert(image.mode)
56
+
57
+
58
+ class Contrast(_Enhance):
59
+ """Adjust image contrast.
60
+
61
+ This class can be used to control the contrast of an image, similar
62
+ to the contrast control on a TV set. An enhancement factor of 0.0
63
+ gives a solid gray image. A factor of 1.0 gives the original image.
64
+ """
65
+
66
+ def __init__(self, image):
67
+ self.image = image
68
+ mean = int(ImageStat.Stat(image.convert("L")).mean[0] + 0.5)
69
+ self.degenerate = Image.new("L", image.size, mean).convert(image.mode)
70
+
71
+ if "A" in image.getbands():
72
+ self.degenerate.putalpha(image.getchannel("A"))
73
+
74
+
75
+ class Brightness(_Enhance):
76
+ """Adjust image brightness.
77
+
78
+ This class can be used to control the brightness of an image. An
79
+ enhancement factor of 0.0 gives a black image. A factor of 1.0 gives the
80
+ original image.
81
+ """
82
+
83
+ def __init__(self, image):
84
+ self.image = image
85
+ self.degenerate = Image.new(image.mode, image.size, 0)
86
+
87
+ if "A" in image.getbands():
88
+ self.degenerate.putalpha(image.getchannel("A"))
89
+
90
+
91
+ class Sharpness(_Enhance):
92
+ """Adjust image sharpness.
93
+
94
+ This class can be used to adjust the sharpness of an image. An
95
+ enhancement factor of 0.0 gives a blurred image, a factor of 1.0 gives the
96
+ original image, and a factor of 2.0 gives a sharpened image.
97
+ """
98
+
99
+ def __init__(self, image):
100
+ self.image = image
101
+ self.degenerate = image.filter(ImageFilter.SMOOTH)
102
+
103
+ if "A" in image.getbands():
104
+ self.degenerate.putalpha(image.getchannel("A"))
.venv/Lib/site-packages/PIL/ImageFile.py ADDED
@@ -0,0 +1,797 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # base class for image file handlers
6
+ #
7
+ # history:
8
+ # 1995-09-09 fl Created
9
+ # 1996-03-11 fl Fixed load mechanism.
10
+ # 1996-04-15 fl Added pcx/xbm decoders.
11
+ # 1996-04-30 fl Added encoders.
12
+ # 1996-12-14 fl Added load helpers
13
+ # 1997-01-11 fl Use encode_to_file where possible
14
+ # 1997-08-27 fl Flush output in _save
15
+ # 1998-03-05 fl Use memory mapping for some modes
16
+ # 1999-02-04 fl Use memory mapping also for "I;16" and "I;16B"
17
+ # 1999-05-31 fl Added image parser
18
+ # 2000-10-12 fl Set readonly flag on memory-mapped images
19
+ # 2002-03-20 fl Use better messages for common decoder errors
20
+ # 2003-04-21 fl Fall back on mmap/map_buffer if map is not available
21
+ # 2003-10-30 fl Added StubImageFile class
22
+ # 2004-02-25 fl Made incremental parser more robust
23
+ #
24
+ # Copyright (c) 1997-2004 by Secret Labs AB
25
+ # Copyright (c) 1995-2004 by Fredrik Lundh
26
+ #
27
+ # See the README file for information on usage and redistribution.
28
+ #
29
+ from __future__ import annotations
30
+
31
+ import io
32
+ import itertools
33
+ import struct
34
+ import sys
35
+ from typing import IO, Any, NamedTuple
36
+
37
+ from . import Image
38
+ from ._deprecate import deprecate
39
+ from ._util import is_path
40
+
41
+ MAXBLOCK = 65536
42
+
43
+ SAFEBLOCK = 1024 * 1024
44
+
45
+ LOAD_TRUNCATED_IMAGES = False
46
+ """Whether or not to load truncated image files. User code may change this."""
47
+
48
+ ERRORS = {
49
+ -1: "image buffer overrun error",
50
+ -2: "decoding error",
51
+ -3: "unknown error",
52
+ -8: "bad configuration",
53
+ -9: "out of memory error",
54
+ }
55
+ """
56
+ Dict of known error codes returned from :meth:`.PyDecoder.decode`,
57
+ :meth:`.PyEncoder.encode` :meth:`.PyEncoder.encode_to_pyfd` and
58
+ :meth:`.PyEncoder.encode_to_file`.
59
+ """
60
+
61
+
62
+ #
63
+ # --------------------------------------------------------------------
64
+ # Helpers
65
+
66
+
67
+ def _get_oserror(error, *, encoder):
68
+ try:
69
+ msg = Image.core.getcodecstatus(error)
70
+ except AttributeError:
71
+ msg = ERRORS.get(error)
72
+ if not msg:
73
+ msg = f"{'encoder' if encoder else 'decoder'} error {error}"
74
+ msg += f" when {'writing' if encoder else 'reading'} image file"
75
+ return OSError(msg)
76
+
77
+
78
+ def raise_oserror(error):
79
+ deprecate(
80
+ "raise_oserror",
81
+ 12,
82
+ action="It is only useful for translating error codes returned by a codec's "
83
+ "decode() method, which ImageFile already does automatically.",
84
+ )
85
+ raise _get_oserror(error, encoder=False)
86
+
87
+
88
+ def _tilesort(t):
89
+ # sort on offset
90
+ return t[2]
91
+
92
+
93
+ class _Tile(NamedTuple):
94
+ codec_name: str
95
+ extents: tuple[int, int, int, int]
96
+ offset: int
97
+ args: tuple[Any, ...] | str | None
98
+
99
+
100
+ #
101
+ # --------------------------------------------------------------------
102
+ # ImageFile base class
103
+
104
+
105
+ class ImageFile(Image.Image):
106
+ """Base class for image file format handlers."""
107
+
108
+ def __init__(self, fp=None, filename=None):
109
+ super().__init__()
110
+
111
+ self._min_frame = 0
112
+
113
+ self.custom_mimetype = None
114
+
115
+ self.tile = None
116
+ """ A list of tile descriptors, or ``None`` """
117
+
118
+ self.readonly = 1 # until we know better
119
+
120
+ self.decoderconfig = ()
121
+ self.decodermaxblock = MAXBLOCK
122
+
123
+ if is_path(fp):
124
+ # filename
125
+ self.fp = open(fp, "rb")
126
+ self.filename = fp
127
+ self._exclusive_fp = True
128
+ else:
129
+ # stream
130
+ self.fp = fp
131
+ self.filename = filename
132
+ # can be overridden
133
+ self._exclusive_fp = None
134
+
135
+ try:
136
+ try:
137
+ self._open()
138
+ except (
139
+ IndexError, # end of data
140
+ TypeError, # end of data (ord)
141
+ KeyError, # unsupported mode
142
+ EOFError, # got header but not the first frame
143
+ struct.error,
144
+ ) as v:
145
+ raise SyntaxError(v) from v
146
+
147
+ if not self.mode or self.size[0] <= 0 or self.size[1] <= 0:
148
+ msg = "not identified by this driver"
149
+ raise SyntaxError(msg)
150
+ except BaseException:
151
+ # close the file only if we have opened it this constructor
152
+ if self._exclusive_fp:
153
+ self.fp.close()
154
+ raise
155
+
156
+ def get_format_mimetype(self):
157
+ if self.custom_mimetype:
158
+ return self.custom_mimetype
159
+ if self.format is not None:
160
+ return Image.MIME.get(self.format.upper())
161
+
162
+ def __setstate__(self, state):
163
+ self.tile = []
164
+ super().__setstate__(state)
165
+
166
+ def verify(self):
167
+ """Check file integrity"""
168
+
169
+ # raise exception if something's wrong. must be called
170
+ # directly after open, and closes file when finished.
171
+ if self._exclusive_fp:
172
+ self.fp.close()
173
+ self.fp = None
174
+
175
+ def load(self):
176
+ """Load image data based on tile list"""
177
+
178
+ if self.tile is None:
179
+ msg = "cannot load this image"
180
+ raise OSError(msg)
181
+
182
+ pixel = Image.Image.load(self)
183
+ if not self.tile:
184
+ return pixel
185
+
186
+ self.map = None
187
+ use_mmap = self.filename and len(self.tile) == 1
188
+ # As of pypy 2.1.0, memory mapping was failing here.
189
+ use_mmap = use_mmap and not hasattr(sys, "pypy_version_info")
190
+
191
+ readonly = 0
192
+
193
+ # look for read/seek overrides
194
+ try:
195
+ read = self.load_read
196
+ # don't use mmap if there are custom read/seek functions
197
+ use_mmap = False
198
+ except AttributeError:
199
+ read = self.fp.read
200
+
201
+ try:
202
+ seek = self.load_seek
203
+ use_mmap = False
204
+ except AttributeError:
205
+ seek = self.fp.seek
206
+
207
+ if use_mmap:
208
+ # try memory mapping
209
+ decoder_name, extents, offset, args = self.tile[0]
210
+ if isinstance(args, str):
211
+ args = (args, 0, 1)
212
+ if (
213
+ decoder_name == "raw"
214
+ and len(args) >= 3
215
+ and args[0] == self.mode
216
+ and args[0] in Image._MAPMODES
217
+ ):
218
+ try:
219
+ # use mmap, if possible
220
+ import mmap
221
+
222
+ with open(self.filename) as fp:
223
+ self.map = mmap.mmap(fp.fileno(), 0, access=mmap.ACCESS_READ)
224
+ if offset + self.size[1] * args[1] > self.map.size():
225
+ msg = "buffer is not large enough"
226
+ raise OSError(msg)
227
+ self.im = Image.core.map_buffer(
228
+ self.map, self.size, decoder_name, offset, args
229
+ )
230
+ readonly = 1
231
+ # After trashing self.im,
232
+ # we might need to reload the palette data.
233
+ if self.palette:
234
+ self.palette.dirty = 1
235
+ except (AttributeError, OSError, ImportError):
236
+ self.map = None
237
+
238
+ self.load_prepare()
239
+ err_code = -3 # initialize to unknown error
240
+ if not self.map:
241
+ # sort tiles in file order
242
+ self.tile.sort(key=_tilesort)
243
+
244
+ try:
245
+ # FIXME: This is a hack to handle TIFF's JpegTables tag.
246
+ prefix = self.tile_prefix
247
+ except AttributeError:
248
+ prefix = b""
249
+
250
+ # Remove consecutive duplicates that only differ by their offset
251
+ self.tile = [
252
+ list(tiles)[-1]
253
+ for _, tiles in itertools.groupby(
254
+ self.tile, lambda tile: (tile[0], tile[1], tile[3])
255
+ )
256
+ ]
257
+ for decoder_name, extents, offset, args in self.tile:
258
+ seek(offset)
259
+ decoder = Image._getdecoder(
260
+ self.mode, decoder_name, args, self.decoderconfig
261
+ )
262
+ try:
263
+ decoder.setimage(self.im, extents)
264
+ if decoder.pulls_fd:
265
+ decoder.setfd(self.fp)
266
+ err_code = decoder.decode(b"")[1]
267
+ else:
268
+ b = prefix
269
+ while True:
270
+ try:
271
+ s = read(self.decodermaxblock)
272
+ except (IndexError, struct.error) as e:
273
+ # truncated png/gif
274
+ if LOAD_TRUNCATED_IMAGES:
275
+ break
276
+ else:
277
+ msg = "image file is truncated"
278
+ raise OSError(msg) from e
279
+
280
+ if not s: # truncated jpeg
281
+ if LOAD_TRUNCATED_IMAGES:
282
+ break
283
+ else:
284
+ msg = (
285
+ "image file is truncated "
286
+ f"({len(b)} bytes not processed)"
287
+ )
288
+ raise OSError(msg)
289
+
290
+ b = b + s
291
+ n, err_code = decoder.decode(b)
292
+ if n < 0:
293
+ break
294
+ b = b[n:]
295
+ finally:
296
+ # Need to cleanup here to prevent leaks
297
+ decoder.cleanup()
298
+
299
+ self.tile = []
300
+ self.readonly = readonly
301
+
302
+ self.load_end()
303
+
304
+ if self._exclusive_fp and self._close_exclusive_fp_after_loading:
305
+ self.fp.close()
306
+ self.fp = None
307
+
308
+ if not self.map and not LOAD_TRUNCATED_IMAGES and err_code < 0:
309
+ # still raised if decoder fails to return anything
310
+ raise _get_oserror(err_code, encoder=False)
311
+
312
+ return Image.Image.load(self)
313
+
314
+ def load_prepare(self):
315
+ # create image memory if necessary
316
+ if not self.im or self.im.mode != self.mode or self.im.size != self.size:
317
+ self.im = Image.core.new(self.mode, self.size)
318
+ # create palette (optional)
319
+ if self.mode == "P":
320
+ Image.Image.load(self)
321
+
322
+ def load_end(self):
323
+ # may be overridden
324
+ pass
325
+
326
+ # may be defined for contained formats
327
+ # def load_seek(self, pos):
328
+ # pass
329
+
330
+ # may be defined for blocked formats (e.g. PNG)
331
+ # def load_read(self, read_bytes):
332
+ # pass
333
+
334
+ def _seek_check(self, frame):
335
+ if (
336
+ frame < self._min_frame
337
+ # Only check upper limit on frames if additional seek operations
338
+ # are not required to do so
339
+ or (
340
+ not (hasattr(self, "_n_frames") and self._n_frames is None)
341
+ and frame >= self.n_frames + self._min_frame
342
+ )
343
+ ):
344
+ msg = "attempt to seek outside sequence"
345
+ raise EOFError(msg)
346
+
347
+ return self.tell() != frame
348
+
349
+
350
+ class StubImageFile(ImageFile):
351
+ """
352
+ Base class for stub image loaders.
353
+
354
+ A stub loader is an image loader that can identify files of a
355
+ certain format, but relies on external code to load the file.
356
+ """
357
+
358
+ def _open(self):
359
+ msg = "StubImageFile subclass must implement _open"
360
+ raise NotImplementedError(msg)
361
+
362
+ def load(self):
363
+ loader = self._load()
364
+ if loader is None:
365
+ msg = f"cannot find loader for this {self.format} file"
366
+ raise OSError(msg)
367
+ image = loader.load(self)
368
+ assert image is not None
369
+ # become the other object (!)
370
+ self.__class__ = image.__class__
371
+ self.__dict__ = image.__dict__
372
+ return image.load()
373
+
374
+ def _load(self):
375
+ """(Hook) Find actual image loader."""
376
+ msg = "StubImageFile subclass must implement _load"
377
+ raise NotImplementedError(msg)
378
+
379
+
380
+ class Parser:
381
+ """
382
+ Incremental image parser. This class implements the standard
383
+ feed/close consumer interface.
384
+ """
385
+
386
+ incremental = None
387
+ image: Image.Image | None = None
388
+ data = None
389
+ decoder = None
390
+ offset = 0
391
+ finished = 0
392
+
393
+ def reset(self):
394
+ """
395
+ (Consumer) Reset the parser. Note that you can only call this
396
+ method immediately after you've created a parser; parser
397
+ instances cannot be reused.
398
+ """
399
+ assert self.data is None, "cannot reuse parsers"
400
+
401
+ def feed(self, data):
402
+ """
403
+ (Consumer) Feed data to the parser.
404
+
405
+ :param data: A string buffer.
406
+ :exception OSError: If the parser failed to parse the image file.
407
+ """
408
+ # collect data
409
+
410
+ if self.finished:
411
+ return
412
+
413
+ if self.data is None:
414
+ self.data = data
415
+ else:
416
+ self.data = self.data + data
417
+
418
+ # parse what we have
419
+ if self.decoder:
420
+ if self.offset > 0:
421
+ # skip header
422
+ skip = min(len(self.data), self.offset)
423
+ self.data = self.data[skip:]
424
+ self.offset = self.offset - skip
425
+ if self.offset > 0 or not self.data:
426
+ return
427
+
428
+ n, e = self.decoder.decode(self.data)
429
+
430
+ if n < 0:
431
+ # end of stream
432
+ self.data = None
433
+ self.finished = 1
434
+ if e < 0:
435
+ # decoding error
436
+ self.image = None
437
+ raise _get_oserror(e, encoder=False)
438
+ else:
439
+ # end of image
440
+ return
441
+ self.data = self.data[n:]
442
+
443
+ elif self.image:
444
+ # if we end up here with no decoder, this file cannot
445
+ # be incrementally parsed. wait until we've gotten all
446
+ # available data
447
+ pass
448
+
449
+ else:
450
+ # attempt to open this file
451
+ try:
452
+ with io.BytesIO(self.data) as fp:
453
+ im = Image.open(fp)
454
+ except OSError:
455
+ pass # not enough data
456
+ else:
457
+ flag = hasattr(im, "load_seek") or hasattr(im, "load_read")
458
+ if flag or len(im.tile) != 1:
459
+ # custom load code, or multiple tiles
460
+ self.decode = None
461
+ else:
462
+ # initialize decoder
463
+ im.load_prepare()
464
+ d, e, o, a = im.tile[0]
465
+ im.tile = []
466
+ self.decoder = Image._getdecoder(im.mode, d, a, im.decoderconfig)
467
+ self.decoder.setimage(im.im, e)
468
+
469
+ # calculate decoder offset
470
+ self.offset = o
471
+ if self.offset <= len(self.data):
472
+ self.data = self.data[self.offset :]
473
+ self.offset = 0
474
+
475
+ self.image = im
476
+
477
+ def __enter__(self):
478
+ return self
479
+
480
+ def __exit__(self, *args):
481
+ self.close()
482
+
483
+ def close(self):
484
+ """
485
+ (Consumer) Close the stream.
486
+
487
+ :returns: An image object.
488
+ :exception OSError: If the parser failed to parse the image file either
489
+ because it cannot be identified or cannot be
490
+ decoded.
491
+ """
492
+ # finish decoding
493
+ if self.decoder:
494
+ # get rid of what's left in the buffers
495
+ self.feed(b"")
496
+ self.data = self.decoder = None
497
+ if not self.finished:
498
+ msg = "image was incomplete"
499
+ raise OSError(msg)
500
+ if not self.image:
501
+ msg = "cannot parse this image"
502
+ raise OSError(msg)
503
+ if self.data:
504
+ # incremental parsing not possible; reopen the file
505
+ # not that we have all data
506
+ with io.BytesIO(self.data) as fp:
507
+ try:
508
+ self.image = Image.open(fp)
509
+ finally:
510
+ self.image.load()
511
+ return self.image
512
+
513
+
514
+ # --------------------------------------------------------------------
515
+
516
+
517
+ def _save(im, fp, tile, bufsize=0) -> None:
518
+ """Helper to save image based on tile list
519
+
520
+ :param im: Image object.
521
+ :param fp: File object.
522
+ :param tile: Tile list.
523
+ :param bufsize: Optional buffer size
524
+ """
525
+
526
+ im.load()
527
+ if not hasattr(im, "encoderconfig"):
528
+ im.encoderconfig = ()
529
+ tile.sort(key=_tilesort)
530
+ # FIXME: make MAXBLOCK a configuration parameter
531
+ # It would be great if we could have the encoder specify what it needs
532
+ # But, it would need at least the image size in most cases. RawEncode is
533
+ # a tricky case.
534
+ bufsize = max(MAXBLOCK, bufsize, im.size[0] * 4) # see RawEncode.c
535
+ try:
536
+ fh = fp.fileno()
537
+ fp.flush()
538
+ _encode_tile(im, fp, tile, bufsize, fh)
539
+ except (AttributeError, io.UnsupportedOperation) as exc:
540
+ _encode_tile(im, fp, tile, bufsize, None, exc)
541
+ if hasattr(fp, "flush"):
542
+ fp.flush()
543
+
544
+
545
+ def _encode_tile(im, fp, tile: list[_Tile], bufsize, fh, exc=None):
546
+ for encoder_name, extents, offset, args in tile:
547
+ if offset > 0:
548
+ fp.seek(offset)
549
+ encoder = Image._getencoder(im.mode, encoder_name, args, im.encoderconfig)
550
+ try:
551
+ encoder.setimage(im.im, extents)
552
+ if encoder.pushes_fd:
553
+ encoder.setfd(fp)
554
+ errcode = encoder.encode_to_pyfd()[1]
555
+ else:
556
+ if exc:
557
+ # compress to Python file-compatible object
558
+ while True:
559
+ errcode, data = encoder.encode(bufsize)[1:]
560
+ fp.write(data)
561
+ if errcode:
562
+ break
563
+ else:
564
+ # slight speedup: compress to real file object
565
+ errcode = encoder.encode_to_file(fh, bufsize)
566
+ if errcode < 0:
567
+ raise _get_oserror(errcode, encoder=True) from exc
568
+ finally:
569
+ encoder.cleanup()
570
+
571
+
572
+ def _safe_read(fp, size):
573
+ """
574
+ Reads large blocks in a safe way. Unlike fp.read(n), this function
575
+ doesn't trust the user. If the requested size is larger than
576
+ SAFEBLOCK, the file is read block by block.
577
+
578
+ :param fp: File handle. Must implement a <b>read</b> method.
579
+ :param size: Number of bytes to read.
580
+ :returns: A string containing <i>size</i> bytes of data.
581
+
582
+ Raises an OSError if the file is truncated and the read cannot be completed
583
+
584
+ """
585
+ if size <= 0:
586
+ return b""
587
+ if size <= SAFEBLOCK:
588
+ data = fp.read(size)
589
+ if len(data) < size:
590
+ msg = "Truncated File Read"
591
+ raise OSError(msg)
592
+ return data
593
+ data = []
594
+ remaining_size = size
595
+ while remaining_size > 0:
596
+ block = fp.read(min(remaining_size, SAFEBLOCK))
597
+ if not block:
598
+ break
599
+ data.append(block)
600
+ remaining_size -= len(block)
601
+ if sum(len(d) for d in data) < size:
602
+ msg = "Truncated File Read"
603
+ raise OSError(msg)
604
+ return b"".join(data)
605
+
606
+
607
+ class PyCodecState:
608
+ def __init__(self):
609
+ self.xsize = 0
610
+ self.ysize = 0
611
+ self.xoff = 0
612
+ self.yoff = 0
613
+
614
+ def extents(self):
615
+ return self.xoff, self.yoff, self.xoff + self.xsize, self.yoff + self.ysize
616
+
617
+
618
+ class PyCodec:
619
+ fd: IO[bytes] | None
620
+
621
+ def __init__(self, mode, *args):
622
+ self.im = None
623
+ self.state = PyCodecState()
624
+ self.fd = None
625
+ self.mode = mode
626
+ self.init(args)
627
+
628
+ def init(self, args):
629
+ """
630
+ Override to perform codec specific initialization
631
+
632
+ :param args: Array of args items from the tile entry
633
+ :returns: None
634
+ """
635
+ self.args = args
636
+
637
+ def cleanup(self):
638
+ """
639
+ Override to perform codec specific cleanup
640
+
641
+ :returns: None
642
+ """
643
+ pass
644
+
645
+ def setfd(self, fd):
646
+ """
647
+ Called from ImageFile to set the Python file-like object
648
+
649
+ :param fd: A Python file-like object
650
+ :returns: None
651
+ """
652
+ self.fd = fd
653
+
654
+ def setimage(self, im, extents=None):
655
+ """
656
+ Called from ImageFile to set the core output image for the codec
657
+
658
+ :param im: A core image object
659
+ :param extents: a 4 tuple of (x0, y0, x1, y1) defining the rectangle
660
+ for this tile
661
+ :returns: None
662
+ """
663
+
664
+ # following c code
665
+ self.im = im
666
+
667
+ if extents:
668
+ (x0, y0, x1, y1) = extents
669
+ else:
670
+ (x0, y0, x1, y1) = (0, 0, 0, 0)
671
+
672
+ if x0 == 0 and x1 == 0:
673
+ self.state.xsize, self.state.ysize = self.im.size
674
+ else:
675
+ self.state.xoff = x0
676
+ self.state.yoff = y0
677
+ self.state.xsize = x1 - x0
678
+ self.state.ysize = y1 - y0
679
+
680
+ if self.state.xsize <= 0 or self.state.ysize <= 0:
681
+ msg = "Size cannot be negative"
682
+ raise ValueError(msg)
683
+
684
+ if (
685
+ self.state.xsize + self.state.xoff > self.im.size[0]
686
+ or self.state.ysize + self.state.yoff > self.im.size[1]
687
+ ):
688
+ msg = "Tile cannot extend outside image"
689
+ raise ValueError(msg)
690
+
691
+
692
+ class PyDecoder(PyCodec):
693
+ """
694
+ Python implementation of a format decoder. Override this class and
695
+ add the decoding logic in the :meth:`decode` method.
696
+
697
+ See :ref:`Writing Your Own File Codec in Python<file-codecs-py>`
698
+ """
699
+
700
+ _pulls_fd = False
701
+
702
+ @property
703
+ def pulls_fd(self):
704
+ return self._pulls_fd
705
+
706
+ def decode(self, buffer):
707
+ """
708
+ Override to perform the decoding process.
709
+
710
+ :param buffer: A bytes object with the data to be decoded.
711
+ :returns: A tuple of ``(bytes consumed, errcode)``.
712
+ If finished with decoding return -1 for the bytes consumed.
713
+ Err codes are from :data:`.ImageFile.ERRORS`.
714
+ """
715
+ msg = "unavailable in base decoder"
716
+ raise NotImplementedError(msg)
717
+
718
+ def set_as_raw(self, data: bytes, rawmode=None) -> None:
719
+ """
720
+ Convenience method to set the internal image from a stream of raw data
721
+
722
+ :param data: Bytes to be set
723
+ :param rawmode: The rawmode to be used for the decoder.
724
+ If not specified, it will default to the mode of the image
725
+ :returns: None
726
+ """
727
+
728
+ if not rawmode:
729
+ rawmode = self.mode
730
+ d = Image._getdecoder(self.mode, "raw", rawmode)
731
+ d.setimage(self.im, self.state.extents())
732
+ s = d.decode(data)
733
+
734
+ if s[0] >= 0:
735
+ msg = "not enough image data"
736
+ raise ValueError(msg)
737
+ if s[1] != 0:
738
+ msg = "cannot decode image data"
739
+ raise ValueError(msg)
740
+
741
+
742
+ class PyEncoder(PyCodec):
743
+ """
744
+ Python implementation of a format encoder. Override this class and
745
+ add the decoding logic in the :meth:`encode` method.
746
+
747
+ See :ref:`Writing Your Own File Codec in Python<file-codecs-py>`
748
+ """
749
+
750
+ _pushes_fd = False
751
+
752
+ @property
753
+ def pushes_fd(self):
754
+ return self._pushes_fd
755
+
756
+ def encode(self, bufsize):
757
+ """
758
+ Override to perform the encoding process.
759
+
760
+ :param bufsize: Buffer size.
761
+ :returns: A tuple of ``(bytes encoded, errcode, bytes)``.
762
+ If finished with encoding return 1 for the error code.
763
+ Err codes are from :data:`.ImageFile.ERRORS`.
764
+ """
765
+ msg = "unavailable in base encoder"
766
+ raise NotImplementedError(msg)
767
+
768
+ def encode_to_pyfd(self):
769
+ """
770
+ If ``pushes_fd`` is ``True``, then this method will be used,
771
+ and ``encode()`` will only be called once.
772
+
773
+ :returns: A tuple of ``(bytes consumed, errcode)``.
774
+ Err codes are from :data:`.ImageFile.ERRORS`.
775
+ """
776
+ if not self.pushes_fd:
777
+ return 0, -8 # bad configuration
778
+ bytes_consumed, errcode, data = self.encode(0)
779
+ if data:
780
+ self.fd.write(data)
781
+ return bytes_consumed, errcode
782
+
783
+ def encode_to_file(self, fh, bufsize):
784
+ """
785
+ :param fh: File handle.
786
+ :param bufsize: Buffer size.
787
+
788
+ :returns: If finished successfully, return 0.
789
+ Otherwise, return an error code. Err codes are from
790
+ :data:`.ImageFile.ERRORS`.
791
+ """
792
+ errcode = 0
793
+ while errcode == 0:
794
+ status, errcode, buf = self.encode(bufsize)
795
+ if status > 0:
796
+ fh.write(buf[status:])
797
+ return errcode
.venv/Lib/site-packages/PIL/ImageFilter.py ADDED
@@ -0,0 +1,565 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # standard filters
6
+ #
7
+ # History:
8
+ # 1995-11-27 fl Created
9
+ # 2002-06-08 fl Added rank and mode filters
10
+ # 2003-09-15 fl Fixed rank calculation in rank filter; added expand call
11
+ #
12
+ # Copyright (c) 1997-2003 by Secret Labs AB.
13
+ # Copyright (c) 1995-2002 by Fredrik Lundh.
14
+ #
15
+ # See the README file for information on usage and redistribution.
16
+ #
17
+ from __future__ import annotations
18
+
19
+ import functools
20
+
21
+
22
+ class Filter:
23
+ pass
24
+
25
+
26
+ class MultibandFilter(Filter):
27
+ pass
28
+
29
+
30
+ class BuiltinFilter(MultibandFilter):
31
+ def filter(self, image):
32
+ if image.mode == "P":
33
+ msg = "cannot filter palette images"
34
+ raise ValueError(msg)
35
+ return image.filter(*self.filterargs)
36
+
37
+
38
+ class Kernel(BuiltinFilter):
39
+ """
40
+ Create a convolution kernel. This only supports 3x3 and 5x5 integer and floating
41
+ point kernels.
42
+
43
+ Kernels can only be applied to "L" and "RGB" images.
44
+
45
+ :param size: Kernel size, given as (width, height). This must be (3,3) or (5,5).
46
+ :param kernel: A sequence containing kernel weights. The kernel will be flipped
47
+ vertically before being applied to the image.
48
+ :param scale: Scale factor. If given, the result for each pixel is divided by this
49
+ value. The default is the sum of the kernel weights.
50
+ :param offset: Offset. If given, this value is added to the result, after it has
51
+ been divided by the scale factor.
52
+ """
53
+
54
+ name = "Kernel"
55
+
56
+ def __init__(self, size, kernel, scale=None, offset=0):
57
+ if scale is None:
58
+ # default scale is sum of kernel
59
+ scale = functools.reduce(lambda a, b: a + b, kernel)
60
+ if size[0] * size[1] != len(kernel):
61
+ msg = "not enough coefficients in kernel"
62
+ raise ValueError(msg)
63
+ self.filterargs = size, scale, offset, kernel
64
+
65
+
66
+ class RankFilter(Filter):
67
+ """
68
+ Create a rank filter. The rank filter sorts all pixels in
69
+ a window of the given size, and returns the ``rank``'th value.
70
+
71
+ :param size: The kernel size, in pixels.
72
+ :param rank: What pixel value to pick. Use 0 for a min filter,
73
+ ``size * size / 2`` for a median filter, ``size * size - 1``
74
+ for a max filter, etc.
75
+ """
76
+
77
+ name = "Rank"
78
+
79
+ def __init__(self, size, rank):
80
+ self.size = size
81
+ self.rank = rank
82
+
83
+ def filter(self, image):
84
+ if image.mode == "P":
85
+ msg = "cannot filter palette images"
86
+ raise ValueError(msg)
87
+ image = image.expand(self.size // 2, self.size // 2)
88
+ return image.rankfilter(self.size, self.rank)
89
+
90
+
91
+ class MedianFilter(RankFilter):
92
+ """
93
+ Create a median filter. Picks the median pixel value in a window with the
94
+ given size.
95
+
96
+ :param size: The kernel size, in pixels.
97
+ """
98
+
99
+ name = "Median"
100
+
101
+ def __init__(self, size=3):
102
+ self.size = size
103
+ self.rank = size * size // 2
104
+
105
+
106
+ class MinFilter(RankFilter):
107
+ """
108
+ Create a min filter. Picks the lowest pixel value in a window with the
109
+ given size.
110
+
111
+ :param size: The kernel size, in pixels.
112
+ """
113
+
114
+ name = "Min"
115
+
116
+ def __init__(self, size=3):
117
+ self.size = size
118
+ self.rank = 0
119
+
120
+
121
+ class MaxFilter(RankFilter):
122
+ """
123
+ Create a max filter. Picks the largest pixel value in a window with the
124
+ given size.
125
+
126
+ :param size: The kernel size, in pixels.
127
+ """
128
+
129
+ name = "Max"
130
+
131
+ def __init__(self, size=3):
132
+ self.size = size
133
+ self.rank = size * size - 1
134
+
135
+
136
+ class ModeFilter(Filter):
137
+ """
138
+ Create a mode filter. Picks the most frequent pixel value in a box with the
139
+ given size. Pixel values that occur only once or twice are ignored; if no
140
+ pixel value occurs more than twice, the original pixel value is preserved.
141
+
142
+ :param size: The kernel size, in pixels.
143
+ """
144
+
145
+ name = "Mode"
146
+
147
+ def __init__(self, size=3):
148
+ self.size = size
149
+
150
+ def filter(self, image):
151
+ return image.modefilter(self.size)
152
+
153
+
154
+ class GaussianBlur(MultibandFilter):
155
+ """Blurs the image with a sequence of extended box filters, which
156
+ approximates a Gaussian kernel. For details on accuracy see
157
+ <https://www.mia.uni-saarland.de/Publications/gwosdek-ssvm11.pdf>
158
+
159
+ :param radius: Standard deviation of the Gaussian kernel. Either a sequence of two
160
+ numbers for x and y, or a single number for both.
161
+ """
162
+
163
+ name = "GaussianBlur"
164
+
165
+ def __init__(self, radius=2):
166
+ self.radius = radius
167
+
168
+ def filter(self, image):
169
+ xy = self.radius
170
+ if not isinstance(xy, (tuple, list)):
171
+ xy = (xy, xy)
172
+ if xy == (0, 0):
173
+ return image.copy()
174
+ return image.gaussian_blur(xy)
175
+
176
+
177
+ class BoxBlur(MultibandFilter):
178
+ """Blurs the image by setting each pixel to the average value of the pixels
179
+ in a square box extending radius pixels in each direction.
180
+ Supports float radius of arbitrary size. Uses an optimized implementation
181
+ which runs in linear time relative to the size of the image
182
+ for any radius value.
183
+
184
+ :param radius: Size of the box in a direction. Either a sequence of two numbers for
185
+ x and y, or a single number for both.
186
+
187
+ Radius 0 does not blur, returns an identical image.
188
+ Radius 1 takes 1 pixel in each direction, i.e. 9 pixels in total.
189
+ """
190
+
191
+ name = "BoxBlur"
192
+
193
+ def __init__(self, radius):
194
+ xy = radius
195
+ if not isinstance(xy, (tuple, list)):
196
+ xy = (xy, xy)
197
+ if xy[0] < 0 or xy[1] < 0:
198
+ msg = "radius must be >= 0"
199
+ raise ValueError(msg)
200
+ self.radius = radius
201
+
202
+ def filter(self, image):
203
+ xy = self.radius
204
+ if not isinstance(xy, (tuple, list)):
205
+ xy = (xy, xy)
206
+ if xy == (0, 0):
207
+ return image.copy()
208
+ return image.box_blur(xy)
209
+
210
+
211
+ class UnsharpMask(MultibandFilter):
212
+ """Unsharp mask filter.
213
+
214
+ See Wikipedia's entry on `digital unsharp masking`_ for an explanation of
215
+ the parameters.
216
+
217
+ :param radius: Blur Radius
218
+ :param percent: Unsharp strength, in percent
219
+ :param threshold: Threshold controls the minimum brightness change that
220
+ will be sharpened
221
+
222
+ .. _digital unsharp masking: https://en.wikipedia.org/wiki/Unsharp_masking#Digital_unsharp_masking
223
+
224
+ """
225
+
226
+ name = "UnsharpMask"
227
+
228
+ def __init__(self, radius=2, percent=150, threshold=3):
229
+ self.radius = radius
230
+ self.percent = percent
231
+ self.threshold = threshold
232
+
233
+ def filter(self, image):
234
+ return image.unsharp_mask(self.radius, self.percent, self.threshold)
235
+
236
+
237
+ class BLUR(BuiltinFilter):
238
+ name = "Blur"
239
+ # fmt: off
240
+ filterargs = (5, 5), 16, 0, (
241
+ 1, 1, 1, 1, 1,
242
+ 1, 0, 0, 0, 1,
243
+ 1, 0, 0, 0, 1,
244
+ 1, 0, 0, 0, 1,
245
+ 1, 1, 1, 1, 1,
246
+ )
247
+ # fmt: on
248
+
249
+
250
+ class CONTOUR(BuiltinFilter):
251
+ name = "Contour"
252
+ # fmt: off
253
+ filterargs = (3, 3), 1, 255, (
254
+ -1, -1, -1,
255
+ -1, 8, -1,
256
+ -1, -1, -1,
257
+ )
258
+ # fmt: on
259
+
260
+
261
+ class DETAIL(BuiltinFilter):
262
+ name = "Detail"
263
+ # fmt: off
264
+ filterargs = (3, 3), 6, 0, (
265
+ 0, -1, 0,
266
+ -1, 10, -1,
267
+ 0, -1, 0,
268
+ )
269
+ # fmt: on
270
+
271
+
272
+ class EDGE_ENHANCE(BuiltinFilter):
273
+ name = "Edge-enhance"
274
+ # fmt: off
275
+ filterargs = (3, 3), 2, 0, (
276
+ -1, -1, -1,
277
+ -1, 10, -1,
278
+ -1, -1, -1,
279
+ )
280
+ # fmt: on
281
+
282
+
283
+ class EDGE_ENHANCE_MORE(BuiltinFilter):
284
+ name = "Edge-enhance More"
285
+ # fmt: off
286
+ filterargs = (3, 3), 1, 0, (
287
+ -1, -1, -1,
288
+ -1, 9, -1,
289
+ -1, -1, -1,
290
+ )
291
+ # fmt: on
292
+
293
+
294
+ class EMBOSS(BuiltinFilter):
295
+ name = "Emboss"
296
+ # fmt: off
297
+ filterargs = (3, 3), 1, 128, (
298
+ -1, 0, 0,
299
+ 0, 1, 0,
300
+ 0, 0, 0,
301
+ )
302
+ # fmt: on
303
+
304
+
305
+ class FIND_EDGES(BuiltinFilter):
306
+ name = "Find Edges"
307
+ # fmt: off
308
+ filterargs = (3, 3), 1, 0, (
309
+ -1, -1, -1,
310
+ -1, 8, -1,
311
+ -1, -1, -1,
312
+ )
313
+ # fmt: on
314
+
315
+
316
+ class SHARPEN(BuiltinFilter):
317
+ name = "Sharpen"
318
+ # fmt: off
319
+ filterargs = (3, 3), 16, 0, (
320
+ -2, -2, -2,
321
+ -2, 32, -2,
322
+ -2, -2, -2,
323
+ )
324
+ # fmt: on
325
+
326
+
327
+ class SMOOTH(BuiltinFilter):
328
+ name = "Smooth"
329
+ # fmt: off
330
+ filterargs = (3, 3), 13, 0, (
331
+ 1, 1, 1,
332
+ 1, 5, 1,
333
+ 1, 1, 1,
334
+ )
335
+ # fmt: on
336
+
337
+
338
+ class SMOOTH_MORE(BuiltinFilter):
339
+ name = "Smooth More"
340
+ # fmt: off
341
+ filterargs = (5, 5), 100, 0, (
342
+ 1, 1, 1, 1, 1,
343
+ 1, 5, 5, 5, 1,
344
+ 1, 5, 44, 5, 1,
345
+ 1, 5, 5, 5, 1,
346
+ 1, 1, 1, 1, 1,
347
+ )
348
+ # fmt: on
349
+
350
+
351
+ class Color3DLUT(MultibandFilter):
352
+ """Three-dimensional color lookup table.
353
+
354
+ Transforms 3-channel pixels using the values of the channels as coordinates
355
+ in the 3D lookup table and interpolating the nearest elements.
356
+
357
+ This method allows you to apply almost any color transformation
358
+ in constant time by using pre-calculated decimated tables.
359
+
360
+ .. versionadded:: 5.2.0
361
+
362
+ :param size: Size of the table. One int or tuple of (int, int, int).
363
+ Minimal size in any dimension is 2, maximum is 65.
364
+ :param table: Flat lookup table. A list of ``channels * size**3``
365
+ float elements or a list of ``size**3`` channels-sized
366
+ tuples with floats. Channels are changed first,
367
+ then first dimension, then second, then third.
368
+ Value 0.0 corresponds lowest value of output, 1.0 highest.
369
+ :param channels: Number of channels in the table. Could be 3 or 4.
370
+ Default is 3.
371
+ :param target_mode: A mode for the result image. Should have not less
372
+ than ``channels`` channels. Default is ``None``,
373
+ which means that mode wouldn't be changed.
374
+ """
375
+
376
+ name = "Color 3D LUT"
377
+
378
+ def __init__(self, size, table, channels=3, target_mode=None, **kwargs):
379
+ if channels not in (3, 4):
380
+ msg = "Only 3 or 4 output channels are supported"
381
+ raise ValueError(msg)
382
+ self.size = size = self._check_size(size)
383
+ self.channels = channels
384
+ self.mode = target_mode
385
+
386
+ # Hidden flag `_copy_table=False` could be used to avoid extra copying
387
+ # of the table if the table is specially made for the constructor.
388
+ copy_table = kwargs.get("_copy_table", True)
389
+ items = size[0] * size[1] * size[2]
390
+ wrong_size = False
391
+
392
+ numpy = None
393
+ if hasattr(table, "shape"):
394
+ try:
395
+ import numpy
396
+ except ImportError:
397
+ pass
398
+
399
+ if numpy and isinstance(table, numpy.ndarray):
400
+ if copy_table:
401
+ table = table.copy()
402
+
403
+ if table.shape in [
404
+ (items * channels,),
405
+ (items, channels),
406
+ (size[2], size[1], size[0], channels),
407
+ ]:
408
+ table = table.reshape(items * channels)
409
+ else:
410
+ wrong_size = True
411
+
412
+ else:
413
+ if copy_table:
414
+ table = list(table)
415
+
416
+ # Convert to a flat list
417
+ if table and isinstance(table[0], (list, tuple)):
418
+ table, raw_table = [], table
419
+ for pixel in raw_table:
420
+ if len(pixel) != channels:
421
+ msg = (
422
+ "The elements of the table should "
423
+ f"have a length of {channels}."
424
+ )
425
+ raise ValueError(msg)
426
+ table.extend(pixel)
427
+
428
+ if wrong_size or len(table) != items * channels:
429
+ msg = (
430
+ "The table should have either channels * size**3 float items "
431
+ "or size**3 items of channels-sized tuples with floats. "
432
+ f"Table should be: {channels}x{size[0]}x{size[1]}x{size[2]}. "
433
+ f"Actual length: {len(table)}"
434
+ )
435
+ raise ValueError(msg)
436
+ self.table = table
437
+
438
+ @staticmethod
439
+ def _check_size(size):
440
+ try:
441
+ _, _, _ = size
442
+ except ValueError as e:
443
+ msg = "Size should be either an integer or a tuple of three integers."
444
+ raise ValueError(msg) from e
445
+ except TypeError:
446
+ size = (size, size, size)
447
+ size = [int(x) for x in size]
448
+ for size_1d in size:
449
+ if not 2 <= size_1d <= 65:
450
+ msg = "Size should be in [2, 65] range."
451
+ raise ValueError(msg)
452
+ return size
453
+
454
+ @classmethod
455
+ def generate(cls, size, callback, channels=3, target_mode=None):
456
+ """Generates new LUT using provided callback.
457
+
458
+ :param size: Size of the table. Passed to the constructor.
459
+ :param callback: Function with three parameters which correspond
460
+ three color channels. Will be called ``size**3``
461
+ times with values from 0.0 to 1.0 and should return
462
+ a tuple with ``channels`` elements.
463
+ :param channels: The number of channels which should return callback.
464
+ :param target_mode: Passed to the constructor of the resulting
465
+ lookup table.
466
+ """
467
+ size_1d, size_2d, size_3d = cls._check_size(size)
468
+ if channels not in (3, 4):
469
+ msg = "Only 3 or 4 output channels are supported"
470
+ raise ValueError(msg)
471
+
472
+ table = [0] * (size_1d * size_2d * size_3d * channels)
473
+ idx_out = 0
474
+ for b in range(size_3d):
475
+ for g in range(size_2d):
476
+ for r in range(size_1d):
477
+ table[idx_out : idx_out + channels] = callback(
478
+ r / (size_1d - 1), g / (size_2d - 1), b / (size_3d - 1)
479
+ )
480
+ idx_out += channels
481
+
482
+ return cls(
483
+ (size_1d, size_2d, size_3d),
484
+ table,
485
+ channels=channels,
486
+ target_mode=target_mode,
487
+ _copy_table=False,
488
+ )
489
+
490
+ def transform(self, callback, with_normals=False, channels=None, target_mode=None):
491
+ """Transforms the table values using provided callback and returns
492
+ a new LUT with altered values.
493
+
494
+ :param callback: A function which takes old lookup table values
495
+ and returns a new set of values. The number
496
+ of arguments which function should take is
497
+ ``self.channels`` or ``3 + self.channels``
498
+ if ``with_normals`` flag is set.
499
+ Should return a tuple of ``self.channels`` or
500
+ ``channels`` elements if it is set.
501
+ :param with_normals: If true, ``callback`` will be called with
502
+ coordinates in the color cube as the first
503
+ three arguments. Otherwise, ``callback``
504
+ will be called only with actual color values.
505
+ :param channels: The number of channels in the resulting lookup table.
506
+ :param target_mode: Passed to the constructor of the resulting
507
+ lookup table.
508
+ """
509
+ if channels not in (None, 3, 4):
510
+ msg = "Only 3 or 4 output channels are supported"
511
+ raise ValueError(msg)
512
+ ch_in = self.channels
513
+ ch_out = channels or ch_in
514
+ size_1d, size_2d, size_3d = self.size
515
+
516
+ table = [0] * (size_1d * size_2d * size_3d * ch_out)
517
+ idx_in = 0
518
+ idx_out = 0
519
+ for b in range(size_3d):
520
+ for g in range(size_2d):
521
+ for r in range(size_1d):
522
+ values = self.table[idx_in : idx_in + ch_in]
523
+ if with_normals:
524
+ values = callback(
525
+ r / (size_1d - 1),
526
+ g / (size_2d - 1),
527
+ b / (size_3d - 1),
528
+ *values,
529
+ )
530
+ else:
531
+ values = callback(*values)
532
+ table[idx_out : idx_out + ch_out] = values
533
+ idx_in += ch_in
534
+ idx_out += ch_out
535
+
536
+ return type(self)(
537
+ self.size,
538
+ table,
539
+ channels=ch_out,
540
+ target_mode=target_mode or self.mode,
541
+ _copy_table=False,
542
+ )
543
+
544
+ def __repr__(self):
545
+ r = [
546
+ f"{self.__class__.__name__} from {self.table.__class__.__name__}",
547
+ "size={:d}x{:d}x{:d}".format(*self.size),
548
+ f"channels={self.channels:d}",
549
+ ]
550
+ if self.mode:
551
+ r.append(f"target_mode={self.mode}")
552
+ return "<{}>".format(" ".join(r))
553
+
554
+ def filter(self, image):
555
+ from . import Image
556
+
557
+ return image.color_lut_3d(
558
+ self.mode or image.mode,
559
+ Image.Resampling.BILINEAR,
560
+ self.channels,
561
+ self.size[0],
562
+ self.size[1],
563
+ self.size[2],
564
+ self.table,
565
+ )
.venv/Lib/site-packages/PIL/ImageFont.py ADDED
@@ -0,0 +1,1252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # PIL raster font management
6
+ #
7
+ # History:
8
+ # 1996-08-07 fl created (experimental)
9
+ # 1997-08-25 fl minor adjustments to handle fonts from pilfont 0.3
10
+ # 1999-02-06 fl rewrote most font management stuff in C
11
+ # 1999-03-17 fl take pth files into account in load_path (from Richard Jones)
12
+ # 2001-02-17 fl added freetype support
13
+ # 2001-05-09 fl added TransposedFont wrapper class
14
+ # 2002-03-04 fl make sure we have a "L" or "1" font
15
+ # 2002-12-04 fl skip non-directory entries in the system path
16
+ # 2003-04-29 fl add embedded default font
17
+ # 2003-09-27 fl added support for truetype charmap encodings
18
+ #
19
+ # Todo:
20
+ # Adapt to PILFONT2 format (16-bit fonts, compressed, single file)
21
+ #
22
+ # Copyright (c) 1997-2003 by Secret Labs AB
23
+ # Copyright (c) 1996-2003 by Fredrik Lundh
24
+ #
25
+ # See the README file for information on usage and redistribution.
26
+ #
27
+
28
+ from __future__ import annotations
29
+
30
+ import base64
31
+ import os
32
+ import sys
33
+ import warnings
34
+ from enum import IntEnum
35
+ from io import BytesIO
36
+ from typing import BinaryIO
37
+
38
+ from . import Image
39
+ from ._typing import StrOrBytesPath
40
+ from ._util import is_directory, is_path
41
+
42
+
43
+ class Layout(IntEnum):
44
+ BASIC = 0
45
+ RAQM = 1
46
+
47
+
48
+ MAX_STRING_LENGTH = 1_000_000
49
+
50
+
51
+ try:
52
+ from . import _imagingft as core
53
+ except ImportError as ex:
54
+ from ._util import DeferredError
55
+
56
+ core = DeferredError.new(ex)
57
+
58
+
59
+ def _string_length_check(text):
60
+ if MAX_STRING_LENGTH is not None and len(text) > MAX_STRING_LENGTH:
61
+ msg = "too many characters in string"
62
+ raise ValueError(msg)
63
+
64
+
65
+ # FIXME: add support for pilfont2 format (see FontFile.py)
66
+
67
+ # --------------------------------------------------------------------
68
+ # Font metrics format:
69
+ # "PILfont" LF
70
+ # fontdescriptor LF
71
+ # (optional) key=value... LF
72
+ # "DATA" LF
73
+ # binary data: 256*10*2 bytes (dx, dy, dstbox, srcbox)
74
+ #
75
+ # To place a character, cut out srcbox and paste at dstbox,
76
+ # relative to the character position. Then move the character
77
+ # position according to dx, dy.
78
+ # --------------------------------------------------------------------
79
+
80
+
81
+ class ImageFont:
82
+ """PIL font wrapper"""
83
+
84
+ def _load_pilfont(self, filename):
85
+ with open(filename, "rb") as fp:
86
+ image = None
87
+ for ext in (".png", ".gif", ".pbm"):
88
+ if image:
89
+ image.close()
90
+ try:
91
+ fullname = os.path.splitext(filename)[0] + ext
92
+ image = Image.open(fullname)
93
+ except Exception:
94
+ pass
95
+ else:
96
+ if image and image.mode in ("1", "L"):
97
+ break
98
+ else:
99
+ if image:
100
+ image.close()
101
+ msg = "cannot find glyph data file"
102
+ raise OSError(msg)
103
+
104
+ self.file = fullname
105
+
106
+ self._load_pilfont_data(fp, image)
107
+ image.close()
108
+
109
+ def _load_pilfont_data(self, file, image):
110
+ # read PILfont header
111
+ if file.readline() != b"PILfont\n":
112
+ msg = "Not a PILfont file"
113
+ raise SyntaxError(msg)
114
+ file.readline().split(b";")
115
+ self.info = [] # FIXME: should be a dictionary
116
+ while True:
117
+ s = file.readline()
118
+ if not s or s == b"DATA\n":
119
+ break
120
+ self.info.append(s)
121
+
122
+ # read PILfont metrics
123
+ data = file.read(256 * 20)
124
+
125
+ # check image
126
+ if image.mode not in ("1", "L"):
127
+ msg = "invalid font image mode"
128
+ raise TypeError(msg)
129
+
130
+ image.load()
131
+
132
+ self.font = Image.core.font(image.im, data)
133
+
134
+ def getmask(self, text, mode="", *args, **kwargs):
135
+ """
136
+ Create a bitmap for the text.
137
+
138
+ If the font uses antialiasing, the bitmap should have mode ``L`` and use a
139
+ maximum value of 255. Otherwise, it should have mode ``1``.
140
+
141
+ :param text: Text to render.
142
+ :param mode: Used by some graphics drivers to indicate what mode the
143
+ driver prefers; if empty, the renderer may return either
144
+ mode. Note that the mode is always a string, to simplify
145
+ C-level implementations.
146
+
147
+ .. versionadded:: 1.1.5
148
+
149
+ :return: An internal PIL storage memory instance as defined by the
150
+ :py:mod:`PIL.Image.core` interface module.
151
+ """
152
+ _string_length_check(text)
153
+ Image._decompression_bomb_check(self.font.getsize(text))
154
+ return self.font.getmask(text, mode)
155
+
156
+ def getbbox(self, text, *args, **kwargs):
157
+ """
158
+ Returns bounding box (in pixels) of given text.
159
+
160
+ .. versionadded:: 9.2.0
161
+
162
+ :param text: Text to render.
163
+ :param mode: Used by some graphics drivers to indicate what mode the
164
+ driver prefers; if empty, the renderer may return either
165
+ mode. Note that the mode is always a string, to simplify
166
+ C-level implementations.
167
+
168
+ :return: ``(left, top, right, bottom)`` bounding box
169
+ """
170
+ _string_length_check(text)
171
+ width, height = self.font.getsize(text)
172
+ return 0, 0, width, height
173
+
174
+ def getlength(self, text, *args, **kwargs):
175
+ """
176
+ Returns length (in pixels) of given text.
177
+ This is the amount by which following text should be offset.
178
+
179
+ .. versionadded:: 9.2.0
180
+ """
181
+ _string_length_check(text)
182
+ width, height = self.font.getsize(text)
183
+ return width
184
+
185
+
186
+ ##
187
+ # Wrapper for FreeType fonts. Application code should use the
188
+ # <b>truetype</b> factory function to create font objects.
189
+
190
+
191
+ class FreeTypeFont:
192
+ """FreeType font wrapper (requires _imagingft service)"""
193
+
194
+ def __init__(
195
+ self,
196
+ font: StrOrBytesPath | BinaryIO | None = None,
197
+ size: float = 10,
198
+ index: int = 0,
199
+ encoding: str = "",
200
+ layout_engine: Layout | None = None,
201
+ ) -> None:
202
+ # FIXME: use service provider instead
203
+
204
+ if size <= 0:
205
+ msg = "font size must be greater than 0"
206
+ raise ValueError(msg)
207
+
208
+ self.path = font
209
+ self.size = size
210
+ self.index = index
211
+ self.encoding = encoding
212
+
213
+ if layout_engine not in (Layout.BASIC, Layout.RAQM):
214
+ layout_engine = Layout.BASIC
215
+ if core.HAVE_RAQM:
216
+ layout_engine = Layout.RAQM
217
+ elif layout_engine == Layout.RAQM and not core.HAVE_RAQM:
218
+ warnings.warn(
219
+ "Raqm layout was requested, but Raqm is not available. "
220
+ "Falling back to basic layout."
221
+ )
222
+ layout_engine = Layout.BASIC
223
+
224
+ self.layout_engine = layout_engine
225
+
226
+ def load_from_bytes(f):
227
+ self.font_bytes = f.read()
228
+ self.font = core.getfont(
229
+ "", size, index, encoding, self.font_bytes, layout_engine
230
+ )
231
+
232
+ if is_path(font):
233
+ font = os.path.realpath(os.fspath(font))
234
+ if sys.platform == "win32":
235
+ font_bytes_path = font if isinstance(font, bytes) else font.encode()
236
+ try:
237
+ font_bytes_path.decode("ascii")
238
+ except UnicodeDecodeError:
239
+ # FreeType cannot load fonts with non-ASCII characters on Windows
240
+ # So load it into memory first
241
+ with open(font, "rb") as f:
242
+ load_from_bytes(f)
243
+ return
244
+ self.font = core.getfont(
245
+ font, size, index, encoding, layout_engine=layout_engine
246
+ )
247
+ else:
248
+ load_from_bytes(font)
249
+
250
+ def __getstate__(self):
251
+ return [self.path, self.size, self.index, self.encoding, self.layout_engine]
252
+
253
+ def __setstate__(self, state):
254
+ path, size, index, encoding, layout_engine = state
255
+ self.__init__(path, size, index, encoding, layout_engine)
256
+
257
+ def getname(self):
258
+ """
259
+ :return: A tuple of the font family (e.g. Helvetica) and the font style
260
+ (e.g. Bold)
261
+ """
262
+ return self.font.family, self.font.style
263
+
264
+ def getmetrics(self):
265
+ """
266
+ :return: A tuple of the font ascent (the distance from the baseline to
267
+ the highest outline point) and descent (the distance from the
268
+ baseline to the lowest outline point, a negative value)
269
+ """
270
+ return self.font.ascent, self.font.descent
271
+
272
+ def getlength(self, text, mode="", direction=None, features=None, language=None):
273
+ """
274
+ Returns length (in pixels with 1/64 precision) of given text when rendered
275
+ in font with provided direction, features, and language.
276
+
277
+ This is the amount by which following text should be offset.
278
+ Text bounding box may extend past the length in some fonts,
279
+ e.g. when using italics or accents.
280
+
281
+ The result is returned as a float; it is a whole number if using basic layout.
282
+
283
+ Note that the sum of two lengths may not equal the length of a concatenated
284
+ string due to kerning. If you need to adjust for kerning, include the following
285
+ character and subtract its length.
286
+
287
+ For example, instead of ::
288
+
289
+ hello = font.getlength("Hello")
290
+ world = font.getlength("World")
291
+ hello_world = hello + world # not adjusted for kerning
292
+ assert hello_world == font.getlength("HelloWorld") # may fail
293
+
294
+ use ::
295
+
296
+ hello = font.getlength("HelloW") - font.getlength("W") # adjusted for kerning
297
+ world = font.getlength("World")
298
+ hello_world = hello + world # adjusted for kerning
299
+ assert hello_world == font.getlength("HelloWorld") # True
300
+
301
+ or disable kerning with (requires libraqm) ::
302
+
303
+ hello = draw.textlength("Hello", font, features=["-kern"])
304
+ world = draw.textlength("World", font, features=["-kern"])
305
+ hello_world = hello + world # kerning is disabled, no need to adjust
306
+ assert hello_world == draw.textlength("HelloWorld", font, features=["-kern"])
307
+
308
+ .. versionadded:: 8.0.0
309
+
310
+ :param text: Text to measure.
311
+ :param mode: Used by some graphics drivers to indicate what mode the
312
+ driver prefers; if empty, the renderer may return either
313
+ mode. Note that the mode is always a string, to simplify
314
+ C-level implementations.
315
+
316
+ :param direction: Direction of the text. It can be 'rtl' (right to
317
+ left), 'ltr' (left to right) or 'ttb' (top to bottom).
318
+ Requires libraqm.
319
+
320
+ :param features: A list of OpenType font features to be used during text
321
+ layout. This is usually used to turn on optional
322
+ font features that are not enabled by default,
323
+ for example 'dlig' or 'ss01', but can be also
324
+ used to turn off default font features for
325
+ example '-liga' to disable ligatures or '-kern'
326
+ to disable kerning. To get all supported
327
+ features, see
328
+ https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist
329
+ Requires libraqm.
330
+
331
+ :param language: Language of the text. Different languages may use
332
+ different glyph shapes or ligatures. This parameter tells
333
+ the font which language the text is in, and to apply the
334
+ correct substitutions as appropriate, if available.
335
+ It should be a `BCP 47 language code
336
+ <https://www.w3.org/International/articles/language-tags/>`_
337
+ Requires libraqm.
338
+
339
+ :return: Either width for horizontal text, or height for vertical text.
340
+ """
341
+ _string_length_check(text)
342
+ return self.font.getlength(text, mode, direction, features, language) / 64
343
+
344
+ def getbbox(
345
+ self,
346
+ text,
347
+ mode="",
348
+ direction=None,
349
+ features=None,
350
+ language=None,
351
+ stroke_width=0,
352
+ anchor=None,
353
+ ):
354
+ """
355
+ Returns bounding box (in pixels) of given text relative to given anchor
356
+ when rendered in font with provided direction, features, and language.
357
+
358
+ Use :py:meth:`getlength()` to get the offset of following text with
359
+ 1/64 pixel precision. The bounding box includes extra margins for
360
+ some fonts, e.g. italics or accents.
361
+
362
+ .. versionadded:: 8.0.0
363
+
364
+ :param text: Text to render.
365
+ :param mode: Used by some graphics drivers to indicate what mode the
366
+ driver prefers; if empty, the renderer may return either
367
+ mode. Note that the mode is always a string, to simplify
368
+ C-level implementations.
369
+
370
+ :param direction: Direction of the text. It can be 'rtl' (right to
371
+ left), 'ltr' (left to right) or 'ttb' (top to bottom).
372
+ Requires libraqm.
373
+
374
+ :param features: A list of OpenType font features to be used during text
375
+ layout. This is usually used to turn on optional
376
+ font features that are not enabled by default,
377
+ for example 'dlig' or 'ss01', but can be also
378
+ used to turn off default font features for
379
+ example '-liga' to disable ligatures or '-kern'
380
+ to disable kerning. To get all supported
381
+ features, see
382
+ https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist
383
+ Requires libraqm.
384
+
385
+ :param language: Language of the text. Different languages may use
386
+ different glyph shapes or ligatures. This parameter tells
387
+ the font which language the text is in, and to apply the
388
+ correct substitutions as appropriate, if available.
389
+ It should be a `BCP 47 language code
390
+ <https://www.w3.org/International/articles/language-tags/>`_
391
+ Requires libraqm.
392
+
393
+ :param stroke_width: The width of the text stroke.
394
+
395
+ :param anchor: The text anchor alignment. Determines the relative location of
396
+ the anchor to the text. The default alignment is top left,
397
+ specifically ``la`` for horizontal text and ``lt`` for
398
+ vertical text. See :ref:`text-anchors` for details.
399
+
400
+ :return: ``(left, top, right, bottom)`` bounding box
401
+ """
402
+ _string_length_check(text)
403
+ size, offset = self.font.getsize(
404
+ text, mode, direction, features, language, anchor
405
+ )
406
+ left, top = offset[0] - stroke_width, offset[1] - stroke_width
407
+ width, height = size[0] + 2 * stroke_width, size[1] + 2 * stroke_width
408
+ return left, top, left + width, top + height
409
+
410
+ def getmask(
411
+ self,
412
+ text,
413
+ mode="",
414
+ direction=None,
415
+ features=None,
416
+ language=None,
417
+ stroke_width=0,
418
+ anchor=None,
419
+ ink=0,
420
+ start=None,
421
+ ):
422
+ """
423
+ Create a bitmap for the text.
424
+
425
+ If the font uses antialiasing, the bitmap should have mode ``L`` and use a
426
+ maximum value of 255. If the font has embedded color data, the bitmap
427
+ should have mode ``RGBA``. Otherwise, it should have mode ``1``.
428
+
429
+ :param text: Text to render.
430
+ :param mode: Used by some graphics drivers to indicate what mode the
431
+ driver prefers; if empty, the renderer may return either
432
+ mode. Note that the mode is always a string, to simplify
433
+ C-level implementations.
434
+
435
+ .. versionadded:: 1.1.5
436
+
437
+ :param direction: Direction of the text. It can be 'rtl' (right to
438
+ left), 'ltr' (left to right) or 'ttb' (top to bottom).
439
+ Requires libraqm.
440
+
441
+ .. versionadded:: 4.2.0
442
+
443
+ :param features: A list of OpenType font features to be used during text
444
+ layout. This is usually used to turn on optional
445
+ font features that are not enabled by default,
446
+ for example 'dlig' or 'ss01', but can be also
447
+ used to turn off default font features for
448
+ example '-liga' to disable ligatures or '-kern'
449
+ to disable kerning. To get all supported
450
+ features, see
451
+ https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist
452
+ Requires libraqm.
453
+
454
+ .. versionadded:: 4.2.0
455
+
456
+ :param language: Language of the text. Different languages may use
457
+ different glyph shapes or ligatures. This parameter tells
458
+ the font which language the text is in, and to apply the
459
+ correct substitutions as appropriate, if available.
460
+ It should be a `BCP 47 language code
461
+ <https://www.w3.org/International/articles/language-tags/>`_
462
+ Requires libraqm.
463
+
464
+ .. versionadded:: 6.0.0
465
+
466
+ :param stroke_width: The width of the text stroke.
467
+
468
+ .. versionadded:: 6.2.0
469
+
470
+ :param anchor: The text anchor alignment. Determines the relative location of
471
+ the anchor to the text. The default alignment is top left,
472
+ specifically ``la`` for horizontal text and ``lt`` for
473
+ vertical text. See :ref:`text-anchors` for details.
474
+
475
+ .. versionadded:: 8.0.0
476
+
477
+ :param ink: Foreground ink for rendering in RGBA mode.
478
+
479
+ .. versionadded:: 8.0.0
480
+
481
+ :param start: Tuple of horizontal and vertical offset, as text may render
482
+ differently when starting at fractional coordinates.
483
+
484
+ .. versionadded:: 9.4.0
485
+
486
+ :return: An internal PIL storage memory instance as defined by the
487
+ :py:mod:`PIL.Image.core` interface module.
488
+ """
489
+ return self.getmask2(
490
+ text,
491
+ mode,
492
+ direction=direction,
493
+ features=features,
494
+ language=language,
495
+ stroke_width=stroke_width,
496
+ anchor=anchor,
497
+ ink=ink,
498
+ start=start,
499
+ )[0]
500
+
501
+ def getmask2(
502
+ self,
503
+ text,
504
+ mode="",
505
+ direction=None,
506
+ features=None,
507
+ language=None,
508
+ stroke_width=0,
509
+ anchor=None,
510
+ ink=0,
511
+ start=None,
512
+ *args,
513
+ **kwargs,
514
+ ):
515
+ """
516
+ Create a bitmap for the text.
517
+
518
+ If the font uses antialiasing, the bitmap should have mode ``L`` and use a
519
+ maximum value of 255. If the font has embedded color data, the bitmap
520
+ should have mode ``RGBA``. Otherwise, it should have mode ``1``.
521
+
522
+ :param text: Text to render.
523
+ :param mode: Used by some graphics drivers to indicate what mode the
524
+ driver prefers; if empty, the renderer may return either
525
+ mode. Note that the mode is always a string, to simplify
526
+ C-level implementations.
527
+
528
+ .. versionadded:: 1.1.5
529
+
530
+ :param direction: Direction of the text. It can be 'rtl' (right to
531
+ left), 'ltr' (left to right) or 'ttb' (top to bottom).
532
+ Requires libraqm.
533
+
534
+ .. versionadded:: 4.2.0
535
+
536
+ :param features: A list of OpenType font features to be used during text
537
+ layout. This is usually used to turn on optional
538
+ font features that are not enabled by default,
539
+ for example 'dlig' or 'ss01', but can be also
540
+ used to turn off default font features for
541
+ example '-liga' to disable ligatures or '-kern'
542
+ to disable kerning. To get all supported
543
+ features, see
544
+ https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist
545
+ Requires libraqm.
546
+
547
+ .. versionadded:: 4.2.0
548
+
549
+ :param language: Language of the text. Different languages may use
550
+ different glyph shapes or ligatures. This parameter tells
551
+ the font which language the text is in, and to apply the
552
+ correct substitutions as appropriate, if available.
553
+ It should be a `BCP 47 language code
554
+ <https://www.w3.org/International/articles/language-tags/>`_
555
+ Requires libraqm.
556
+
557
+ .. versionadded:: 6.0.0
558
+
559
+ :param stroke_width: The width of the text stroke.
560
+
561
+ .. versionadded:: 6.2.0
562
+
563
+ :param anchor: The text anchor alignment. Determines the relative location of
564
+ the anchor to the text. The default alignment is top left,
565
+ specifically ``la`` for horizontal text and ``lt`` for
566
+ vertical text. See :ref:`text-anchors` for details.
567
+
568
+ .. versionadded:: 8.0.0
569
+
570
+ :param ink: Foreground ink for rendering in RGBA mode.
571
+
572
+ .. versionadded:: 8.0.0
573
+
574
+ :param start: Tuple of horizontal and vertical offset, as text may render
575
+ differently when starting at fractional coordinates.
576
+
577
+ .. versionadded:: 9.4.0
578
+
579
+ :return: A tuple of an internal PIL storage memory instance as defined by the
580
+ :py:mod:`PIL.Image.core` interface module, and the text offset, the
581
+ gap between the starting coordinate and the first marking
582
+ """
583
+ _string_length_check(text)
584
+ if start is None:
585
+ start = (0, 0)
586
+
587
+ def fill(width, height):
588
+ size = (width, height)
589
+ Image._decompression_bomb_check(size)
590
+ return Image.core.fill("RGBA" if mode == "RGBA" else "L", size)
591
+
592
+ return self.font.render(
593
+ text,
594
+ fill,
595
+ mode,
596
+ direction,
597
+ features,
598
+ language,
599
+ stroke_width,
600
+ anchor,
601
+ ink,
602
+ start[0],
603
+ start[1],
604
+ )
605
+
606
+ def font_variant(
607
+ self, font=None, size=None, index=None, encoding=None, layout_engine=None
608
+ ):
609
+ """
610
+ Create a copy of this FreeTypeFont object,
611
+ using any specified arguments to override the settings.
612
+
613
+ Parameters are identical to the parameters used to initialize this
614
+ object.
615
+
616
+ :return: A FreeTypeFont object.
617
+ """
618
+ if font is None:
619
+ try:
620
+ font = BytesIO(self.font_bytes)
621
+ except AttributeError:
622
+ font = self.path
623
+ return FreeTypeFont(
624
+ font=font,
625
+ size=self.size if size is None else size,
626
+ index=self.index if index is None else index,
627
+ encoding=self.encoding if encoding is None else encoding,
628
+ layout_engine=layout_engine or self.layout_engine,
629
+ )
630
+
631
+ def get_variation_names(self):
632
+ """
633
+ :returns: A list of the named styles in a variation font.
634
+ :exception OSError: If the font is not a variation font.
635
+ """
636
+ try:
637
+ names = self.font.getvarnames()
638
+ except AttributeError as e:
639
+ msg = "FreeType 2.9.1 or greater is required"
640
+ raise NotImplementedError(msg) from e
641
+ return [name.replace(b"\x00", b"") for name in names]
642
+
643
+ def set_variation_by_name(self, name):
644
+ """
645
+ :param name: The name of the style.
646
+ :exception OSError: If the font is not a variation font.
647
+ """
648
+ names = self.get_variation_names()
649
+ if not isinstance(name, bytes):
650
+ name = name.encode()
651
+ index = names.index(name) + 1
652
+
653
+ if index == getattr(self, "_last_variation_index", None):
654
+ # When the same name is set twice in a row,
655
+ # there is an 'unknown freetype error'
656
+ # https://savannah.nongnu.org/bugs/?56186
657
+ return
658
+ self._last_variation_index = index
659
+
660
+ self.font.setvarname(index)
661
+
662
+ def get_variation_axes(self):
663
+ """
664
+ :returns: A list of the axes in a variation font.
665
+ :exception OSError: If the font is not a variation font.
666
+ """
667
+ try:
668
+ axes = self.font.getvaraxes()
669
+ except AttributeError as e:
670
+ msg = "FreeType 2.9.1 or greater is required"
671
+ raise NotImplementedError(msg) from e
672
+ for axis in axes:
673
+ axis["name"] = axis["name"].replace(b"\x00", b"")
674
+ return axes
675
+
676
+ def set_variation_by_axes(self, axes):
677
+ """
678
+ :param axes: A list of values for each axis.
679
+ :exception OSError: If the font is not a variation font.
680
+ """
681
+ try:
682
+ self.font.setvaraxes(axes)
683
+ except AttributeError as e:
684
+ msg = "FreeType 2.9.1 or greater is required"
685
+ raise NotImplementedError(msg) from e
686
+
687
+
688
+ class TransposedFont:
689
+ """Wrapper for writing rotated or mirrored text"""
690
+
691
+ def __init__(self, font, orientation=None):
692
+ """
693
+ Wrapper that creates a transposed font from any existing font
694
+ object.
695
+
696
+ :param font: A font object.
697
+ :param orientation: An optional orientation. If given, this should
698
+ be one of Image.Transpose.FLIP_LEFT_RIGHT, Image.Transpose.FLIP_TOP_BOTTOM,
699
+ Image.Transpose.ROTATE_90, Image.Transpose.ROTATE_180, or
700
+ Image.Transpose.ROTATE_270.
701
+ """
702
+ self.font = font
703
+ self.orientation = orientation # any 'transpose' argument, or None
704
+
705
+ def getmask(self, text, mode="", *args, **kwargs):
706
+ im = self.font.getmask(text, mode, *args, **kwargs)
707
+ if self.orientation is not None:
708
+ return im.transpose(self.orientation)
709
+ return im
710
+
711
+ def getbbox(self, text, *args, **kwargs):
712
+ # TransposedFont doesn't support getmask2, move top-left point to (0, 0)
713
+ # this has no effect on ImageFont and simulates anchor="lt" for FreeTypeFont
714
+ left, top, right, bottom = self.font.getbbox(text, *args, **kwargs)
715
+ width = right - left
716
+ height = bottom - top
717
+ if self.orientation in (Image.Transpose.ROTATE_90, Image.Transpose.ROTATE_270):
718
+ return 0, 0, height, width
719
+ return 0, 0, width, height
720
+
721
+ def getlength(self, text, *args, **kwargs):
722
+ if self.orientation in (Image.Transpose.ROTATE_90, Image.Transpose.ROTATE_270):
723
+ msg = "text length is undefined for text rotated by 90 or 270 degrees"
724
+ raise ValueError(msg)
725
+ return self.font.getlength(text, *args, **kwargs)
726
+
727
+
728
+ def load(filename):
729
+ """
730
+ Load a font file. This function loads a font object from the given
731
+ bitmap font file, and returns the corresponding font object.
732
+
733
+ :param filename: Name of font file.
734
+ :return: A font object.
735
+ :exception OSError: If the file could not be read.
736
+ """
737
+ f = ImageFont()
738
+ f._load_pilfont(filename)
739
+ return f
740
+
741
+
742
+ def truetype(font=None, size=10, index=0, encoding="", layout_engine=None):
743
+ """
744
+ Load a TrueType or OpenType font from a file or file-like object,
745
+ and create a font object.
746
+ This function loads a font object from the given file or file-like
747
+ object, and creates a font object for a font of the given size.
748
+
749
+ Pillow uses FreeType to open font files. On Windows, be aware that FreeType
750
+ will keep the file open as long as the FreeTypeFont object exists. Windows
751
+ limits the number of files that can be open in C at once to 512, so if many
752
+ fonts are opened simultaneously and that limit is approached, an
753
+ ``OSError`` may be thrown, reporting that FreeType "cannot open resource".
754
+ A workaround would be to copy the file(s) into memory, and open that instead.
755
+
756
+ This function requires the _imagingft service.
757
+
758
+ :param font: A filename or file-like object containing a TrueType font.
759
+ If the file is not found in this filename, the loader may also
760
+ search in other directories, such as the :file:`fonts/`
761
+ directory on Windows or :file:`/Library/Fonts/`,
762
+ :file:`/System/Library/Fonts/` and :file:`~/Library/Fonts/` on
763
+ macOS.
764
+
765
+ :param size: The requested size, in pixels.
766
+ :param index: Which font face to load (default is first available face).
767
+ :param encoding: Which font encoding to use (default is Unicode). Possible
768
+ encodings include (see the FreeType documentation for more
769
+ information):
770
+
771
+ * "unic" (Unicode)
772
+ * "symb" (Microsoft Symbol)
773
+ * "ADOB" (Adobe Standard)
774
+ * "ADBE" (Adobe Expert)
775
+ * "ADBC" (Adobe Custom)
776
+ * "armn" (Apple Roman)
777
+ * "sjis" (Shift JIS)
778
+ * "gb " (PRC)
779
+ * "big5"
780
+ * "wans" (Extended Wansung)
781
+ * "joha" (Johab)
782
+ * "lat1" (Latin-1)
783
+
784
+ This specifies the character set to use. It does not alter the
785
+ encoding of any text provided in subsequent operations.
786
+ :param layout_engine: Which layout engine to use, if available:
787
+ :attr:`.ImageFont.Layout.BASIC` or :attr:`.ImageFont.Layout.RAQM`.
788
+ If it is available, Raqm layout will be used by default.
789
+ Otherwise, basic layout will be used.
790
+
791
+ Raqm layout is recommended for all non-English text. If Raqm layout
792
+ is not required, basic layout will have better performance.
793
+
794
+ You can check support for Raqm layout using
795
+ :py:func:`PIL.features.check_feature` with ``feature="raqm"``.
796
+
797
+ .. versionadded:: 4.2.0
798
+ :return: A font object.
799
+ :exception OSError: If the file could not be read.
800
+ :exception ValueError: If the font size is not greater than zero.
801
+ """
802
+
803
+ def freetype(font):
804
+ return FreeTypeFont(font, size, index, encoding, layout_engine)
805
+
806
+ try:
807
+ return freetype(font)
808
+ except OSError:
809
+ if not is_path(font):
810
+ raise
811
+ ttf_filename = os.path.basename(font)
812
+
813
+ dirs = []
814
+ if sys.platform == "win32":
815
+ # check the windows font repository
816
+ # NOTE: must use uppercase WINDIR, to work around bugs in
817
+ # 1.5.2's os.environ.get()
818
+ windir = os.environ.get("WINDIR")
819
+ if windir:
820
+ dirs.append(os.path.join(windir, "fonts"))
821
+ elif sys.platform in ("linux", "linux2"):
822
+ lindirs = os.environ.get("XDG_DATA_DIRS")
823
+ if not lindirs:
824
+ # According to the freedesktop spec, XDG_DATA_DIRS should
825
+ # default to /usr/share
826
+ lindirs = "/usr/share"
827
+ dirs += [os.path.join(lindir, "fonts") for lindir in lindirs.split(":")]
828
+ elif sys.platform == "darwin":
829
+ dirs += [
830
+ "/Library/Fonts",
831
+ "/System/Library/Fonts",
832
+ os.path.expanduser("~/Library/Fonts"),
833
+ ]
834
+
835
+ ext = os.path.splitext(ttf_filename)[1]
836
+ first_font_with_a_different_extension = None
837
+ for directory in dirs:
838
+ for walkroot, walkdir, walkfilenames in os.walk(directory):
839
+ for walkfilename in walkfilenames:
840
+ if ext and walkfilename == ttf_filename:
841
+ return freetype(os.path.join(walkroot, walkfilename))
842
+ elif not ext and os.path.splitext(walkfilename)[0] == ttf_filename:
843
+ fontpath = os.path.join(walkroot, walkfilename)
844
+ if os.path.splitext(fontpath)[1] == ".ttf":
845
+ return freetype(fontpath)
846
+ if not ext and first_font_with_a_different_extension is None:
847
+ first_font_with_a_different_extension = fontpath
848
+ if first_font_with_a_different_extension:
849
+ return freetype(first_font_with_a_different_extension)
850
+ raise
851
+
852
+
853
+ def load_path(filename):
854
+ """
855
+ Load font file. Same as :py:func:`~PIL.ImageFont.load`, but searches for a
856
+ bitmap font along the Python path.
857
+
858
+ :param filename: Name of font file.
859
+ :return: A font object.
860
+ :exception OSError: If the file could not be read.
861
+ """
862
+ for directory in sys.path:
863
+ if is_directory(directory):
864
+ if not isinstance(filename, str):
865
+ filename = filename.decode("utf-8")
866
+ try:
867
+ return load(os.path.join(directory, filename))
868
+ except OSError:
869
+ pass
870
+ msg = "cannot find font file"
871
+ raise OSError(msg)
872
+
873
+
874
+ def load_default(size: float | None = None) -> FreeTypeFont | ImageFont:
875
+ """If FreeType support is available, load a version of Aileron Regular,
876
+ https://dotcolon.net/font/aileron, with a more limited character set.
877
+
878
+ Otherwise, load a "better than nothing" font.
879
+
880
+ .. versionadded:: 1.1.4
881
+
882
+ :param size: The font size of Aileron Regular.
883
+
884
+ .. versionadded:: 10.1.0
885
+
886
+ :return: A font object.
887
+ """
888
+ if core.__class__.__name__ == "module" or size is not None:
889
+ f = truetype(
890
+ BytesIO(
891
+ base64.b64decode(
892
+ b"""
893
+ AAEAAAAPAIAAAwBwRkZUTYwDlUAAADFoAAAAHEdERUYAqADnAAAo8AAAACRHUE9ThhmITwAAKfgAA
894
+ AduR1NVQnHxefoAACkUAAAA4k9TLzJovoHLAAABeAAAAGBjbWFw5lFQMQAAA6gAAAGqZ2FzcP//AA
895
+ MAACjoAAAACGdseWYmRXoPAAAGQAAAHfhoZWFkE18ayQAAAPwAAAA2aGhlYQboArEAAAE0AAAAJGh
896
+ tdHjjERZ8AAAB2AAAAdBsb2NhuOexrgAABVQAAADqbWF4cAC7AEYAAAFYAAAAIG5hbWUr+h5lAAAk
897
+ OAAAA6Jwb3N0D3oPTQAAJ9wAAAEKAAEAAAABGhxJDqIhXw889QALA+gAAAAA0Bqf2QAAAADhCh2h/
898
+ 2r/LgOxAyAAAAAIAAIAAAAAAAAAAQAAA8r/GgAAA7j/av9qA7EAAQAAAAAAAAAAAAAAAAAAAHQAAQ
899
+ AAAHQAQwAFAAAAAAACAAAAAQABAAAAQAAAAAAAAAADAfoBkAAFAAgCigJYAAAASwKKAlgAAAFeADI
900
+ BPgAAAAAFAAAAAAAAAAAAAAcAAAAAAAAAAAAAAABVS1dOAEAAIPsCAwL/GgDIA8oA5iAAAJMAAAAA
901
+ AhICsgAAACAAAwH0AAAAAAAAAU0AAADYAAAA8gA5AVMAVgJEAEYCRAA1AuQAKQKOAEAAsAArATsAZ
902
+ AE7AB4CMABVAkQAUADc/+EBEgAgANwAJQEv//sCRAApAkQAggJEADwCRAAtAkQAIQJEADkCRAArAk
903
+ QAMgJEACwCRAAxANwAJQDc/+ECRABnAkQAUAJEAEQB8wAjA1QANgJ/AB0CcwBkArsALwLFAGQCSwB
904
+ kAjcAZALGAC8C2gBkAQgAZAIgADcCYQBkAj8AZANiAGQCzgBkAuEALwJWAGQC3QAvAmsAZAJJADQC
905
+ ZAAiAqoAXgJuACADuAAaAnEAGQJFABMCTwAuATMAYgEv//sBJwAiAkQAUAH0ADIBLAApAhMAJAJjA
906
+ EoCEQAeAmcAHgIlAB4BIgAVAmcAHgJRAEoA7gA+AOn/8wIKAEoA9wBGA1cASgJRAEoCSgAeAmMASg
907
+ JnAB4BSgBKAcsAGAE5ABQCUABCAgIAAQMRAAEB4v/6AgEAAQHOABQBLwBAAPoAYAEvACECRABNA0Y
908
+ AJAItAHgBKgAcAkQAUAEsAHQAygAgAi0AOQD3ADYA9wAWAaEANgGhABYCbAAlAYMAeAGDADkA6/9q
909
+ AhsAFAIKABUB/QAVAAAAAwAAAAMAAAAcAAEAAAAAAKQAAwABAAAAHAAEAIgAAAAeABAAAwAOAH4Aq
910
+ QCrALEAtAC3ALsgGSAdICYgOiBEISL7Av//AAAAIACpAKsAsAC0ALcAuyAYIBwgJiA5IEQhIvsB//
911
+ //4/+5/7j/tP+y/7D/reBR4E/gR+A14CzfTwVxAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
912
+ AAAAAAAEGAAABAAAAAAAAAAECAAAAAgAAAAAAAAAAAAAAAAAAAAEAAAMEBQYHCAkKCwwNDg8QERIT
913
+ FBUWFxgZGhscHR4fICEiIyQlJicoKSorLC0uLzAxMjM0NTY3ODk6Ozw9Pj9AQUJDREVGR0hJSktMT
914
+ U5PUFFSU1RVVldYWVpbXF1eX2BhAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGQAAA
915
+ AAAAAAYnFmAAAAAABlAAAAAAAAAAAAAAAAAAAAAAAAAAAAY2htAAAAAAAAAABrbGlqAAAAAHAAbm9
916
+ ycwBnAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAmACYAJgAmAD4AUgCCAMoBCgFO
917
+ AVwBcgGIAaYBvAHKAdYB6AH2AgwCIAJKAogCpgLWAw4DIgNkA5wDugPUA+gD/AQQBEYEogS8BPoFJ
918
+ gVSBWoFgAWwBcoF1gX6BhQGJAZMBmgGiga0BuIHGgdUB2YHkAeiB8AH3AfyCAoIHAgqCDoITghcCG
919
+ oIogjSCPoJKglYCXwJwgnqCgIKKApACl4Klgq8CtwLDAs8C1YLjAuyC9oL7gwMDCYMSAxgDKAMrAz
920
+ qDQoNTA1mDYQNoA2uDcAN2g3oDfYODA4iDkoOXA5sDnoOnA7EDvwAAAAFAAAAAAH0ArwAAwAGAAkA
921
+ DAAPAAAxESERAxMhExcRASELARETAfT6qv6syKr+jgFUqsiqArz9RAGLAP/+1P8B/v3VAP8BLP4CA
922
+ P8AAgA5//IAuQKyAAMACwAANyMDMwIyFhQGIiY0oE4MZk84JCQ4JLQB/v3AJDgkJDgAAgBWAeUBPA
923
+ LfAAMABwAAEyMnMxcjJzOmRgpagkYKWgHl+vr6AAAAAAIARgAAAf4CsgAbAB8AAAEHMxUjByM3Iwc
924
+ jNyM1MzcjNTM3MwczNzMHMxUrAQczAZgdZXEvOi9bLzovWmYdZXEvOi9bLzovWp9bHlsBn4w429vb
925
+ 2ziMONvb29s4jAAAAAMANf+mAg4DDAAfACYALAAAJRQGBxUjNS4BJzMeARcRLgE0Njc1MxUeARcjJ
926
+ icVHgEBFBYXNQ4BExU+ATU0Ag5xWDpgcgRcBz41Xl9oVTpVYwpcC1ttXP6cLTQuM5szOrVRZwlOTQ
927
+ ZqVzZECAEAGlukZAlOTQdrUG8O7iNlAQgxNhDlCDj+8/YGOjReAAAAAAUAKf/yArsCvAAHAAsAFQA
928
+ dACcAABIyFhQGIiY0EyMBMwQiBhUUFjI2NTQSMhYUBiImNDYiBhUUFjI2NTR5iFBQiFCVVwHAV/5c
929
+ OiMjOiPmiFBQiFCxOiMjOiMCvFaSVlaS/ZoCsjIzMC80NC8w/uNWklZWkhozMC80NC8wAAAAAgBA/
930
+ /ICbgLAACIALgAAARUjEQYjIiY1NDY3LgE1NDYzMhcVJiMiBhUUFhcWOwE1MxUFFBYzMjc1IyIHDg
931
+ ECbmBcYYOOVkg7R4hsQjY4Q0RNRD4SLDxW/pJUXzksPCkUUk0BgUb+zBVUZ0BkDw5RO1huCkULQzp
932
+ COAMBcHDHRz0J/AIHRQAAAAEAKwHlAIUC3wADAAATIycze0YKWgHl+gAAAAABAGT/sAEXAwwACQAA
933
+ EzMGEBcjLgE0Nt06dXU6OUBAAwzG/jDGVePs4wAAAAEAHv+wANEDDAAJAAATMx4BFAYHIzYQHjo5Q
934
+ EA5OnUDDFXj7ONVxgHQAAAAAQBVAFIB2wHbAA4AAAE3FwcXBycHJzcnNxcnMwEtmxOfcTJjYzJxnx
935
+ ObCj4BKD07KYolmZkliik7PbMAAQBQAFUB9AIlAAsAAAEjFSM1IzUzNTMVMwH0tTq1tTq1AR/Kyjj
936
+ OzgAAAAAB/+H/iACMAGQABAAANwcjNzOMWlFOXVrS3AAAAQAgAP8A8gE3AAMAABMjNTPy0tIA/zgA
937
+ AQAl//IApQByAAcAADYyFhQGIiY0STgkJDgkciQ4JCQ4AAAAAf/7/+IBNALQAAMAABcjEzM5Pvs+H
938
+ gLuAAAAAAIAKf/yAhsCwAADAAcAABIgECA2IBAgKQHy/g5gATL+zgLA/TJEAkYAAAAAAQCCAAABlg
939
+ KyAAgAAAERIxEHNTc2MwGWVr6SIygCsv1OAldxW1sWAAEAPAAAAg4CwAAZAAA3IRUhNRM+ATU0JiM
940
+ iDwEjNz4BMzIWFRQGB7kBUv4x+kI2QTt+EAFWAQp8aGVtSl5GRjEA/0RVLzlLmAoKa3FsUkNxXQAA
941
+ AAEALf/yAhYCwAAqAAABHgEVFAYjIi8BMxceATMyNjU0KwE1MzI2NTQmIyIGDwEjNz4BMzIWFRQGA
942
+ YxBSZJo2RUBVgEHV0JBUaQREUBUQzc5TQcBVgEKfGhfcEMBbxJbQl1x0AoKRkZHPn9GSD80QUVCCg
943
+ pfbGBPOlgAAAACACEAAAIkArIACgAPAAAlIxUjNSE1ATMRMyMRBg8BAiRXVv6qAVZWV60dHLCurq4
944
+ rAdn+QgFLMibzAAABADn/8gIZArIAHQAAATIWFRQGIyIvATMXFjMyNjU0JiMiByMTIRUhBzc2ATNv
945
+ d5Fl1RQBVgIad0VSTkVhL1IwAYj+vh8rMAHHgGdtgcUKCoFXTU5bYgGRRvAuHQAAAAACACv/8gITA
946
+ sAAFwAjAAABMhYVFAYjIhE0NjMyFh8BIycmIyIDNzYTMjY1NCYjIgYVFBYBLmp7imr0l3RZdAgBXA
947
+ IYZ5wKJzU6QVNJSz5SUAHSgWltiQFGxcNlVQoKdv7sPiz+ZF1LTmJbU0lhAAAAAQAyAAACGgKyAAY
948
+ AAAEVASMBITUCGv6oXAFL/oECsij9dgJsRgAAAAMALP/xAhgCwAAWACAALAAAAR4BFRQGIyImNTQ2
949
+ Ny4BNTQ2MhYVFAYmIgYVFBYyNjU0AzI2NTQmIyIGFRQWAZQ5S5BmbIpPOjA7ecp5P2F8Q0J8RIVJS
950
+ 0pLTEtOAW0TXTxpZ2ZqPF0SE1A3VWVlVTdQ/UU0N0RENzT9/ko+Ok1NOj1LAAIAMf/yAhkCwAAXAC
951
+ MAAAEyERQGIyImLwEzFxYzMhMHBiMiJjU0NhMyNjU0JiMiBhUUFgEl9Jd0WXQIAVwCGGecCic1SWp
952
+ 7imo+UlBAQVNJAsD+usXDZVUKCnYBFD4sgWltif5kW1NJYV1LTmIAAAACACX/8gClAiAABwAPAAAS
953
+ MhYUBiImNBIyFhQGIiY0STgkJDgkJDgkJDgkAiAkOCQkOP52JDgkJDgAAAAC/+H/iAClAiAABwAMA
954
+ AASMhYUBiImNBMHIzczSTgkJDgkaFpSTl4CICQ4JCQ4/mba5gAAAQBnAB4B+AH0AAYAAAENARUlNS
955
+ UB+P6qAVb+bwGRAbCmpkbJRMkAAAIAUAC7AfQBuwADAAcAAAEhNSERITUhAfT+XAGk/lwBpAGDOP8
956
+ AOAABAEQAHgHVAfQABgAAARUFNS0BNQHV/m8BVv6qAStEyUSmpkYAAAAAAgAj//IB1ALAABgAIAAA
957
+ ATIWFRQHDgEHIz4BNz4BNTQmIyIGByM+ARIyFhQGIiY0AQRibmktIAJWBSEqNig+NTlHBFoDezQ4J
958
+ CQ4JALAZ1BjaS03JS1DMD5LLDQ/SUVgcv2yJDgkJDgAAAAAAgA2/5gDFgKYADYAQgAAAQMGFRQzMj
959
+ Y1NCYjIg4CFRQWMzI2NxcGIyImNTQ+AjMyFhUUBiMiJwcGIyImNTQ2MzIfATcHNzYmIyIGFRQzMjY
960
+ Cej8EJjJJlnBAfGQ+oHtAhjUYg5OPx0h2k06Os3xRWQsVLjY5VHtdPBwJETcJDyUoOkZEJz8B0f74
961
+ EQ8kZl6EkTFZjVOLlyknMVm1pmCiaTq4lX6CSCknTVRmmR8wPdYnQzxuSWVGAAIAHQAAAncCsgAHA
962
+ AoAACUjByMTMxMjATMDAcj+UVz4dO5d/sjPZPT0ArL9TgE6ATQAAAADAGQAAAJMArIAEAAbACcAAA
963
+ EeARUUBgcGKwERMzIXFhUUJRUzMjc2NTQnJiMTPgE1NCcmKwEVMzIBvkdHZkwiNt7LOSGq/oeFHBt
964
+ hahIlSTM+cB8Yj5UWAW8QT0VYYgwFArIEF5Fv1eMED2NfDAL93AU+N24PBP0AAAAAAQAv//ICjwLA
965
+ ABsAAAEyFh8BIycmIyIGFRQWMzI/ATMHDgEjIiY1NDYBdX+PCwFWAiKiaHx5ZaIiAlYBCpWBk6a0A
966
+ sCAagoKpqN/gaOmCgplhcicn8sAAAIAZAAAAp8CsgAMABkAAAEeARUUBgcGKwERMzITPgE1NCYnJi
967
+ sBETMyAY59lJp8IzXN0jUVWmdjWRs5d3I4Aq4QqJWUug8EArL9mQ+PeHGHDgX92gAAAAABAGQAAAI
968
+ vArIACwAAJRUhESEVIRUhFSEVAi/+NQHB/pUBTf6zRkYCskbwRvAAAAABAGQAAAIlArIACQAAExUh
969
+ FSERIxEhFboBQ/69VgHBAmzwRv7KArJGAAAAAAEAL//yAo8CwAAfAAABMxEjNQcGIyImNTQ2MzIWH
970
+ wEjJyYjIgYVFBYzMjY1IwGP90wfPnWTprSSf48LAVYCIqJofHllVG+hAU3+s3hARsicn8uAagoKpq
971
+ N/gaN1XAAAAAEAZAAAAowCsgALAAABESMRIREjETMRIRECjFb+hFZWAXwCsv1OAS7+0gKy/sQBPAA
972
+ AAAABAGQAAAC6ArIAAwAAMyMRM7pWVgKyAAABADf/8gHoArIAEwAAAREUBw4BIyImLwEzFxYzMjc2
973
+ NREB6AIFcGpgbQIBVgIHfXQKAQKy/lYxIltob2EpKYyEFD0BpwAAAAABAGQAAAJ0ArIACwAACQEjA
974
+ wcVIxEzEQEzATsBJ3ntQlZWAVVlAWH+nwEnR+ACsv6RAW8AAQBkAAACLwKyAAUAACUVIREzEQIv/j
975
+ VWRkYCsv2UAAABAGQAAAMUArIAFAAAAREjETQ3BgcDIwMmJxYVESMRMxsBAxRWAiMxemx8NxsCVo7
976
+ MywKy/U4BY7ZLco7+nAFmoFxLtP6dArL9lwJpAAAAAAEAZAAAAoACsgANAAAhIwEWFREjETMBJjUR
977
+ MwKAhP67A1aEAUUDVAJeeov+pwKy/aJ5jAFZAAAAAgAv//ICuwLAAAkAEwAAEiAWFRQGICY1NBIyN
978
+ jU0JiIGFRTbATSsrP7MrNrYenrYegLAxaKhxsahov47nIeIm5uIhwACAGQAAAJHArIADgAYAAABHg
979
+ EVFAYHBisBESMRMzITNjQnJisBETMyAZRUX2VOHzuAVtY7GlxcGDWIiDUCrgtnVlVpCgT+5gKy/rU
980
+ V1BUF/vgAAAACAC//zAK9AsAAEgAcAAAlFhcHJiMiBwYjIiY1NDYgFhUUJRQWMjY1NCYiBgI9PUMx
981
+ UDcfKh8omqysATSs/dR62Hp62HpICTg7NgkHxqGixcWitbWHnJyHiJubAAIAZAAAAlgCsgAXACMAA
982
+ CUWFyMmJyYnJisBESMRMzIXHgEVFAYHFiUzMjc+ATU0JyYrAQIqDCJfGQwNWhAhglbiOx9QXEY1Tv
983
+ 6bhDATMj1lGSyMtYgtOXR0BwH+1wKyBApbU0BSESRAAgVAOGoQBAABADT/8gIoAsAAJQAAATIWFyM
984
+ uASMiBhUUFhceARUUBiMiJiczHgEzMjY1NCYnLgE1NDYBOmd2ClwGS0E6SUNRdW+HZnKKC1wPWkQ9
985
+ Uk1cZGuEAsBwXUJHNjQ3OhIbZVZZbm5kREo+NT5DFRdYUFdrAAAAAAEAIgAAAmQCsgAHAAABIxEjE
986
+ SM1IQJk9lb2AkICbP2UAmxGAAEAXv/yAmQCsgAXAAABERQHDgEiJicmNREzERQXHgEyNjc2NRECZA
987
+ IIgfCBCAJWAgZYmlgGAgKy/k0qFFxzc1wUKgGz/lUrEkRQUEQSKwGrAAAAAAEAIAAAAnoCsgAGAAA
988
+ hIwMzGwEzAYJ07l3N1FwCsv2PAnEAAAEAGgAAA7ECsgAMAAABAyMLASMDMxsBMxsBA7HAcZyicrZi
989
+ kaB0nJkCsv1OAlP9rQKy/ZsCW/2kAmYAAAEAGQAAAm8CsgALAAAhCwEjEwMzGwEzAxMCCsrEY/bkY
990
+ re+Y/D6AST+3AFcAVb+5gEa/q3+oQAAAQATAAACUQKyAAgAAAERIxEDMxsBMwFdVvRjwLphARD+8A
991
+ EQAaL+sQFPAAABAC4AAAI5ArIACQAAJRUhNQEhNSEVAQI5/fUBof57Aen+YUZGQgIqRkX92QAAAAA
992
+ BAGL/sAEFAwwABwAAARUjETMVIxEBBWlpowMMOP0UOANcAAAB//v/4gE0AtAAAwAABSMDMwE0Pvs+
993
+ HgLuAAAAAQAi/7AAxQMMAAcAABcjNTMRIzUzxaNpaaNQOALsOAABAFAA1wH0AmgABgAAJQsBIxMzE
994
+ wGwjY1GsESw1wFZ/qcBkf5vAAAAAQAy/6oBwv/iAAMAAAUhNSEBwv5wAZBWOAAAAAEAKQJEALYCsg
995
+ ADAAATIycztjhVUAJEbgAAAAACACT/8gHQAiAAHQAlAAAhJwcGIyImNTQ2OwE1NCcmIyIHIz4BMzI
996
+ XFh0BFBcnMjY9ASYVFAF6CR0wVUtgkJoiAgdgaQlaBm1Zrg4DCuQ9R+5MOSFQR1tbDiwUUXBUXowf
997
+ J8c9SjRORzYSgVwAAAAAAgBK//ICRQLfABEAHgAAATIWFRQGIyImLwEVIxEzETc2EzI2NTQmIyIGH
998
+ QEUFgFUcYCVbiNJEyNWVigySElcU01JXmECIJd4i5QTEDRJAt/+3jkq/hRuZV55ZWsdX14AAQAe//
999
+ IB9wIgABgAAAEyFhcjJiMiBhUUFjMyNjczDgEjIiY1NDYBF152DFocbEJXU0A1Rw1aE3pbaoKQAiB
1000
+ oWH5qZm1tPDlaXYuLgZcAAAACAB7/8gIZAt8AEQAeAAABESM1BwYjIiY1NDYzMhYfAREDMjY9ATQm
1001
+ IyIGFRQWAhlWKDJacYCVbiNJEyOnSV5hQUlcUwLf/SFVOSqXeIuUExA0ARb9VWVrHV9ebmVeeQACA
1002
+ B7/8gH9AiAAFQAbAAABFAchHgEzMjY3Mw4BIyImNTQ2MzIWJyIGByEmAf0C/oAGUkA1SwlaD4FXbI
1003
+ WObmt45UBVBwEqDQEYFhNjWD84W16Oh3+akU9aU60AAAEAFQAAARoC8gAWAAATBh0BMxUjESMRIzU
1004
+ zNTQ3PgEzMhcVJqcDbW1WOTkDB0k8Hx5oAngVITRC/jQBzEIsJRs5PwVHEwAAAAIAHv8uAhkCIAAi
1005
+ AC8AAAERFAcOASMiLwEzFx4BMzI2NzY9AQcGIyImNTQ2MzIWHwE1AzI2PQE0JiMiBhUUFgIZAQSEd
1006
+ NwRAVcBBU5DTlUDASgyWnGAlW4jSRMjp0leYUFJXFMCEv5wSh1zeq8KCTI8VU0ZIQk5Kpd4i5QTED
1007
+ RJ/iJlax1fXm5lXnkAAQBKAAACCgLkABcAAAEWFREjETQnLgEHDgEdASMRMxE3NjMyFgIIAlYCBDs
1008
+ 6RVRWViE5UVViAYUbQP7WASQxGzI7AQJyf+kC5P7TPSxUAAACAD4AAACsAsAABwALAAASMhYUBiIm
1009
+ NBMjETNeLiAgLiBiVlYCwCAuICAu/WACEgAC//P/LgCnAsAABwAVAAASMhYUBiImNBcRFAcGIyInN
1010
+ RY3NjURWS4gIC4gYgMLcRwNSgYCAsAgLiAgLo79wCUbZAJGBzMOHgJEAAAAAQBKAAACCALfAAsAAC
1011
+ EnBxUjETMREzMHEwGTwTJWVvdu9/rgN6kC3/4oAQv6/ugAAQBG//wA3gLfAA8AABMRFBceATcVBiM
1012
+ iJicmNRGcAQIcIxkkKi4CAQLf/bkhERoSBD4EJC8SNAJKAAAAAQBKAAADEAIgACQAAAEWFREjETQn
1013
+ JiMiFREjETQnJiMiFREjETMVNzYzMhYXNzYzMhYDCwVWBAxedFYEDF50VlYiJko7ThAvJkpEVAGfI
1014
+ jn+vAEcQyRZ1v76ARxDJFnW/voCEk08HzYtRB9HAAAAAAEASgAAAgoCIAAWAAABFhURIxE0JyYjIg
1015
+ YdASMRMxU3NjMyFgIIAlYCCXBEVVZWITlRVWIBhRtA/tYBJDEbbHR/6QISWz0sVAAAAAACAB7/8gI
1016
+ sAiAABwARAAASIBYUBiAmNBIyNjU0JiIGFRSlAQCHh/8Ah7ieWlqeWgIgn/Cfn/D+s3ZfYHV1YF8A
1017
+ AgBK/zwCRQIgABEAHgAAATIWFRQGIyImLwERIxEzFTc2EzI2NTQmIyIGHQEUFgFUcYCVbiNJEyNWV
1018
+ igySElcU01JXmECIJd4i5QTEDT+8wLWVTkq/hRuZV55ZWsdX14AAgAe/zwCGQIgABEAHgAAAREjEQ
1019
+ cGIyImNTQ2MzIWHwE1AzI2PQE0JiMiBhUUFgIZVigyWnGAlW4jSRMjp0leYUFJXFMCEv0qARk5Kpd
1020
+ 4i5QTEDRJ/iJlax1fXm5lXnkAAQBKAAABPgIeAA0AAAEyFxUmBhURIxEzFTc2ARoWDkdXVlYwIwIe
1021
+ B0EFVlf+0gISU0cYAAEAGP/yAa0CIAAjAAATMhYXIyYjIgYVFBYXHgEVFAYjIiYnMxYzMjY1NCYnL
1022
+ gE1NDbkV2MJWhNdKy04PF1XbVhWbgxaE2ktOjlEUllkAiBaS2MrJCUoEBlPQkhOVFZoKCUmLhIWSE
1023
+ BIUwAAAAEAFP/4ARQCiQAXAAATERQXHgE3FQYjIiYnJjURIzUzNTMVMxWxAQMmMx8qMjMEAUdHVmM
1024
+ BzP7PGw4mFgY/BSwxDjQBNUJ7e0IAAAABAEL/8gICAhIAFwAAAREjNQcGIyImJyY1ETMRFBceATMy
1025
+ Nj0BAgJWITlRT2EKBVYEBkA1RFECEv3uWj4qTToiOQE+/tIlJC43c4DpAAAAAAEAAQAAAfwCEgAGA
1026
+ AABAyMDMxsBAfzJaclfop8CEv3uAhL+LQHTAAABAAEAAAMLAhIADAAAAQMjCwEjAzMbATMbAQMLqW
1027
+ Z2dmapY3t0a3Z7AhL97gG+/kICEv5AAcD+QwG9AAAB//oAAAHWAhIACwAAARMjJwcjEwMzFzczARq
1028
+ 8ZIuKY763ZoWFYwEO/vLV1QEMAQbNzQAAAQAB/y4B+wISABEAAAEDDgEjIic1FjMyNj8BAzMbAQH7
1029
+ 2iFZQB8NDRIpNhQH02GenQIS/cFVUAJGASozEwIt/i4B0gABABQAAAGxAg4ACQAAJRUhNQEhNSEVA
1030
+ QGx/mMBNP7iAYL+zkREQgGIREX+ewAAAAABAED/sAEOAwwALAAAASMiBhUUFxYVFAYHHgEVFAcGFR
1031
+ QWOwEVIyImNTQ3NjU0JzU2NTQnJjU0NjsBAQ4MKiMLDS4pKS4NCyMqDAtERAwLUlILDERECwLUGBk
1032
+ WTlsgKzUFBTcrIFtOFhkYOC87GFVMIkUIOAhFIkxVGDsvAAAAAAEAYP84AJoDIAADAAAXIxEzmjo6
1033
+ yAPoAAEAIf+wAO8DDAAsAAATFQYVFBcWFRQGKwE1MzI2NTQnJjU0NjcuATU0NzY1NCYrATUzMhYVF
1034
+ AcGFRTvUgsMREQLDCojCw0uKSkuDQsjKgwLREQMCwF6OAhFIkxVGDsvOBgZFk5bICs1BQU3KyBbTh
1035
+ YZGDgvOxhVTCJFAAABAE0A3wH2AWQAEwAAATMUIyImJyYjIhUjNDMyFhcWMzIBvjhuGywtQR0xOG4
1036
+ bLC1BHTEBZIURGCNMhREYIwAAAwAk/94DIgLoAAcAEQApAAAAIBYQBiAmECQgBhUUFiA2NTQlMhYX
1037
+ IyYjIgYUFjMyNjczDgEjIiY1NDYBAQFE3d3+vN0CB/7wubkBELn+xVBnD1wSWDo+QTcqOQZcEmZWX
1038
+ HN2Aujg/rbg4AFKpr+Mjb6+jYxbWEldV5ZZNShLVn5na34AAgB4AFIB9AGeAAUACwAAAQcXIyc3Mw
1039
+ cXIyc3AUqJiUmJifOJiUmJiQGepqampqampqYAAAIAHAHSAQ4CwAAHAA8AABIyFhQGIiY0NiIGFBY
1040
+ yNjRgakREakSTNCEhNCECwEJqQkJqCiM4IyM4AAAAAAIAUAAAAfQCCwALAA8AAAEzFSMVIzUjNTM1
1041
+ MxMhNSEBP7W1OrW1OrX+XAGkAVs4tLQ4sP31OAAAAQB0AkQBAQKyAAMAABMjNzOsOD1QAkRuAAAAA
1042
+ AEAIADsAKoBdgAHAAASMhYUBiImNEg6KCg6KAF2KDooKDoAAAIAOQBSAbUBngAFAAsAACUHIzcnMw
1043
+ UHIzcnMwELiUmJiUkBM4lJiYlJ+KampqampqYAAAABADYB5QDhAt8ABAAAEzczByM2Xk1OXQHv8Po
1044
+ AAQAWAeUAwQLfAAQAABMHIzczwV5NTl0C1fD6AAIANgHlAYsC3wAEAAkAABM3MwcjPwEzByM2Xk1O
1045
+ XapeTU5dAe/w+grw+gAAAgAWAeUBawLfAAQACQAAEwcjNzMXByM3M8FeTU5dql5NTl0C1fD6CvD6A
1046
+ AADACX/8gI1AHIABwAPABcAADYyFhQGIiY0NjIWFAYiJjQ2MhYUBiImNEk4JCQ4JOw4JCQ4JOw4JC
1047
+ Q4JHIkOCQkOCQkOCQkOCQkOCQkOAAAAAEAeABSAUoBngAFAAABBxcjJzcBSomJSYmJAZ6mpqamAAA
1048
+ AAAEAOQBSAQsBngAFAAAlByM3JzMBC4lJiYlJ+KampgAAAf9qAAABgQKyAAMAACsBATM/VwHAVwKy
1049
+ AAAAAAIAFAHIAdwClAAHABQAABMVIxUjNSM1BRUjNwcjJxcjNTMXN9pKMkoByDICKzQqATJLKysCl
1050
+ CmjoykBy46KiY3Lm5sAAQAVAAABvALyABgAAAERIxEjESMRIzUzNTQ3NjMyFxUmBgcGHQEBvFbCVj
1051
+ k5AxHHHx5iVgcDAg798gHM/jQBzEIOJRuWBUcIJDAVIRYAAAABABX//AHkAvIAJQAAJR4BNxUGIyI
1052
+ mJyY1ESYjIgcGHQEzFSMRIxEjNTM1NDc2MzIXERQBowIcIxkkKi4CAR4nXgwDbW1WLy8DEbNdOmYa
1053
+ EQQ/BCQvEjQCFQZWFSEWQv40AcxCDiUblhP9uSEAAAAAAAAWAQ4AAQAAAAAAAAATACgAAQAAAAAAA
1054
+ QAHAEwAAQAAAAAAAgAHAGQAAQAAAAAAAwAaAKIAAQAAAAAABAAHAM0AAQAAAAAABQA8AU8AAQAAAA
1055
+ AABgAPAawAAQAAAAAACAALAdQAAQAAAAAACQALAfgAAQAAAAAACwAXAjQAAQAAAAAADAAXAnwAAwA
1056
+ BBAkAAAAmAAAAAwABBAkAAQAOADwAAwABBAkAAgAOAFQAAwABBAkAAwA0AGwAAwABBAkABAAOAL0A
1057
+ AwABBAkABQB4ANUAAwABBAkABgAeAYwAAwABBAkACAAWAbwAAwABBAkACQAWAeAAAwABBAkACwAuA
1058
+ gQAAwABBAkADAAuAkwATgBvACAAUgBpAGcAaAB0AHMAIABSAGUAcwBlAHIAdgBlAGQALgAATm8gUm
1059
+ lnaHRzIFJlc2VydmVkLgAAQQBpAGwAZQByAG8AbgAAQWlsZXJvbgAAUgBlAGcAdQBsAGEAcgAAUmV
1060
+ ndWxhcgAAMQAuADEAMAAyADsAVQBLAFcATgA7AEEAaQBsAGUAcgBvAG4ALQBSAGUAZwB1AGwAYQBy
1061
+ AAAxLjEwMjtVS1dOO0FpbGVyb24tUmVndWxhcgAAQQBpAGwAZQByAG8AbgAAQWlsZXJvbgAAVgBlA
1062
+ HIAcwBpAG8AbgAgADEALgAxADAAMgA7AFAAUwAgADAAMAAxAC4AMQAwADIAOwBoAG8AdABjAG8Abg
1063
+ B2ACAAMQAuADAALgA3ADAAOwBtAGEAawBlAG8AdABmAC4AbABpAGIAMgAuADUALgA1ADgAMwAyADk
1064
+ AAFZlcnNpb24gMS4xMDI7UFMgMDAxLjEwMjtob3Rjb252IDEuMC43MDttYWtlb3RmLmxpYjIuNS41
1065
+ ODMyOQAAQQBpAGwAZQByAG8AbgAtAFIAZQBnAHUAbABhAHIAAEFpbGVyb24tUmVndWxhcgAAUwBvA
1066
+ HIAYQAgAFMAYQBnAGEAbgBvAABTb3JhIFNhZ2FubwAAUwBvAHIAYQAgAFMAYQBnAGEAbgBvAABTb3
1067
+ JhIFNhZ2FubwAAaAB0AHQAcAA6AC8ALwB3AHcAdwAuAGQAbwB0AGMAbwBsAG8AbgAuAG4AZQB0AAB
1068
+ odHRwOi8vd3d3LmRvdGNvbG9uLm5ldAAAaAB0AHQAcAA6AC8ALwB3AHcAdwAuAGQAbwB0AGMAbwBs
1069
+ AG8AbgAuAG4AZQB0AABodHRwOi8vd3d3LmRvdGNvbG9uLm5ldAAAAAACAAAAAAAA/4MAMgAAAAAAA
1070
+ AAAAAAAAAAAAAAAAAAAAHQAAAABAAIAAwAEAAUABgAHAAgACQAKAAsADAANAA4ADwAQABEAEgATAB
1071
+ QAFQAWABcAGAAZABoAGwAcAB0AHgAfACAAIQAiACMAJAAlACYAJwAoACkAKgArACwALQAuAC8AMAA
1072
+ xADIAMwA0ADUANgA3ADgAOQA6ADsAPAA9AD4APwBAAEEAQgBDAEQARQBGAEcASABJAEoASwBMAE0A
1073
+ TgBPAFAAUQBSAFMAVABVAFYAVwBYAFkAWgBbAFwAXQBeAF8AYABhAIsAqQCDAJMAjQDDAKoAtgC3A
1074
+ LQAtQCrAL4AvwC8AIwAwADBAAAAAAAB//8AAgABAAAADAAAABwAAAACAAIAAwBxAAEAcgBzAAIABA
1075
+ AAAAIAAAABAAAACgBMAGYAAkRGTFQADmxhdG4AGgAEAAAAAP//AAEAAAAWAANDQVQgAB5NT0wgABZ
1076
+ ST00gABYAAP//AAEAAAAA//8AAgAAAAEAAmxpZ2EADmxvY2wAFAAAAAEAAQAAAAEAAAACAAYAEAAG
1077
+ AAAAAgASADQABAAAAAEATAADAAAAAgAQABYAAQAcAAAAAQABAE8AAQABAGcAAQABAE8AAwAAAAIAE
1078
+ AAWAAEAHAAAAAEAAQAvAAEAAQBnAAEAAQAvAAEAGgABAAgAAgAGAAwAcwACAE8AcgACAEwAAQABAE
1079
+ kAAAABAAAACgBGAGAAAkRGTFQADmxhdG4AHAAEAAAAAP//AAIAAAABABYAA0NBVCAAFk1PTCAAFlJ
1080
+ PTSAAFgAA//8AAgAAAAEAAmNwc3AADmtlcm4AFAAAAAEAAAAAAAEAAQACAAYADgABAAAAAQASAAIA
1081
+ AAACAB4ANgABAAoABQAFAAoAAgABACQAPQAAAAEAEgAEAAAAAQAMAAEAOP/nAAEAAQAkAAIGigAEA
1082
+ AAFJAXKABoAGQAA//gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
1083
+ AAAAD/sv+4/+z/7v/MAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
1084
+ AAAAAAAD/xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/9T/6AAAAAD/8QAA
1085
+ ABD/vQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/7gAAAAAAAAAAAAAAAAAA//MAA
1086
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABIAAAAAAAAAAP/5AAAAAAAAAA
1087
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP/gAAD/4AAAAAAAAAAAAAAAAAA
1088
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//L/9AAAAAAAAAAAAAAAAAAAAAAA
1089
+ AAAAAAAAAAAA/+gAAAAAAAkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
1090
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP/zAAAAAA
1091
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP/mAAAAAAAAAAAAAAAAAAD
1092
+ /4gAA//AAAAAA//YAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/+AAAAAAAAP/OAAAAAAAAAAAAAAAA
1093
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/zv/qAAAAAP/0AAAACAAAAAAAAAAAAAAAAAAAAAAAA
1094
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP/ZAAD/egAA/1kAAAAA/5D/rgAAAAAAAAAAAA
1095
+ AAAAAAAAAAAAAAAAD/9AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
1096
+ AAAAAAAAAAAAAAAAAAAD/8AAA/7b/8P+wAAD/8P/E/98AAAAA/8P/+P/0//oAAAAAAAAAAAAA//gA
1097
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/+AAAAAAAAAAAAAAA
1098
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/w//C/9MAAP/SAAD/9wAAAAAAAA
1099
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAD/yAAA/+kAAAAA//QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
1100
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/9wAAAAD//QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
1101
+ AAAAAAAAAAAAAAAAAAAAAP/2AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
1102
+ AAAAAAAAP/cAAAAAAAAAAAAAAAA/7YAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
1103
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAP/8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/6AAAAAAAAAA
1104
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAkAFAAEAAAAAQACwAAABcA
1105
+ BgAAAAAAAAAIAA4AAAAAAAsAEgAAAAAAAAATABkAAwANAAAAAQAJAAAAAAAAAAAAAAAAAAAAGAAAA
1106
+ AAABwAAAAAAAAAAAAAAFQAFAAAAAAAYABgAAAAUAAAACgAAAAwAAgAPABEAFgAAAAAAAAAAAAAAAA
1107
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAEAEQBdAAYAAAAAAAAAAAAAAAAAAAAAAAA
1108
+ AAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAcAAAAAAAAABwAAAAAACAAAAAAAAAAAAAcAAAAHAAAAEwAJ
1109
+ ABUADgAPAAAACwAQAAAAAAAAAAAAAAAAAAUAGAACAAIAAgAAAAIAGAAXAAAAGAAAABYAFgACABYAA
1110
+ gAWAAAAEQADAAoAFAAMAA0ABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASAAAAEgAGAAEAHgAkAC
1111
+ YAJwApACoALQAuAC8AMgAzADcAOAA5ADoAPAA9AEUASABOAE8AUgBTAFUAVwBZAFoAWwBcAF0AcwA
1112
+ AAAAAAQAAAADa3tfFAAAAANAan9kAAAAA4QodoQ==
1113
+ """
1114
+ )
1115
+ ),
1116
+ 10 if size is None else size,
1117
+ layout_engine=Layout.BASIC,
1118
+ )
1119
+ else:
1120
+ f = ImageFont()
1121
+ f._load_pilfont_data(
1122
+ # courB08
1123
+ BytesIO(
1124
+ base64.b64decode(
1125
+ b"""
1126
+ UElMZm9udAo7Ozs7OzsxMDsKREFUQQoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
1127
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
1128
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
1129
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
1130
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
1131
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
1132
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
1133
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
1134
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
1135
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
1136
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
1137
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAAA//8AAQAAAAAAAAABAAEA
1138
+ BgAAAAH/+gADAAAAAQAAAAMABgAGAAAAAf/6AAT//QADAAAABgADAAYAAAAA//kABQABAAYAAAAL
1139
+ AAgABgAAAAD/+AAFAAEACwAAABAACQAGAAAAAP/5AAUAAAAQAAAAFQAHAAYAAP////oABQAAABUA
1140
+ AAAbAAYABgAAAAH/+QAE//wAGwAAAB4AAwAGAAAAAf/5AAQAAQAeAAAAIQAIAAYAAAAB//kABAAB
1141
+ ACEAAAAkAAgABgAAAAD/+QAE//0AJAAAACgABAAGAAAAAP/6AAX//wAoAAAALQAFAAYAAAAB//8A
1142
+ BAACAC0AAAAwAAMABgAAAAD//AAF//0AMAAAADUAAQAGAAAAAf//AAMAAAA1AAAANwABAAYAAAAB
1143
+ //kABQABADcAAAA7AAgABgAAAAD/+QAFAAAAOwAAAEAABwAGAAAAAP/5AAYAAABAAAAARgAHAAYA
1144
+ AAAA//kABQAAAEYAAABLAAcABgAAAAD/+QAFAAAASwAAAFAABwAGAAAAAP/5AAYAAABQAAAAVgAH
1145
+ AAYAAAAA//kABQAAAFYAAABbAAcABgAAAAD/+QAFAAAAWwAAAGAABwAGAAAAAP/5AAUAAABgAAAA
1146
+ ZQAHAAYAAAAA//kABQAAAGUAAABqAAcABgAAAAD/+QAFAAAAagAAAG8ABwAGAAAAAf/8AAMAAABv
1147
+ AAAAcQAEAAYAAAAA//wAAwACAHEAAAB0AAYABgAAAAD/+gAE//8AdAAAAHgABQAGAAAAAP/7AAT/
1148
+ /gB4AAAAfAADAAYAAAAB//oABf//AHwAAACAAAUABgAAAAD/+gAFAAAAgAAAAIUABgAGAAAAAP/5
1149
+ AAYAAQCFAAAAiwAIAAYAAP////oABgAAAIsAAACSAAYABgAA////+gAFAAAAkgAAAJgABgAGAAAA
1150
+ AP/6AAUAAACYAAAAnQAGAAYAAP////oABQAAAJ0AAACjAAYABgAA////+gAFAAAAowAAAKkABgAG
1151
+ AAD////6AAUAAACpAAAArwAGAAYAAAAA//oABQAAAK8AAAC0AAYABgAA////+gAGAAAAtAAAALsA
1152
+ BgAGAAAAAP/6AAQAAAC7AAAAvwAGAAYAAP////oABQAAAL8AAADFAAYABgAA////+gAGAAAAxQAA
1153
+ AMwABgAGAAD////6AAUAAADMAAAA0gAGAAYAAP////oABQAAANIAAADYAAYABgAA////+gAGAAAA
1154
+ 2AAAAN8ABgAGAAAAAP/6AAUAAADfAAAA5AAGAAYAAP////oABQAAAOQAAADqAAYABgAAAAD/+gAF
1155
+ AAEA6gAAAO8ABwAGAAD////6AAYAAADvAAAA9gAGAAYAAAAA//oABQAAAPYAAAD7AAYABgAA////
1156
+ +gAFAAAA+wAAAQEABgAGAAD////6AAYAAAEBAAABCAAGAAYAAP////oABgAAAQgAAAEPAAYABgAA
1157
+ ////+gAGAAABDwAAARYABgAGAAAAAP/6AAYAAAEWAAABHAAGAAYAAP////oABgAAARwAAAEjAAYA
1158
+ BgAAAAD/+gAFAAABIwAAASgABgAGAAAAAf/5AAQAAQEoAAABKwAIAAYAAAAA//kABAABASsAAAEv
1159
+ AAgABgAAAAH/+QAEAAEBLwAAATIACAAGAAAAAP/5AAX//AEyAAABNwADAAYAAAAAAAEABgACATcA
1160
+ AAE9AAEABgAAAAH/+QAE//wBPQAAAUAAAwAGAAAAAP/7AAYAAAFAAAABRgAFAAYAAP////kABQAA
1161
+ AUYAAAFMAAcABgAAAAD/+wAFAAABTAAAAVEABQAGAAAAAP/5AAYAAAFRAAABVwAHAAYAAAAA//sA
1162
+ BQAAAVcAAAFcAAUABgAAAAD/+QAFAAABXAAAAWEABwAGAAAAAP/7AAYAAgFhAAABZwAHAAYAAP//
1163
+ //kABQAAAWcAAAFtAAcABgAAAAD/+QAGAAABbQAAAXMABwAGAAAAAP/5AAQAAgFzAAABdwAJAAYA
1164
+ AP////kABgAAAXcAAAF+AAcABgAAAAD/+QAGAAABfgAAAYQABwAGAAD////7AAUAAAGEAAABigAF
1165
+ AAYAAP////sABQAAAYoAAAGQAAUABgAAAAD/+wAFAAABkAAAAZUABQAGAAD////7AAUAAgGVAAAB
1166
+ mwAHAAYAAAAA//sABgACAZsAAAGhAAcABgAAAAD/+wAGAAABoQAAAacABQAGAAAAAP/7AAYAAAGn
1167
+ AAABrQAFAAYAAAAA//kABgAAAa0AAAGzAAcABgAA////+wAGAAABswAAAboABQAGAAD////7AAUA
1168
+ AAG6AAABwAAFAAYAAP////sABgAAAcAAAAHHAAUABgAAAAD/+wAGAAABxwAAAc0ABQAGAAD////7
1169
+ AAYAAgHNAAAB1AAHAAYAAAAA//sABQAAAdQAAAHZAAUABgAAAAH/+QAFAAEB2QAAAd0ACAAGAAAA
1170
+ Av/6AAMAAQHdAAAB3gAHAAYAAAAA//kABAABAd4AAAHiAAgABgAAAAD/+wAF//0B4gAAAecAAgAA
1171
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
1172
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
1173
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
1174
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
1175
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
1176
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
1177
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
1178
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
1179
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
1180
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
1181
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
1182
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAAB
1183
+ //sAAwACAecAAAHpAAcABgAAAAD/+QAFAAEB6QAAAe4ACAAGAAAAAP/5AAYAAAHuAAAB9AAHAAYA
1184
+ AAAA//oABf//AfQAAAH5AAUABgAAAAD/+QAGAAAB+QAAAf8ABwAGAAAAAv/5AAMAAgH/AAACAAAJ
1185
+ AAYAAAAA//kABQABAgAAAAIFAAgABgAAAAH/+gAE//sCBQAAAggAAQAGAAAAAP/5AAYAAAIIAAAC
1186
+ DgAHAAYAAAAB//kABf/+Ag4AAAISAAUABgAA////+wAGAAACEgAAAhkABQAGAAAAAP/7AAX//gIZ
1187
+ AAACHgADAAYAAAAA//wABf/9Ah4AAAIjAAEABgAAAAD/+QAHAAACIwAAAioABwAGAAAAAP/6AAT/
1188
+ +wIqAAACLgABAAYAAAAA//kABP/8Ai4AAAIyAAMABgAAAAD/+gAFAAACMgAAAjcABgAGAAAAAf/5
1189
+ AAT//QI3AAACOgAEAAYAAAAB//kABP/9AjoAAAI9AAQABgAAAAL/+QAE//sCPQAAAj8AAgAGAAD/
1190
+ ///7AAYAAgI/AAACRgAHAAYAAAAA//kABgABAkYAAAJMAAgABgAAAAH//AAD//0CTAAAAk4AAQAG
1191
+ AAAAAf//AAQAAgJOAAACUQADAAYAAAAB//kABP/9AlEAAAJUAAQABgAAAAH/+QAF//4CVAAAAlgA
1192
+ BQAGAAD////7AAYAAAJYAAACXwAFAAYAAP////kABgAAAl8AAAJmAAcABgAA////+QAGAAACZgAA
1193
+ Am0ABwAGAAD////5AAYAAAJtAAACdAAHAAYAAAAA//sABQACAnQAAAJ5AAcABgAA////9wAGAAAC
1194
+ eQAAAoAACQAGAAD////3AAYAAAKAAAAChwAJAAYAAP////cABgAAAocAAAKOAAkABgAA////9wAG
1195
+ AAACjgAAApUACQAGAAD////4AAYAAAKVAAACnAAIAAYAAP////cABgAAApwAAAKjAAkABgAA////
1196
+ +gAGAAACowAAAqoABgAGAAAAAP/6AAUAAgKqAAACrwAIAAYAAP////cABQAAAq8AAAK1AAkABgAA
1197
+ ////9wAFAAACtQAAArsACQAGAAD////3AAUAAAK7AAACwQAJAAYAAP////gABQAAAsEAAALHAAgA
1198
+ BgAAAAD/9wAEAAACxwAAAssACQAGAAAAAP/3AAQAAALLAAACzwAJAAYAAAAA//cABAAAAs8AAALT
1199
+ AAkABgAAAAD/+AAEAAAC0wAAAtcACAAGAAD////6AAUAAALXAAAC3QAGAAYAAP////cABgAAAt0A
1200
+ AALkAAkABgAAAAD/9wAFAAAC5AAAAukACQAGAAAAAP/3AAUAAALpAAAC7gAJAAYAAAAA//cABQAA
1201
+ Au4AAALzAAkABgAAAAD/9wAFAAAC8wAAAvgACQAGAAAAAP/4AAUAAAL4AAAC/QAIAAYAAAAA//oA
1202
+ Bf//Av0AAAMCAAUABgAA////+gAGAAADAgAAAwkABgAGAAD////3AAYAAAMJAAADEAAJAAYAAP//
1203
+ //cABgAAAxAAAAMXAAkABgAA////9wAGAAADFwAAAx4ACQAGAAD////4AAYAAAAAAAoABwASAAYA
1204
+ AP////cABgAAAAcACgAOABMABgAA////+gAFAAAADgAKABQAEAAGAAD////6AAYAAAAUAAoAGwAQ
1205
+ AAYAAAAA//gABgAAABsACgAhABIABgAAAAD/+AAGAAAAIQAKACcAEgAGAAAAAP/4AAYAAAAnAAoA
1206
+ LQASAAYAAAAA//gABgAAAC0ACgAzABIABgAAAAD/+QAGAAAAMwAKADkAEQAGAAAAAP/3AAYAAAA5
1207
+ AAoAPwATAAYAAP////sABQAAAD8ACgBFAA8ABgAAAAD/+wAFAAIARQAKAEoAEQAGAAAAAP/4AAUA
1208
+ AABKAAoATwASAAYAAAAA//gABQAAAE8ACgBUABIABgAAAAD/+AAFAAAAVAAKAFkAEgAGAAAAAP/5
1209
+ AAUAAABZAAoAXgARAAYAAAAA//gABgAAAF4ACgBkABIABgAAAAD/+AAGAAAAZAAKAGoAEgAGAAAA
1210
+ AP/4AAYAAABqAAoAcAASAAYAAAAA//kABgAAAHAACgB2ABEABgAAAAD/+AAFAAAAdgAKAHsAEgAG
1211
+ AAD////4AAYAAAB7AAoAggASAAYAAAAA//gABQAAAIIACgCHABIABgAAAAD/+AAFAAAAhwAKAIwA
1212
+ EgAGAAAAAP/4AAUAAACMAAoAkQASAAYAAAAA//gABQAAAJEACgCWABIABgAAAAD/+QAFAAAAlgAK
1213
+ AJsAEQAGAAAAAP/6AAX//wCbAAoAoAAPAAYAAAAA//oABQABAKAACgClABEABgAA////+AAGAAAA
1214
+ pQAKAKwAEgAGAAD////4AAYAAACsAAoAswASAAYAAP////gABgAAALMACgC6ABIABgAA////+QAG
1215
+ AAAAugAKAMEAEQAGAAD////4AAYAAgDBAAoAyAAUAAYAAP////kABQACAMgACgDOABMABgAA////
1216
+ +QAGAAIAzgAKANUAEw==
1217
+ """
1218
+ )
1219
+ ),
1220
+ Image.open(
1221
+ BytesIO(
1222
+ base64.b64decode(
1223
+ b"""
1224
+ iVBORw0KGgoAAAANSUhEUgAAAx4AAAAUAQAAAAArMtZoAAAEwElEQVR4nABlAJr/AHVE4czCI/4u
1225
+ Mc4b7vuds/xzjz5/3/7u/n9vMe7vnfH/9++vPn/xyf5zhxzjt8GHw8+2d83u8x27199/nxuQ6Od9
1226
+ M43/5z2I+9n9ZtmDBwMQECDRQw/eQIQohJXxpBCNVE6QCCAAAAD//wBlAJr/AgALyj1t/wINwq0g
1227
+ LeNZUworuN1cjTPIzrTX6ofHWeo3v336qPzfEwRmBnHTtf95/fglZK5N0PDgfRTslpGBvz7LFc4F
1228
+ IUXBWQGjQ5MGCx34EDFPwXiY4YbYxavpnhHFrk14CDAAAAD//wBlAJr/AgKqRooH2gAgPeggvUAA
1229
+ Bu2WfgPoAwzRAABAAAAAAACQgLz/3Uv4Gv+gX7BJgDeeGP6AAAD1NMDzKHD7ANWr3loYbxsAD791
1230
+ NAADfcoIDyP44K/jv4Y63/Z+t98Ovt+ub4T48LAAAAD//wBlAJr/AuplMlADJAAAAGuAphWpqhMx
1231
+ in0A/fRvAYBABPgBwBUgABBQ/sYAyv9g0bCHgOLoGAAAAAAAREAAwI7nr0ArYpow7aX8//9LaP/9
1232
+ SjdavWA8ePHeBIKB//81/83ndznOaXx379wAAAD//wBlAJr/AqDxW+D3AABAAbUh/QMnbQag/gAY
1233
+ AYDAAACgtgD/gOqAAAB5IA/8AAAk+n9w0AAA8AAAmFRJuPo27ciC0cD5oeW4E7KA/wD3ECMAn2tt
1234
+ y8PgwH8AfAxFzC0JzeAMtratAsC/ffwAAAD//wBlAJr/BGKAyCAA4AAAAvgeYTAwHd1kmQF5chkG
1235
+ ABoMIHcL5xVpTfQbUqzlAAAErwAQBgAAEOClA5D9il08AEh/tUzdCBsXkbgACED+woQg8Si9VeqY
1236
+ lODCn7lmF6NhnAEYgAAA/NMIAAAAAAD//2JgjLZgVGBg5Pv/Tvpc8hwGBjYGJADjHDrAwPzAjv/H
1237
+ /Wf3PzCwtzcwHmBgYGcwbZz8wHaCAQMDOwMDQ8MCBgYOC3W7mp+f0w+wHOYxO3OG+e376hsMZjk3
1238
+ AAAAAP//YmCMY2A4wMAIN5e5gQETPD6AZisDAwMDgzSDAAPjByiHcQMDAwMDg1nOze1lByRu5/47
1239
+ c4859311AYNZzg0AAAAA//9iYGDBYihOIIMuwIjGL39/fwffA8b//xv/P2BPtzzHwCBjUQAAAAD/
1240
+ /yLFBrIBAAAA//9i1HhcwdhizX7u8NZNzyLbvT97bfrMf/QHI8evOwcSqGUJAAAA//9iYBB81iSw
1241
+ pEE170Qrg5MIYydHqwdDQRMrAwcVrQAAAAD//2J4x7j9AAMDn8Q/BgYLBoaiAwwMjPdvMDBYM1Tv
1242
+ oJodAAAAAP//Yqo/83+dxePWlxl3npsel9lvLfPcqlE9725C+acfVLMEAAAA//9i+s9gwCoaaGMR
1243
+ evta/58PTEWzr21hufPjA8N+qlnBwAAAAAD//2JiWLci5v1+HmFXDqcnULE/MxgYGBj+f6CaJQAA
1244
+ AAD//2Ji2FrkY3iYpYC5qDeGgeEMAwPDvwQBBoYvcTwOVLMEAAAA//9isDBgkP///0EOg9z35v//
1245
+ Gc/eeW7BwPj5+QGZhANUswMAAAD//2JgqGBgYGBgqEMXlvhMPUsAAAAA//8iYDd1AAAAAP//AwDR
1246
+ w7IkEbzhVQAAAABJRU5ErkJggg==
1247
+ """
1248
+ )
1249
+ )
1250
+ ),
1251
+ )
1252
+ return f
.venv/Lib/site-packages/PIL/ImageGrab.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library
3
+ # $Id$
4
+ #
5
+ # screen grabber
6
+ #
7
+ # History:
8
+ # 2001-04-26 fl created
9
+ # 2001-09-17 fl use builtin driver, if present
10
+ # 2002-11-19 fl added grabclipboard support
11
+ #
12
+ # Copyright (c) 2001-2002 by Secret Labs AB
13
+ # Copyright (c) 2001-2002 by Fredrik Lundh
14
+ #
15
+ # See the README file for information on usage and redistribution.
16
+ #
17
+ from __future__ import annotations
18
+
19
+ import io
20
+ import os
21
+ import shutil
22
+ import subprocess
23
+ import sys
24
+ import tempfile
25
+
26
+ from . import Image
27
+
28
+
29
+ def grab(bbox=None, include_layered_windows=False, all_screens=False, xdisplay=None):
30
+ if xdisplay is None:
31
+ if sys.platform == "darwin":
32
+ fh, filepath = tempfile.mkstemp(".png")
33
+ os.close(fh)
34
+ args = ["screencapture"]
35
+ if bbox:
36
+ left, top, right, bottom = bbox
37
+ args += ["-R", f"{left},{top},{right-left},{bottom-top}"]
38
+ subprocess.call(args + ["-x", filepath])
39
+ im = Image.open(filepath)
40
+ im.load()
41
+ os.unlink(filepath)
42
+ if bbox:
43
+ im_resized = im.resize((right - left, bottom - top))
44
+ im.close()
45
+ return im_resized
46
+ return im
47
+ elif sys.platform == "win32":
48
+ offset, size, data = Image.core.grabscreen_win32(
49
+ include_layered_windows, all_screens
50
+ )
51
+ im = Image.frombytes(
52
+ "RGB",
53
+ size,
54
+ data,
55
+ # RGB, 32-bit line padding, origin lower left corner
56
+ "raw",
57
+ "BGR",
58
+ (size[0] * 3 + 3) & -4,
59
+ -1,
60
+ )
61
+ if bbox:
62
+ x0, y0 = offset
63
+ left, top, right, bottom = bbox
64
+ im = im.crop((left - x0, top - y0, right - x0, bottom - y0))
65
+ return im
66
+ try:
67
+ if not Image.core.HAVE_XCB:
68
+ msg = "Pillow was built without XCB support"
69
+ raise OSError(msg)
70
+ size, data = Image.core.grabscreen_x11(xdisplay)
71
+ except OSError:
72
+ if (
73
+ xdisplay is None
74
+ and sys.platform not in ("darwin", "win32")
75
+ and shutil.which("gnome-screenshot")
76
+ ):
77
+ fh, filepath = tempfile.mkstemp(".png")
78
+ os.close(fh)
79
+ subprocess.call(["gnome-screenshot", "-f", filepath])
80
+ im = Image.open(filepath)
81
+ im.load()
82
+ os.unlink(filepath)
83
+ if bbox:
84
+ im_cropped = im.crop(bbox)
85
+ im.close()
86
+ return im_cropped
87
+ return im
88
+ else:
89
+ raise
90
+ else:
91
+ im = Image.frombytes("RGB", size, data, "raw", "BGRX", size[0] * 4, 1)
92
+ if bbox:
93
+ im = im.crop(bbox)
94
+ return im
95
+
96
+
97
+ def grabclipboard():
98
+ if sys.platform == "darwin":
99
+ fh, filepath = tempfile.mkstemp(".png")
100
+ os.close(fh)
101
+ commands = [
102
+ 'set theFile to (open for access POSIX file "'
103
+ + filepath
104
+ + '" with write permission)',
105
+ "try",
106
+ " write (the clipboard as «class PNGf») to theFile",
107
+ "end try",
108
+ "close access theFile",
109
+ ]
110
+ script = ["osascript"]
111
+ for command in commands:
112
+ script += ["-e", command]
113
+ subprocess.call(script)
114
+
115
+ im = None
116
+ if os.stat(filepath).st_size != 0:
117
+ im = Image.open(filepath)
118
+ im.load()
119
+ os.unlink(filepath)
120
+ return im
121
+ elif sys.platform == "win32":
122
+ fmt, data = Image.core.grabclipboard_win32()
123
+ if fmt == "file": # CF_HDROP
124
+ import struct
125
+
126
+ o = struct.unpack_from("I", data)[0]
127
+ if data[16] != 0:
128
+ files = data[o:].decode("utf-16le").split("\0")
129
+ else:
130
+ files = data[o:].decode("mbcs").split("\0")
131
+ return files[: files.index("")]
132
+ if isinstance(data, bytes):
133
+ data = io.BytesIO(data)
134
+ if fmt == "png":
135
+ from . import PngImagePlugin
136
+
137
+ return PngImagePlugin.PngImageFile(data)
138
+ elif fmt == "DIB":
139
+ from . import BmpImagePlugin
140
+
141
+ return BmpImagePlugin.DibImageFile(data)
142
+ return None
143
+ else:
144
+ if os.getenv("WAYLAND_DISPLAY"):
145
+ session_type = "wayland"
146
+ elif os.getenv("DISPLAY"):
147
+ session_type = "x11"
148
+ else: # Session type check failed
149
+ session_type = None
150
+
151
+ if shutil.which("wl-paste") and session_type in ("wayland", None):
152
+ args = ["wl-paste", "-t", "image"]
153
+ elif shutil.which("xclip") and session_type in ("x11", None):
154
+ args = ["xclip", "-selection", "clipboard", "-t", "image/png", "-o"]
155
+ else:
156
+ msg = "wl-paste or xclip is required for ImageGrab.grabclipboard() on Linux"
157
+ raise NotImplementedError(msg)
158
+
159
+ p = subprocess.run(args, capture_output=True)
160
+ if p.returncode != 0:
161
+ err = p.stderr
162
+ for silent_error in [
163
+ # wl-paste, when the clipboard is empty
164
+ b"Nothing is copied",
165
+ # Ubuntu/Debian wl-paste, when the clipboard is empty
166
+ b"No selection",
167
+ # Ubuntu/Debian wl-paste, when an image isn't available
168
+ b"No suitable type of content copied",
169
+ # wl-paste or Ubuntu/Debian xclip, when an image isn't available
170
+ b" not available",
171
+ # xclip, when an image isn't available
172
+ b"cannot convert ",
173
+ # xclip, when the clipboard isn't initialized
174
+ b"xclip: Error: There is no owner for the ",
175
+ ]:
176
+ if silent_error in err:
177
+ return None
178
+ msg = f"{args[0]} error"
179
+ if err:
180
+ msg += f": {err.strip().decode()}"
181
+ raise ChildProcessError(msg)
182
+
183
+ data = io.BytesIO(p.stdout)
184
+ im = Image.open(data)
185
+ im.load()
186
+ return im
.venv/Lib/site-packages/PIL/ImageMath.py ADDED
@@ -0,0 +1,357 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library
3
+ # $Id$
4
+ #
5
+ # a simple math add-on for the Python Imaging Library
6
+ #
7
+ # History:
8
+ # 1999-02-15 fl Original PIL Plus release
9
+ # 2005-05-05 fl Simplified and cleaned up for PIL 1.1.6
10
+ # 2005-09-12 fl Fixed int() and float() for Python 2.4.1
11
+ #
12
+ # Copyright (c) 1999-2005 by Secret Labs AB
13
+ # Copyright (c) 2005 by Fredrik Lundh
14
+ #
15
+ # See the README file for information on usage and redistribution.
16
+ #
17
+ from __future__ import annotations
18
+
19
+ import builtins
20
+ from types import CodeType
21
+ from typing import Any, Callable
22
+
23
+ from . import Image, _imagingmath
24
+ from ._deprecate import deprecate
25
+
26
+
27
+ class _Operand:
28
+ """Wraps an image operand, providing standard operators"""
29
+
30
+ def __init__(self, im: Image.Image):
31
+ self.im = im
32
+
33
+ def __fixup(self, im1: _Operand | float) -> Image.Image:
34
+ # convert image to suitable mode
35
+ if isinstance(im1, _Operand):
36
+ # argument was an image.
37
+ if im1.im.mode in ("1", "L"):
38
+ return im1.im.convert("I")
39
+ elif im1.im.mode in ("I", "F"):
40
+ return im1.im
41
+ else:
42
+ msg = f"unsupported mode: {im1.im.mode}"
43
+ raise ValueError(msg)
44
+ else:
45
+ # argument was a constant
46
+ if isinstance(im1, (int, float)) and self.im.mode in ("1", "L", "I"):
47
+ return Image.new("I", self.im.size, im1)
48
+ else:
49
+ return Image.new("F", self.im.size, im1)
50
+
51
+ def apply(
52
+ self,
53
+ op: str,
54
+ im1: _Operand | float,
55
+ im2: _Operand | float | None = None,
56
+ mode: str | None = None,
57
+ ) -> _Operand:
58
+ im_1 = self.__fixup(im1)
59
+ if im2 is None:
60
+ # unary operation
61
+ out = Image.new(mode or im_1.mode, im_1.size, None)
62
+ im_1.load()
63
+ try:
64
+ op = getattr(_imagingmath, op + "_" + im_1.mode)
65
+ except AttributeError as e:
66
+ msg = f"bad operand type for '{op}'"
67
+ raise TypeError(msg) from e
68
+ _imagingmath.unop(op, out.im.id, im_1.im.id)
69
+ else:
70
+ # binary operation
71
+ im_2 = self.__fixup(im2)
72
+ if im_1.mode != im_2.mode:
73
+ # convert both arguments to floating point
74
+ if im_1.mode != "F":
75
+ im_1 = im_1.convert("F")
76
+ if im_2.mode != "F":
77
+ im_2 = im_2.convert("F")
78
+ if im_1.size != im_2.size:
79
+ # crop both arguments to a common size
80
+ size = (
81
+ min(im_1.size[0], im_2.size[0]),
82
+ min(im_1.size[1], im_2.size[1]),
83
+ )
84
+ if im_1.size != size:
85
+ im_1 = im_1.crop((0, 0) + size)
86
+ if im_2.size != size:
87
+ im_2 = im_2.crop((0, 0) + size)
88
+ out = Image.new(mode or im_1.mode, im_1.size, None)
89
+ im_1.load()
90
+ im_2.load()
91
+ try:
92
+ op = getattr(_imagingmath, op + "_" + im_1.mode)
93
+ except AttributeError as e:
94
+ msg = f"bad operand type for '{op}'"
95
+ raise TypeError(msg) from e
96
+ _imagingmath.binop(op, out.im.id, im_1.im.id, im_2.im.id)
97
+ return _Operand(out)
98
+
99
+ # unary operators
100
+ def __bool__(self) -> bool:
101
+ # an image is "true" if it contains at least one non-zero pixel
102
+ return self.im.getbbox() is not None
103
+
104
+ def __abs__(self) -> _Operand:
105
+ return self.apply("abs", self)
106
+
107
+ def __pos__(self) -> _Operand:
108
+ return self
109
+
110
+ def __neg__(self) -> _Operand:
111
+ return self.apply("neg", self)
112
+
113
+ # binary operators
114
+ def __add__(self, other: _Operand | float) -> _Operand:
115
+ return self.apply("add", self, other)
116
+
117
+ def __radd__(self, other: _Operand | float) -> _Operand:
118
+ return self.apply("add", other, self)
119
+
120
+ def __sub__(self, other: _Operand | float) -> _Operand:
121
+ return self.apply("sub", self, other)
122
+
123
+ def __rsub__(self, other: _Operand | float) -> _Operand:
124
+ return self.apply("sub", other, self)
125
+
126
+ def __mul__(self, other: _Operand | float) -> _Operand:
127
+ return self.apply("mul", self, other)
128
+
129
+ def __rmul__(self, other: _Operand | float) -> _Operand:
130
+ return self.apply("mul", other, self)
131
+
132
+ def __truediv__(self, other: _Operand | float) -> _Operand:
133
+ return self.apply("div", self, other)
134
+
135
+ def __rtruediv__(self, other: _Operand | float) -> _Operand:
136
+ return self.apply("div", other, self)
137
+
138
+ def __mod__(self, other: _Operand | float) -> _Operand:
139
+ return self.apply("mod", self, other)
140
+
141
+ def __rmod__(self, other: _Operand | float) -> _Operand:
142
+ return self.apply("mod", other, self)
143
+
144
+ def __pow__(self, other: _Operand | float) -> _Operand:
145
+ return self.apply("pow", self, other)
146
+
147
+ def __rpow__(self, other: _Operand | float) -> _Operand:
148
+ return self.apply("pow", other, self)
149
+
150
+ # bitwise
151
+ def __invert__(self) -> _Operand:
152
+ return self.apply("invert", self)
153
+
154
+ def __and__(self, other: _Operand | float) -> _Operand:
155
+ return self.apply("and", self, other)
156
+
157
+ def __rand__(self, other: _Operand | float) -> _Operand:
158
+ return self.apply("and", other, self)
159
+
160
+ def __or__(self, other: _Operand | float) -> _Operand:
161
+ return self.apply("or", self, other)
162
+
163
+ def __ror__(self, other: _Operand | float) -> _Operand:
164
+ return self.apply("or", other, self)
165
+
166
+ def __xor__(self, other: _Operand | float) -> _Operand:
167
+ return self.apply("xor", self, other)
168
+
169
+ def __rxor__(self, other: _Operand | float) -> _Operand:
170
+ return self.apply("xor", other, self)
171
+
172
+ def __lshift__(self, other: _Operand | float) -> _Operand:
173
+ return self.apply("lshift", self, other)
174
+
175
+ def __rshift__(self, other: _Operand | float) -> _Operand:
176
+ return self.apply("rshift", self, other)
177
+
178
+ # logical
179
+ def __eq__(self, other):
180
+ return self.apply("eq", self, other)
181
+
182
+ def __ne__(self, other):
183
+ return self.apply("ne", self, other)
184
+
185
+ def __lt__(self, other: _Operand | float) -> _Operand:
186
+ return self.apply("lt", self, other)
187
+
188
+ def __le__(self, other: _Operand | float) -> _Operand:
189
+ return self.apply("le", self, other)
190
+
191
+ def __gt__(self, other: _Operand | float) -> _Operand:
192
+ return self.apply("gt", self, other)
193
+
194
+ def __ge__(self, other: _Operand | float) -> _Operand:
195
+ return self.apply("ge", self, other)
196
+
197
+
198
+ # conversions
199
+ def imagemath_int(self: _Operand) -> _Operand:
200
+ return _Operand(self.im.convert("I"))
201
+
202
+
203
+ def imagemath_float(self: _Operand) -> _Operand:
204
+ return _Operand(self.im.convert("F"))
205
+
206
+
207
+ # logical
208
+ def imagemath_equal(self: _Operand, other: _Operand | float | None) -> _Operand:
209
+ return self.apply("eq", self, other, mode="I")
210
+
211
+
212
+ def imagemath_notequal(self: _Operand, other: _Operand | float | None) -> _Operand:
213
+ return self.apply("ne", self, other, mode="I")
214
+
215
+
216
+ def imagemath_min(self: _Operand, other: _Operand | float | None) -> _Operand:
217
+ return self.apply("min", self, other)
218
+
219
+
220
+ def imagemath_max(self: _Operand, other: _Operand | float | None) -> _Operand:
221
+ return self.apply("max", self, other)
222
+
223
+
224
+ def imagemath_convert(self: _Operand, mode: str) -> _Operand:
225
+ return _Operand(self.im.convert(mode))
226
+
227
+
228
+ ops = {
229
+ "int": imagemath_int,
230
+ "float": imagemath_float,
231
+ "equal": imagemath_equal,
232
+ "notequal": imagemath_notequal,
233
+ "min": imagemath_min,
234
+ "max": imagemath_max,
235
+ "convert": imagemath_convert,
236
+ }
237
+
238
+
239
+ def lambda_eval(
240
+ expression: Callable[[dict[str, Any]], Any],
241
+ options: dict[str, Any] = {},
242
+ **kw: Any,
243
+ ) -> Any:
244
+ """
245
+ Returns the result of an image function.
246
+
247
+ :py:mod:`~PIL.ImageMath` only supports single-layer images. To process multi-band
248
+ images, use the :py:meth:`~PIL.Image.Image.split` method or
249
+ :py:func:`~PIL.Image.merge` function.
250
+
251
+ :param expression: A function that receives a dictionary.
252
+ :param options: Values to add to the function's dictionary. You
253
+ can either use a dictionary, or one or more keyword
254
+ arguments.
255
+ :return: The expression result. This is usually an image object, but can
256
+ also be an integer, a floating point value, or a pixel tuple,
257
+ depending on the expression.
258
+ """
259
+
260
+ args: dict[str, Any] = ops.copy()
261
+ args.update(options)
262
+ args.update(kw)
263
+ for k, v in args.items():
264
+ if hasattr(v, "im"):
265
+ args[k] = _Operand(v)
266
+
267
+ out = expression(args)
268
+ try:
269
+ return out.im
270
+ except AttributeError:
271
+ return out
272
+
273
+
274
+ def unsafe_eval(
275
+ expression: str,
276
+ options: dict[str, Any] = {},
277
+ **kw: Any,
278
+ ) -> Any:
279
+ """
280
+ Evaluates an image expression. This uses Python's ``eval()`` function to process
281
+ the expression string, and carries the security risks of doing so. It is not
282
+ recommended to process expressions without considering this.
283
+ :py:meth:`~lambda_eval` is a more secure alternative.
284
+
285
+ :py:mod:`~PIL.ImageMath` only supports single-layer images. To process multi-band
286
+ images, use the :py:meth:`~PIL.Image.Image.split` method or
287
+ :py:func:`~PIL.Image.merge` function.
288
+
289
+ :param expression: A string containing a Python-style expression.
290
+ :param options: Values to add to the evaluation context. You
291
+ can either use a dictionary, or one or more keyword
292
+ arguments.
293
+ :return: The evaluated expression. This is usually an image object, but can
294
+ also be an integer, a floating point value, or a pixel tuple,
295
+ depending on the expression.
296
+ """
297
+
298
+ # build execution namespace
299
+ args: dict[str, Any] = ops.copy()
300
+ for k in list(options.keys()) + list(kw.keys()):
301
+ if "__" in k or hasattr(builtins, k):
302
+ msg = f"'{k}' not allowed"
303
+ raise ValueError(msg)
304
+
305
+ args.update(options)
306
+ args.update(kw)
307
+ for k, v in args.items():
308
+ if hasattr(v, "im"):
309
+ args[k] = _Operand(v)
310
+
311
+ compiled_code = compile(expression, "<string>", "eval")
312
+
313
+ def scan(code: CodeType) -> None:
314
+ for const in code.co_consts:
315
+ if type(const) is type(compiled_code):
316
+ scan(const)
317
+
318
+ for name in code.co_names:
319
+ if name not in args and name != "abs":
320
+ msg = f"'{name}' not allowed"
321
+ raise ValueError(msg)
322
+
323
+ scan(compiled_code)
324
+ out = builtins.eval(expression, {"__builtins": {"abs": abs}}, args)
325
+ try:
326
+ return out.im
327
+ except AttributeError:
328
+ return out
329
+
330
+
331
+ def eval(
332
+ expression: str,
333
+ _dict: dict[str, Any] = {},
334
+ **kw: Any,
335
+ ) -> Any:
336
+ """
337
+ Evaluates an image expression.
338
+
339
+ Deprecated. Use lambda_eval() or unsafe_eval() instead.
340
+
341
+ :param expression: A string containing a Python-style expression.
342
+ :param _dict: Values to add to the evaluation context. You
343
+ can either use a dictionary, or one or more keyword
344
+ arguments.
345
+ :return: The evaluated expression. This is usually an image object, but can
346
+ also be an integer, a floating point value, or a pixel tuple,
347
+ depending on the expression.
348
+
349
+ .. deprecated:: 10.3.0
350
+ """
351
+
352
+ deprecate(
353
+ "ImageMath.eval",
354
+ 12,
355
+ "ImageMath.lambda_eval or ImageMath.unsafe_eval",
356
+ )
357
+ return unsafe_eval(expression, _dict, **kw)
.venv/Lib/site-packages/PIL/ImageMode.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # standard mode descriptors
6
+ #
7
+ # History:
8
+ # 2006-03-20 fl Added
9
+ #
10
+ # Copyright (c) 2006 by Secret Labs AB.
11
+ # Copyright (c) 2006 by Fredrik Lundh.
12
+ #
13
+ # See the README file for information on usage and redistribution.
14
+ #
15
+ from __future__ import annotations
16
+
17
+ import sys
18
+ from functools import lru_cache
19
+
20
+
21
+ class ModeDescriptor:
22
+ """Wrapper for mode strings."""
23
+
24
+ def __init__(
25
+ self,
26
+ mode: str,
27
+ bands: tuple[str, ...],
28
+ basemode: str,
29
+ basetype: str,
30
+ typestr: str,
31
+ ) -> None:
32
+ self.mode = mode
33
+ self.bands = bands
34
+ self.basemode = basemode
35
+ self.basetype = basetype
36
+ self.typestr = typestr
37
+
38
+ def __str__(self) -> str:
39
+ return self.mode
40
+
41
+
42
+ @lru_cache
43
+ def getmode(mode: str) -> ModeDescriptor:
44
+ """Gets a mode descriptor for the given mode."""
45
+ # initialize mode cache
46
+ endian = "<" if sys.byteorder == "little" else ">"
47
+
48
+ modes = {
49
+ # core modes
50
+ # Bits need to be extended to bytes
51
+ "1": ("L", "L", ("1",), "|b1"),
52
+ "L": ("L", "L", ("L",), "|u1"),
53
+ "I": ("L", "I", ("I",), endian + "i4"),
54
+ "F": ("L", "F", ("F",), endian + "f4"),
55
+ "P": ("P", "L", ("P",), "|u1"),
56
+ "RGB": ("RGB", "L", ("R", "G", "B"), "|u1"),
57
+ "RGBX": ("RGB", "L", ("R", "G", "B", "X"), "|u1"),
58
+ "RGBA": ("RGB", "L", ("R", "G", "B", "A"), "|u1"),
59
+ "CMYK": ("RGB", "L", ("C", "M", "Y", "K"), "|u1"),
60
+ "YCbCr": ("RGB", "L", ("Y", "Cb", "Cr"), "|u1"),
61
+ # UNDONE - unsigned |u1i1i1
62
+ "LAB": ("RGB", "L", ("L", "A", "B"), "|u1"),
63
+ "HSV": ("RGB", "L", ("H", "S", "V"), "|u1"),
64
+ # extra experimental modes
65
+ "RGBa": ("RGB", "L", ("R", "G", "B", "a"), "|u1"),
66
+ "BGR;15": ("RGB", "L", ("B", "G", "R"), "|u1"),
67
+ "BGR;16": ("RGB", "L", ("B", "G", "R"), "|u1"),
68
+ "BGR;24": ("RGB", "L", ("B", "G", "R"), "|u1"),
69
+ "LA": ("L", "L", ("L", "A"), "|u1"),
70
+ "La": ("L", "L", ("L", "a"), "|u1"),
71
+ "PA": ("RGB", "L", ("P", "A"), "|u1"),
72
+ }
73
+ if mode in modes:
74
+ base_mode, base_type, bands, type_str = modes[mode]
75
+ return ModeDescriptor(mode, bands, base_mode, base_type, type_str)
76
+
77
+ mapping_modes = {
78
+ # I;16 == I;16L, and I;32 == I;32L
79
+ "I;16": "<u2",
80
+ "I;16S": "<i2",
81
+ "I;16L": "<u2",
82
+ "I;16LS": "<i2",
83
+ "I;16B": ">u2",
84
+ "I;16BS": ">i2",
85
+ "I;16N": endian + "u2",
86
+ "I;16NS": endian + "i2",
87
+ "I;32": "<u4",
88
+ "I;32B": ">u4",
89
+ "I;32L": "<u4",
90
+ "I;32S": "<i4",
91
+ "I;32BS": ">i4",
92
+ "I;32LS": "<i4",
93
+ }
94
+
95
+ type_str = mapping_modes[mode]
96
+ return ModeDescriptor(mode, ("I",), "L", "L", type_str)
.venv/Lib/site-packages/PIL/ImageMorph.py ADDED
@@ -0,0 +1,265 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # A binary morphology add-on for the Python Imaging Library
2
+ #
3
+ # History:
4
+ # 2014-06-04 Initial version.
5
+ #
6
+ # Copyright (c) 2014 Dov Grobgeld <dov.grobgeld@gmail.com>
7
+ from __future__ import annotations
8
+
9
+ import re
10
+
11
+ from . import Image, _imagingmorph
12
+
13
+ LUT_SIZE = 1 << 9
14
+
15
+ # fmt: off
16
+ ROTATION_MATRIX = [
17
+ 6, 3, 0,
18
+ 7, 4, 1,
19
+ 8, 5, 2,
20
+ ]
21
+ MIRROR_MATRIX = [
22
+ 2, 1, 0,
23
+ 5, 4, 3,
24
+ 8, 7, 6,
25
+ ]
26
+ # fmt: on
27
+
28
+
29
+ class LutBuilder:
30
+ """A class for building a MorphLut from a descriptive language
31
+
32
+ The input patterns is a list of a strings sequences like these::
33
+
34
+ 4:(...
35
+ .1.
36
+ 111)->1
37
+
38
+ (whitespaces including linebreaks are ignored). The option 4
39
+ describes a series of symmetry operations (in this case a
40
+ 4-rotation), the pattern is described by:
41
+
42
+ - . or X - Ignore
43
+ - 1 - Pixel is on
44
+ - 0 - Pixel is off
45
+
46
+ The result of the operation is described after "->" string.
47
+
48
+ The default is to return the current pixel value, which is
49
+ returned if no other match is found.
50
+
51
+ Operations:
52
+
53
+ - 4 - 4 way rotation
54
+ - N - Negate
55
+ - 1 - Dummy op for no other operation (an op must always be given)
56
+ - M - Mirroring
57
+
58
+ Example::
59
+
60
+ lb = LutBuilder(patterns = ["4:(... .1. 111)->1"])
61
+ lut = lb.build_lut()
62
+
63
+ """
64
+
65
+ def __init__(
66
+ self, patterns: list[str] | None = None, op_name: str | None = None
67
+ ) -> None:
68
+ if patterns is not None:
69
+ self.patterns = patterns
70
+ else:
71
+ self.patterns = []
72
+ self.lut: bytearray | None = None
73
+ if op_name is not None:
74
+ known_patterns = {
75
+ "corner": ["1:(... ... ...)->0", "4:(00. 01. ...)->1"],
76
+ "dilation4": ["4:(... .0. .1.)->1"],
77
+ "dilation8": ["4:(... .0. .1.)->1", "4:(... .0. ..1)->1"],
78
+ "erosion4": ["4:(... .1. .0.)->0"],
79
+ "erosion8": ["4:(... .1. .0.)->0", "4:(... .1. ..0)->0"],
80
+ "edge": [
81
+ "1:(... ... ...)->0",
82
+ "4:(.0. .1. ...)->1",
83
+ "4:(01. .1. ...)->1",
84
+ ],
85
+ }
86
+ if op_name not in known_patterns:
87
+ msg = "Unknown pattern " + op_name + "!"
88
+ raise Exception(msg)
89
+
90
+ self.patterns = known_patterns[op_name]
91
+
92
+ def add_patterns(self, patterns: list[str]) -> None:
93
+ self.patterns += patterns
94
+
95
+ def build_default_lut(self) -> None:
96
+ symbols = [0, 1]
97
+ m = 1 << 4 # pos of current pixel
98
+ self.lut = bytearray(symbols[(i & m) > 0] for i in range(LUT_SIZE))
99
+
100
+ def get_lut(self) -> bytearray | None:
101
+ return self.lut
102
+
103
+ def _string_permute(self, pattern: str, permutation: list[int]) -> str:
104
+ """string_permute takes a pattern and a permutation and returns the
105
+ string permuted according to the permutation list.
106
+ """
107
+ assert len(permutation) == 9
108
+ return "".join(pattern[p] for p in permutation)
109
+
110
+ def _pattern_permute(
111
+ self, basic_pattern: str, options: str, basic_result: int
112
+ ) -> list[tuple[str, int]]:
113
+ """pattern_permute takes a basic pattern and its result and clones
114
+ the pattern according to the modifications described in the $options
115
+ parameter. It returns a list of all cloned patterns."""
116
+ patterns = [(basic_pattern, basic_result)]
117
+
118
+ # rotations
119
+ if "4" in options:
120
+ res = patterns[-1][1]
121
+ for i in range(4):
122
+ patterns.append(
123
+ (self._string_permute(patterns[-1][0], ROTATION_MATRIX), res)
124
+ )
125
+ # mirror
126
+ if "M" in options:
127
+ n = len(patterns)
128
+ for pattern, res in patterns[:n]:
129
+ patterns.append((self._string_permute(pattern, MIRROR_MATRIX), res))
130
+
131
+ # negate
132
+ if "N" in options:
133
+ n = len(patterns)
134
+ for pattern, res in patterns[:n]:
135
+ # Swap 0 and 1
136
+ pattern = pattern.replace("0", "Z").replace("1", "0").replace("Z", "1")
137
+ res = 1 - int(res)
138
+ patterns.append((pattern, res))
139
+
140
+ return patterns
141
+
142
+ def build_lut(self) -> bytearray:
143
+ """Compile all patterns into a morphology lut.
144
+
145
+ TBD :Build based on (file) morphlut:modify_lut
146
+ """
147
+ self.build_default_lut()
148
+ assert self.lut is not None
149
+ patterns = []
150
+
151
+ # Parse and create symmetries of the patterns strings
152
+ for p in self.patterns:
153
+ m = re.search(r"(\w*):?\s*\((.+?)\)\s*->\s*(\d)", p.replace("\n", ""))
154
+ if not m:
155
+ msg = 'Syntax error in pattern "' + p + '"'
156
+ raise Exception(msg)
157
+ options = m.group(1)
158
+ pattern = m.group(2)
159
+ result = int(m.group(3))
160
+
161
+ # Get rid of spaces
162
+ pattern = pattern.replace(" ", "").replace("\n", "")
163
+
164
+ patterns += self._pattern_permute(pattern, options, result)
165
+
166
+ # compile the patterns into regular expressions for speed
167
+ compiled_patterns = []
168
+ for pattern in patterns:
169
+ p = pattern[0].replace(".", "X").replace("X", "[01]")
170
+ compiled_patterns.append((re.compile(p), pattern[1]))
171
+
172
+ # Step through table and find patterns that match.
173
+ # Note that all the patterns are searched. The last one
174
+ # caught overrides
175
+ for i in range(LUT_SIZE):
176
+ # Build the bit pattern
177
+ bitpattern = bin(i)[2:]
178
+ bitpattern = ("0" * (9 - len(bitpattern)) + bitpattern)[::-1]
179
+
180
+ for pattern, r in compiled_patterns:
181
+ if pattern.match(bitpattern):
182
+ self.lut[i] = [0, 1][r]
183
+
184
+ return self.lut
185
+
186
+
187
+ class MorphOp:
188
+ """A class for binary morphological operators"""
189
+
190
+ def __init__(
191
+ self,
192
+ lut: bytearray | None = None,
193
+ op_name: str | None = None,
194
+ patterns: list[str] | None = None,
195
+ ) -> None:
196
+ """Create a binary morphological operator"""
197
+ self.lut = lut
198
+ if op_name is not None:
199
+ self.lut = LutBuilder(op_name=op_name).build_lut()
200
+ elif patterns is not None:
201
+ self.lut = LutBuilder(patterns=patterns).build_lut()
202
+
203
+ def apply(self, image: Image.Image):
204
+ """Run a single morphological operation on an image
205
+
206
+ Returns a tuple of the number of changed pixels and the
207
+ morphed image"""
208
+ if self.lut is None:
209
+ msg = "No operator loaded"
210
+ raise Exception(msg)
211
+
212
+ if image.mode != "L":
213
+ msg = "Image mode must be L"
214
+ raise ValueError(msg)
215
+ outimage = Image.new(image.mode, image.size, None)
216
+ count = _imagingmorph.apply(bytes(self.lut), image.im.id, outimage.im.id)
217
+ return count, outimage
218
+
219
+ def match(self, image: Image.Image):
220
+ """Get a list of coordinates matching the morphological operation on
221
+ an image.
222
+
223
+ Returns a list of tuples of (x,y) coordinates
224
+ of all matching pixels. See :ref:`coordinate-system`."""
225
+ if self.lut is None:
226
+ msg = "No operator loaded"
227
+ raise Exception(msg)
228
+
229
+ if image.mode != "L":
230
+ msg = "Image mode must be L"
231
+ raise ValueError(msg)
232
+ return _imagingmorph.match(bytes(self.lut), image.im.id)
233
+
234
+ def get_on_pixels(self, image: Image.Image):
235
+ """Get a list of all turned on pixels in a binary image
236
+
237
+ Returns a list of tuples of (x,y) coordinates
238
+ of all matching pixels. See :ref:`coordinate-system`."""
239
+
240
+ if image.mode != "L":
241
+ msg = "Image mode must be L"
242
+ raise ValueError(msg)
243
+ return _imagingmorph.get_on_pixels(image.im.id)
244
+
245
+ def load_lut(self, filename: str) -> None:
246
+ """Load an operator from an mrl file"""
247
+ with open(filename, "rb") as f:
248
+ self.lut = bytearray(f.read())
249
+
250
+ if len(self.lut) != LUT_SIZE:
251
+ self.lut = None
252
+ msg = "Wrong size operator file!"
253
+ raise Exception(msg)
254
+
255
+ def save_lut(self, filename: str) -> None:
256
+ """Save an operator to an mrl file"""
257
+ if self.lut is None:
258
+ msg = "No operator loaded"
259
+ raise Exception(msg)
260
+ with open(filename, "wb") as f:
261
+ f.write(self.lut)
262
+
263
+ def set_lut(self, lut: bytearray | None) -> None:
264
+ """Set the lut from an external source"""
265
+ self.lut = lut
.venv/Lib/site-packages/PIL/ImageOps.py ADDED
@@ -0,0 +1,724 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # standard image operations
6
+ #
7
+ # History:
8
+ # 2001-10-20 fl Created
9
+ # 2001-10-23 fl Added autocontrast operator
10
+ # 2001-12-18 fl Added Kevin's fit operator
11
+ # 2004-03-14 fl Fixed potential division by zero in equalize
12
+ # 2005-05-05 fl Fixed equalize for low number of values
13
+ #
14
+ # Copyright (c) 2001-2004 by Secret Labs AB
15
+ # Copyright (c) 2001-2004 by Fredrik Lundh
16
+ #
17
+ # See the README file for information on usage and redistribution.
18
+ #
19
+ from __future__ import annotations
20
+
21
+ import functools
22
+ import operator
23
+ import re
24
+ from typing import Protocol, Sequence, cast
25
+
26
+ from . import ExifTags, Image, ImagePalette
27
+
28
+ #
29
+ # helpers
30
+
31
+
32
+ def _border(border: int | tuple[int, ...]) -> tuple[int, int, int, int]:
33
+ if isinstance(border, tuple):
34
+ if len(border) == 2:
35
+ left, top = right, bottom = border
36
+ elif len(border) == 4:
37
+ left, top, right, bottom = border
38
+ else:
39
+ left = top = right = bottom = border
40
+ return left, top, right, bottom
41
+
42
+
43
+ def _color(color: str | int | tuple[int, ...], mode: str) -> int | tuple[int, ...]:
44
+ if isinstance(color, str):
45
+ from . import ImageColor
46
+
47
+ color = ImageColor.getcolor(color, mode)
48
+ return color
49
+
50
+
51
+ def _lut(image: Image.Image, lut: list[int]) -> Image.Image:
52
+ if image.mode == "P":
53
+ # FIXME: apply to lookup table, not image data
54
+ msg = "mode P support coming soon"
55
+ raise NotImplementedError(msg)
56
+ elif image.mode in ("L", "RGB"):
57
+ if image.mode == "RGB" and len(lut) == 256:
58
+ lut = lut + lut + lut
59
+ return image.point(lut)
60
+ else:
61
+ msg = f"not supported for mode {image.mode}"
62
+ raise OSError(msg)
63
+
64
+
65
+ #
66
+ # actions
67
+
68
+
69
+ def autocontrast(
70
+ image: Image.Image,
71
+ cutoff: float | tuple[float, float] = 0,
72
+ ignore: int | Sequence[int] | None = None,
73
+ mask: Image.Image | None = None,
74
+ preserve_tone: bool = False,
75
+ ) -> Image.Image:
76
+ """
77
+ Maximize (normalize) image contrast. This function calculates a
78
+ histogram of the input image (or mask region), removes ``cutoff`` percent of the
79
+ lightest and darkest pixels from the histogram, and remaps the image
80
+ so that the darkest pixel becomes black (0), and the lightest
81
+ becomes white (255).
82
+
83
+ :param image: The image to process.
84
+ :param cutoff: The percent to cut off from the histogram on the low and
85
+ high ends. Either a tuple of (low, high), or a single
86
+ number for both.
87
+ :param ignore: The background pixel value (use None for no background).
88
+ :param mask: Histogram used in contrast operation is computed using pixels
89
+ within the mask. If no mask is given the entire image is used
90
+ for histogram computation.
91
+ :param preserve_tone: Preserve image tone in Photoshop-like style autocontrast.
92
+
93
+ .. versionadded:: 8.2.0
94
+
95
+ :return: An image.
96
+ """
97
+ if preserve_tone:
98
+ histogram = image.convert("L").histogram(mask)
99
+ else:
100
+ histogram = image.histogram(mask)
101
+
102
+ lut = []
103
+ for layer in range(0, len(histogram), 256):
104
+ h = histogram[layer : layer + 256]
105
+ if ignore is not None:
106
+ # get rid of outliers
107
+ if isinstance(ignore, int):
108
+ h[ignore] = 0
109
+ else:
110
+ for ix in ignore:
111
+ h[ix] = 0
112
+ if cutoff:
113
+ # cut off pixels from both ends of the histogram
114
+ if not isinstance(cutoff, tuple):
115
+ cutoff = (cutoff, cutoff)
116
+ # get number of pixels
117
+ n = 0
118
+ for ix in range(256):
119
+ n = n + h[ix]
120
+ # remove cutoff% pixels from the low end
121
+ cut = int(n * cutoff[0] // 100)
122
+ for lo in range(256):
123
+ if cut > h[lo]:
124
+ cut = cut - h[lo]
125
+ h[lo] = 0
126
+ else:
127
+ h[lo] -= cut
128
+ cut = 0
129
+ if cut <= 0:
130
+ break
131
+ # remove cutoff% samples from the high end
132
+ cut = int(n * cutoff[1] // 100)
133
+ for hi in range(255, -1, -1):
134
+ if cut > h[hi]:
135
+ cut = cut - h[hi]
136
+ h[hi] = 0
137
+ else:
138
+ h[hi] -= cut
139
+ cut = 0
140
+ if cut <= 0:
141
+ break
142
+ # find lowest/highest samples after preprocessing
143
+ for lo in range(256):
144
+ if h[lo]:
145
+ break
146
+ for hi in range(255, -1, -1):
147
+ if h[hi]:
148
+ break
149
+ if hi <= lo:
150
+ # don't bother
151
+ lut.extend(list(range(256)))
152
+ else:
153
+ scale = 255.0 / (hi - lo)
154
+ offset = -lo * scale
155
+ for ix in range(256):
156
+ ix = int(ix * scale + offset)
157
+ if ix < 0:
158
+ ix = 0
159
+ elif ix > 255:
160
+ ix = 255
161
+ lut.append(ix)
162
+ return _lut(image, lut)
163
+
164
+
165
+ def colorize(
166
+ image: Image.Image,
167
+ black: str | tuple[int, ...],
168
+ white: str | tuple[int, ...],
169
+ mid: str | int | tuple[int, ...] | None = None,
170
+ blackpoint: int = 0,
171
+ whitepoint: int = 255,
172
+ midpoint: int = 127,
173
+ ) -> Image.Image:
174
+ """
175
+ Colorize grayscale image.
176
+ This function calculates a color wedge which maps all black pixels in
177
+ the source image to the first color and all white pixels to the
178
+ second color. If ``mid`` is specified, it uses three-color mapping.
179
+ The ``black`` and ``white`` arguments should be RGB tuples or color names;
180
+ optionally you can use three-color mapping by also specifying ``mid``.
181
+ Mapping positions for any of the colors can be specified
182
+ (e.g. ``blackpoint``), where these parameters are the integer
183
+ value corresponding to where the corresponding color should be mapped.
184
+ These parameters must have logical order, such that
185
+ ``blackpoint <= midpoint <= whitepoint`` (if ``mid`` is specified).
186
+
187
+ :param image: The image to colorize.
188
+ :param black: The color to use for black input pixels.
189
+ :param white: The color to use for white input pixels.
190
+ :param mid: The color to use for midtone input pixels.
191
+ :param blackpoint: an int value [0, 255] for the black mapping.
192
+ :param whitepoint: an int value [0, 255] for the white mapping.
193
+ :param midpoint: an int value [0, 255] for the midtone mapping.
194
+ :return: An image.
195
+ """
196
+
197
+ # Initial asserts
198
+ assert image.mode == "L"
199
+ if mid is None:
200
+ assert 0 <= blackpoint <= whitepoint <= 255
201
+ else:
202
+ assert 0 <= blackpoint <= midpoint <= whitepoint <= 255
203
+
204
+ # Define colors from arguments
205
+ rgb_black = cast(Sequence[int], _color(black, "RGB"))
206
+ rgb_white = cast(Sequence[int], _color(white, "RGB"))
207
+ rgb_mid = cast(Sequence[int], _color(mid, "RGB")) if mid is not None else None
208
+
209
+ # Empty lists for the mapping
210
+ red = []
211
+ green = []
212
+ blue = []
213
+
214
+ # Create the low-end values
215
+ for i in range(0, blackpoint):
216
+ red.append(rgb_black[0])
217
+ green.append(rgb_black[1])
218
+ blue.append(rgb_black[2])
219
+
220
+ # Create the mapping (2-color)
221
+ if rgb_mid is None:
222
+ range_map = range(0, whitepoint - blackpoint)
223
+
224
+ for i in range_map:
225
+ red.append(
226
+ rgb_black[0] + i * (rgb_white[0] - rgb_black[0]) // len(range_map)
227
+ )
228
+ green.append(
229
+ rgb_black[1] + i * (rgb_white[1] - rgb_black[1]) // len(range_map)
230
+ )
231
+ blue.append(
232
+ rgb_black[2] + i * (rgb_white[2] - rgb_black[2]) // len(range_map)
233
+ )
234
+
235
+ # Create the mapping (3-color)
236
+ else:
237
+ range_map1 = range(0, midpoint - blackpoint)
238
+ range_map2 = range(0, whitepoint - midpoint)
239
+
240
+ for i in range_map1:
241
+ red.append(
242
+ rgb_black[0] + i * (rgb_mid[0] - rgb_black[0]) // len(range_map1)
243
+ )
244
+ green.append(
245
+ rgb_black[1] + i * (rgb_mid[1] - rgb_black[1]) // len(range_map1)
246
+ )
247
+ blue.append(
248
+ rgb_black[2] + i * (rgb_mid[2] - rgb_black[2]) // len(range_map1)
249
+ )
250
+ for i in range_map2:
251
+ red.append(rgb_mid[0] + i * (rgb_white[0] - rgb_mid[0]) // len(range_map2))
252
+ green.append(
253
+ rgb_mid[1] + i * (rgb_white[1] - rgb_mid[1]) // len(range_map2)
254
+ )
255
+ blue.append(rgb_mid[2] + i * (rgb_white[2] - rgb_mid[2]) // len(range_map2))
256
+
257
+ # Create the high-end values
258
+ for i in range(0, 256 - whitepoint):
259
+ red.append(rgb_white[0])
260
+ green.append(rgb_white[1])
261
+ blue.append(rgb_white[2])
262
+
263
+ # Return converted image
264
+ image = image.convert("RGB")
265
+ return _lut(image, red + green + blue)
266
+
267
+
268
+ def contain(
269
+ image: Image.Image, size: tuple[int, int], method: int = Image.Resampling.BICUBIC
270
+ ) -> Image.Image:
271
+ """
272
+ Returns a resized version of the image, set to the maximum width and height
273
+ within the requested size, while maintaining the original aspect ratio.
274
+
275
+ :param image: The image to resize.
276
+ :param size: The requested output size in pixels, given as a
277
+ (width, height) tuple.
278
+ :param method: Resampling method to use. Default is
279
+ :py:attr:`~PIL.Image.Resampling.BICUBIC`.
280
+ See :ref:`concept-filters`.
281
+ :return: An image.
282
+ """
283
+
284
+ im_ratio = image.width / image.height
285
+ dest_ratio = size[0] / size[1]
286
+
287
+ if im_ratio != dest_ratio:
288
+ if im_ratio > dest_ratio:
289
+ new_height = round(image.height / image.width * size[0])
290
+ if new_height != size[1]:
291
+ size = (size[0], new_height)
292
+ else:
293
+ new_width = round(image.width / image.height * size[1])
294
+ if new_width != size[0]:
295
+ size = (new_width, size[1])
296
+ return image.resize(size, resample=method)
297
+
298
+
299
+ def cover(
300
+ image: Image.Image, size: tuple[int, int], method: int = Image.Resampling.BICUBIC
301
+ ) -> Image.Image:
302
+ """
303
+ Returns a resized version of the image, so that the requested size is
304
+ covered, while maintaining the original aspect ratio.
305
+
306
+ :param image: The image to resize.
307
+ :param size: The requested output size in pixels, given as a
308
+ (width, height) tuple.
309
+ :param method: Resampling method to use. Default is
310
+ :py:attr:`~PIL.Image.Resampling.BICUBIC`.
311
+ See :ref:`concept-filters`.
312
+ :return: An image.
313
+ """
314
+
315
+ im_ratio = image.width / image.height
316
+ dest_ratio = size[0] / size[1]
317
+
318
+ if im_ratio != dest_ratio:
319
+ if im_ratio < dest_ratio:
320
+ new_height = round(image.height / image.width * size[0])
321
+ if new_height != size[1]:
322
+ size = (size[0], new_height)
323
+ else:
324
+ new_width = round(image.width / image.height * size[1])
325
+ if new_width != size[0]:
326
+ size = (new_width, size[1])
327
+ return image.resize(size, resample=method)
328
+
329
+
330
+ def pad(
331
+ image: Image.Image,
332
+ size: tuple[int, int],
333
+ method: int = Image.Resampling.BICUBIC,
334
+ color: str | int | tuple[int, ...] | None = None,
335
+ centering: tuple[float, float] = (0.5, 0.5),
336
+ ) -> Image.Image:
337
+ """
338
+ Returns a resized and padded version of the image, expanded to fill the
339
+ requested aspect ratio and size.
340
+
341
+ :param image: The image to resize and crop.
342
+ :param size: The requested output size in pixels, given as a
343
+ (width, height) tuple.
344
+ :param method: Resampling method to use. Default is
345
+ :py:attr:`~PIL.Image.Resampling.BICUBIC`.
346
+ See :ref:`concept-filters`.
347
+ :param color: The background color of the padded image.
348
+ :param centering: Control the position of the original image within the
349
+ padded version.
350
+
351
+ (0.5, 0.5) will keep the image centered
352
+ (0, 0) will keep the image aligned to the top left
353
+ (1, 1) will keep the image aligned to the bottom
354
+ right
355
+ :return: An image.
356
+ """
357
+
358
+ resized = contain(image, size, method)
359
+ if resized.size == size:
360
+ out = resized
361
+ else:
362
+ out = Image.new(image.mode, size, color)
363
+ if resized.palette:
364
+ out.putpalette(resized.getpalette())
365
+ if resized.width != size[0]:
366
+ x = round((size[0] - resized.width) * max(0, min(centering[0], 1)))
367
+ out.paste(resized, (x, 0))
368
+ else:
369
+ y = round((size[1] - resized.height) * max(0, min(centering[1], 1)))
370
+ out.paste(resized, (0, y))
371
+ return out
372
+
373
+
374
+ def crop(image: Image.Image, border: int = 0) -> Image.Image:
375
+ """
376
+ Remove border from image. The same amount of pixels are removed
377
+ from all four sides. This function works on all image modes.
378
+
379
+ .. seealso:: :py:meth:`~PIL.Image.Image.crop`
380
+
381
+ :param image: The image to crop.
382
+ :param border: The number of pixels to remove.
383
+ :return: An image.
384
+ """
385
+ left, top, right, bottom = _border(border)
386
+ return image.crop((left, top, image.size[0] - right, image.size[1] - bottom))
387
+
388
+
389
+ def scale(
390
+ image: Image.Image, factor: float, resample: int = Image.Resampling.BICUBIC
391
+ ) -> Image.Image:
392
+ """
393
+ Returns a rescaled image by a specific factor given in parameter.
394
+ A factor greater than 1 expands the image, between 0 and 1 contracts the
395
+ image.
396
+
397
+ :param image: The image to rescale.
398
+ :param factor: The expansion factor, as a float.
399
+ :param resample: Resampling method to use. Default is
400
+ :py:attr:`~PIL.Image.Resampling.BICUBIC`.
401
+ See :ref:`concept-filters`.
402
+ :returns: An :py:class:`~PIL.Image.Image` object.
403
+ """
404
+ if factor == 1:
405
+ return image.copy()
406
+ elif factor <= 0:
407
+ msg = "the factor must be greater than 0"
408
+ raise ValueError(msg)
409
+ else:
410
+ size = (round(factor * image.width), round(factor * image.height))
411
+ return image.resize(size, resample)
412
+
413
+
414
+ class SupportsGetMesh(Protocol):
415
+ """
416
+ An object that supports the ``getmesh`` method, taking an image as an
417
+ argument, and returning a list of tuples. Each tuple contains two tuples,
418
+ the source box as a tuple of 4 integers, and a tuple of 8 integers for the
419
+ final quadrilateral, in order of top left, bottom left, bottom right, top
420
+ right.
421
+ """
422
+
423
+ def getmesh(
424
+ self, image: Image.Image
425
+ ) -> list[
426
+ tuple[tuple[int, int, int, int], tuple[int, int, int, int, int, int, int, int]]
427
+ ]: ...
428
+
429
+
430
+ def deform(
431
+ image: Image.Image,
432
+ deformer: SupportsGetMesh,
433
+ resample: int = Image.Resampling.BILINEAR,
434
+ ) -> Image.Image:
435
+ """
436
+ Deform the image.
437
+
438
+ :param image: The image to deform.
439
+ :param deformer: A deformer object. Any object that implements a
440
+ ``getmesh`` method can be used.
441
+ :param resample: An optional resampling filter. Same values possible as
442
+ in the PIL.Image.transform function.
443
+ :return: An image.
444
+ """
445
+ return image.transform(
446
+ image.size, Image.Transform.MESH, deformer.getmesh(image), resample
447
+ )
448
+
449
+
450
+ def equalize(image: Image.Image, mask: Image.Image | None = None) -> Image.Image:
451
+ """
452
+ Equalize the image histogram. This function applies a non-linear
453
+ mapping to the input image, in order to create a uniform
454
+ distribution of grayscale values in the output image.
455
+
456
+ :param image: The image to equalize.
457
+ :param mask: An optional mask. If given, only the pixels selected by
458
+ the mask are included in the analysis.
459
+ :return: An image.
460
+ """
461
+ if image.mode == "P":
462
+ image = image.convert("RGB")
463
+ h = image.histogram(mask)
464
+ lut = []
465
+ for b in range(0, len(h), 256):
466
+ histo = [_f for _f in h[b : b + 256] if _f]
467
+ if len(histo) <= 1:
468
+ lut.extend(list(range(256)))
469
+ else:
470
+ step = (functools.reduce(operator.add, histo) - histo[-1]) // 255
471
+ if not step:
472
+ lut.extend(list(range(256)))
473
+ else:
474
+ n = step // 2
475
+ for i in range(256):
476
+ lut.append(n // step)
477
+ n = n + h[i + b]
478
+ return _lut(image, lut)
479
+
480
+
481
+ def expand(
482
+ image: Image.Image,
483
+ border: int | tuple[int, ...] = 0,
484
+ fill: str | int | tuple[int, ...] = 0,
485
+ ) -> Image.Image:
486
+ """
487
+ Add border to the image
488
+
489
+ :param image: The image to expand.
490
+ :param border: Border width, in pixels.
491
+ :param fill: Pixel fill value (a color value). Default is 0 (black).
492
+ :return: An image.
493
+ """
494
+ left, top, right, bottom = _border(border)
495
+ width = left + image.size[0] + right
496
+ height = top + image.size[1] + bottom
497
+ color = _color(fill, image.mode)
498
+ if image.palette:
499
+ palette = ImagePalette.ImagePalette(palette=image.getpalette())
500
+ if isinstance(color, tuple):
501
+ color = palette.getcolor(color)
502
+ else:
503
+ palette = None
504
+ out = Image.new(image.mode, (width, height), color)
505
+ if palette:
506
+ out.putpalette(palette.palette)
507
+ out.paste(image, (left, top))
508
+ return out
509
+
510
+
511
+ def fit(
512
+ image: Image.Image,
513
+ size: tuple[int, int],
514
+ method: int = Image.Resampling.BICUBIC,
515
+ bleed: float = 0.0,
516
+ centering: tuple[float, float] = (0.5, 0.5),
517
+ ) -> Image.Image:
518
+ """
519
+ Returns a resized and cropped version of the image, cropped to the
520
+ requested aspect ratio and size.
521
+
522
+ This function was contributed by Kevin Cazabon.
523
+
524
+ :param image: The image to resize and crop.
525
+ :param size: The requested output size in pixels, given as a
526
+ (width, height) tuple.
527
+ :param method: Resampling method to use. Default is
528
+ :py:attr:`~PIL.Image.Resampling.BICUBIC`.
529
+ See :ref:`concept-filters`.
530
+ :param bleed: Remove a border around the outside of the image from all
531
+ four edges. The value is a decimal percentage (use 0.01 for
532
+ one percent). The default value is 0 (no border).
533
+ Cannot be greater than or equal to 0.5.
534
+ :param centering: Control the cropping position. Use (0.5, 0.5) for
535
+ center cropping (e.g. if cropping the width, take 50% off
536
+ of the left side, and therefore 50% off the right side).
537
+ (0.0, 0.0) will crop from the top left corner (i.e. if
538
+ cropping the width, take all of the crop off of the right
539
+ side, and if cropping the height, take all of it off the
540
+ bottom). (1.0, 0.0) will crop from the bottom left
541
+ corner, etc. (i.e. if cropping the width, take all of the
542
+ crop off the left side, and if cropping the height take
543
+ none from the top, and therefore all off the bottom).
544
+ :return: An image.
545
+ """
546
+
547
+ # by Kevin Cazabon, Feb 17/2000
548
+ # kevin@cazabon.com
549
+ # https://www.cazabon.com
550
+
551
+ centering_x, centering_y = centering
552
+
553
+ if not 0.0 <= centering_x <= 1.0:
554
+ centering_x = 0.5
555
+ if not 0.0 <= centering_y <= 1.0:
556
+ centering_y = 0.5
557
+
558
+ if not 0.0 <= bleed < 0.5:
559
+ bleed = 0.0
560
+
561
+ # calculate the area to use for resizing and cropping, subtracting
562
+ # the 'bleed' around the edges
563
+
564
+ # number of pixels to trim off on Top and Bottom, Left and Right
565
+ bleed_pixels = (bleed * image.size[0], bleed * image.size[1])
566
+
567
+ live_size = (
568
+ image.size[0] - bleed_pixels[0] * 2,
569
+ image.size[1] - bleed_pixels[1] * 2,
570
+ )
571
+
572
+ # calculate the aspect ratio of the live_size
573
+ live_size_ratio = live_size[0] / live_size[1]
574
+
575
+ # calculate the aspect ratio of the output image
576
+ output_ratio = size[0] / size[1]
577
+
578
+ # figure out if the sides or top/bottom will be cropped off
579
+ if live_size_ratio == output_ratio:
580
+ # live_size is already the needed ratio
581
+ crop_width = live_size[0]
582
+ crop_height = live_size[1]
583
+ elif live_size_ratio >= output_ratio:
584
+ # live_size is wider than what's needed, crop the sides
585
+ crop_width = output_ratio * live_size[1]
586
+ crop_height = live_size[1]
587
+ else:
588
+ # live_size is taller than what's needed, crop the top and bottom
589
+ crop_width = live_size[0]
590
+ crop_height = live_size[0] / output_ratio
591
+
592
+ # make the crop
593
+ crop_left = bleed_pixels[0] + (live_size[0] - crop_width) * centering_x
594
+ crop_top = bleed_pixels[1] + (live_size[1] - crop_height) * centering_y
595
+
596
+ crop = (crop_left, crop_top, crop_left + crop_width, crop_top + crop_height)
597
+
598
+ # resize the image and return it
599
+ return image.resize(size, method, box=crop)
600
+
601
+
602
+ def flip(image: Image.Image) -> Image.Image:
603
+ """
604
+ Flip the image vertically (top to bottom).
605
+
606
+ :param image: The image to flip.
607
+ :return: An image.
608
+ """
609
+ return image.transpose(Image.Transpose.FLIP_TOP_BOTTOM)
610
+
611
+
612
+ def grayscale(image: Image.Image) -> Image.Image:
613
+ """
614
+ Convert the image to grayscale.
615
+
616
+ :param image: The image to convert.
617
+ :return: An image.
618
+ """
619
+ return image.convert("L")
620
+
621
+
622
+ def invert(image: Image.Image) -> Image.Image:
623
+ """
624
+ Invert (negate) the image.
625
+
626
+ :param image: The image to invert.
627
+ :return: An image.
628
+ """
629
+ lut = list(range(255, -1, -1))
630
+ return image.point(lut) if image.mode == "1" else _lut(image, lut)
631
+
632
+
633
+ def mirror(image: Image.Image) -> Image.Image:
634
+ """
635
+ Flip image horizontally (left to right).
636
+
637
+ :param image: The image to mirror.
638
+ :return: An image.
639
+ """
640
+ return image.transpose(Image.Transpose.FLIP_LEFT_RIGHT)
641
+
642
+
643
+ def posterize(image: Image.Image, bits: int) -> Image.Image:
644
+ """
645
+ Reduce the number of bits for each color channel.
646
+
647
+ :param image: The image to posterize.
648
+ :param bits: The number of bits to keep for each channel (1-8).
649
+ :return: An image.
650
+ """
651
+ mask = ~(2 ** (8 - bits) - 1)
652
+ lut = [i & mask for i in range(256)]
653
+ return _lut(image, lut)
654
+
655
+
656
+ def solarize(image: Image.Image, threshold: int = 128) -> Image.Image:
657
+ """
658
+ Invert all pixel values above a threshold.
659
+
660
+ :param image: The image to solarize.
661
+ :param threshold: All pixels above this grayscale level are inverted.
662
+ :return: An image.
663
+ """
664
+ lut = []
665
+ for i in range(256):
666
+ if i < threshold:
667
+ lut.append(i)
668
+ else:
669
+ lut.append(255 - i)
670
+ return _lut(image, lut)
671
+
672
+
673
+ def exif_transpose(image: Image.Image, *, in_place: bool = False) -> Image.Image | None:
674
+ """
675
+ If an image has an EXIF Orientation tag, other than 1, transpose the image
676
+ accordingly, and remove the orientation data.
677
+
678
+ :param image: The image to transpose.
679
+ :param in_place: Boolean. Keyword-only argument.
680
+ If ``True``, the original image is modified in-place, and ``None`` is returned.
681
+ If ``False`` (default), a new :py:class:`~PIL.Image.Image` object is returned
682
+ with the transposition applied. If there is no transposition, a copy of the
683
+ image will be returned.
684
+ """
685
+ image.load()
686
+ image_exif = image.getexif()
687
+ orientation = image_exif.get(ExifTags.Base.Orientation, 1)
688
+ method = {
689
+ 2: Image.Transpose.FLIP_LEFT_RIGHT,
690
+ 3: Image.Transpose.ROTATE_180,
691
+ 4: Image.Transpose.FLIP_TOP_BOTTOM,
692
+ 5: Image.Transpose.TRANSPOSE,
693
+ 6: Image.Transpose.ROTATE_270,
694
+ 7: Image.Transpose.TRANSVERSE,
695
+ 8: Image.Transpose.ROTATE_90,
696
+ }.get(orientation)
697
+ if method is not None:
698
+ transposed_image = image.transpose(method)
699
+ if in_place:
700
+ image.im = transposed_image.im
701
+ image.pyaccess = None
702
+ image._size = transposed_image._size
703
+ exif_image = image if in_place else transposed_image
704
+
705
+ exif = exif_image.getexif()
706
+ if ExifTags.Base.Orientation in exif:
707
+ del exif[ExifTags.Base.Orientation]
708
+ if "exif" in exif_image.info:
709
+ exif_image.info["exif"] = exif.tobytes()
710
+ elif "Raw profile type exif" in exif_image.info:
711
+ exif_image.info["Raw profile type exif"] = exif.tobytes().hex()
712
+ elif "XML:com.adobe.xmp" in exif_image.info:
713
+ for pattern in (
714
+ r'tiff:Orientation="([0-9])"',
715
+ r"<tiff:Orientation>([0-9])</tiff:Orientation>",
716
+ ):
717
+ exif_image.info["XML:com.adobe.xmp"] = re.sub(
718
+ pattern, "", exif_image.info["XML:com.adobe.xmp"]
719
+ )
720
+ if not in_place:
721
+ return transposed_image
722
+ elif not in_place:
723
+ return image.copy()
724
+ return None
.venv/Lib/site-packages/PIL/ImagePalette.py ADDED
@@ -0,0 +1,263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # image palette object
6
+ #
7
+ # History:
8
+ # 1996-03-11 fl Rewritten.
9
+ # 1997-01-03 fl Up and running.
10
+ # 1997-08-23 fl Added load hack
11
+ # 2001-04-16 fl Fixed randint shadow bug in random()
12
+ #
13
+ # Copyright (c) 1997-2001 by Secret Labs AB
14
+ # Copyright (c) 1996-1997 by Fredrik Lundh
15
+ #
16
+ # See the README file for information on usage and redistribution.
17
+ #
18
+ from __future__ import annotations
19
+
20
+ import array
21
+ from typing import Sequence
22
+
23
+ from . import GimpGradientFile, GimpPaletteFile, ImageColor, PaletteFile
24
+
25
+
26
+ class ImagePalette:
27
+ """
28
+ Color palette for palette mapped images
29
+
30
+ :param mode: The mode to use for the palette. See:
31
+ :ref:`concept-modes`. Defaults to "RGB"
32
+ :param palette: An optional palette. If given, it must be a bytearray,
33
+ an array or a list of ints between 0-255. The list must consist of
34
+ all channels for one color followed by the next color (e.g. RGBRGBRGB).
35
+ Defaults to an empty palette.
36
+ """
37
+
38
+ def __init__(self, mode: str = "RGB", palette: Sequence[int] | None = None) -> None:
39
+ self.mode = mode
40
+ self.rawmode = None # if set, palette contains raw data
41
+ self.palette = palette or bytearray()
42
+ self.dirty: int | None = None
43
+
44
+ @property
45
+ def palette(self):
46
+ return self._palette
47
+
48
+ @palette.setter
49
+ def palette(self, palette):
50
+ self._colors = None
51
+ self._palette = palette
52
+
53
+ @property
54
+ def colors(self):
55
+ if self._colors is None:
56
+ mode_len = len(self.mode)
57
+ self._colors = {}
58
+ for i in range(0, len(self.palette), mode_len):
59
+ color = tuple(self.palette[i : i + mode_len])
60
+ if color in self._colors:
61
+ continue
62
+ self._colors[color] = i // mode_len
63
+ return self._colors
64
+
65
+ @colors.setter
66
+ def colors(self, colors):
67
+ self._colors = colors
68
+
69
+ def copy(self):
70
+ new = ImagePalette()
71
+
72
+ new.mode = self.mode
73
+ new.rawmode = self.rawmode
74
+ if self.palette is not None:
75
+ new.palette = self.palette[:]
76
+ new.dirty = self.dirty
77
+
78
+ return new
79
+
80
+ def getdata(self):
81
+ """
82
+ Get palette contents in format suitable for the low-level
83
+ ``im.putpalette`` primitive.
84
+
85
+ .. warning:: This method is experimental.
86
+ """
87
+ if self.rawmode:
88
+ return self.rawmode, self.palette
89
+ return self.mode, self.tobytes()
90
+
91
+ def tobytes(self):
92
+ """Convert palette to bytes.
93
+
94
+ .. warning:: This method is experimental.
95
+ """
96
+ if self.rawmode:
97
+ msg = "palette contains raw palette data"
98
+ raise ValueError(msg)
99
+ if isinstance(self.palette, bytes):
100
+ return self.palette
101
+ arr = array.array("B", self.palette)
102
+ return arr.tobytes()
103
+
104
+ # Declare tostring as an alias for tobytes
105
+ tostring = tobytes
106
+
107
+ def _new_color_index(self, image=None, e=None):
108
+ if not isinstance(self.palette, bytearray):
109
+ self._palette = bytearray(self.palette)
110
+ index = len(self.palette) // 3
111
+ special_colors = ()
112
+ if image:
113
+ special_colors = (
114
+ image.info.get("background"),
115
+ image.info.get("transparency"),
116
+ )
117
+ while index in special_colors:
118
+ index += 1
119
+ if index >= 256:
120
+ if image:
121
+ # Search for an unused index
122
+ for i, count in reversed(list(enumerate(image.histogram()))):
123
+ if count == 0 and i not in special_colors:
124
+ index = i
125
+ break
126
+ if index >= 256:
127
+ msg = "cannot allocate more than 256 colors"
128
+ raise ValueError(msg) from e
129
+ return index
130
+
131
+ def getcolor(self, color, image=None) -> int:
132
+ """Given an rgb tuple, allocate palette entry.
133
+
134
+ .. warning:: This method is experimental.
135
+ """
136
+ if self.rawmode:
137
+ msg = "palette contains raw palette data"
138
+ raise ValueError(msg)
139
+ if isinstance(color, tuple):
140
+ if self.mode == "RGB":
141
+ if len(color) == 4:
142
+ if color[3] != 255:
143
+ msg = "cannot add non-opaque RGBA color to RGB palette"
144
+ raise ValueError(msg)
145
+ color = color[:3]
146
+ elif self.mode == "RGBA":
147
+ if len(color) == 3:
148
+ color += (255,)
149
+ try:
150
+ return self.colors[color]
151
+ except KeyError as e:
152
+ # allocate new color slot
153
+ index = self._new_color_index(image, e)
154
+ self.colors[color] = index
155
+ if index * 3 < len(self.palette):
156
+ self._palette = (
157
+ self.palette[: index * 3]
158
+ + bytes(color)
159
+ + self.palette[index * 3 + 3 :]
160
+ )
161
+ else:
162
+ self._palette += bytes(color)
163
+ self.dirty = 1
164
+ return index
165
+ else:
166
+ msg = f"unknown color specifier: {repr(color)}"
167
+ raise ValueError(msg)
168
+
169
+ def save(self, fp):
170
+ """Save palette to text file.
171
+
172
+ .. warning:: This method is experimental.
173
+ """
174
+ if self.rawmode:
175
+ msg = "palette contains raw palette data"
176
+ raise ValueError(msg)
177
+ if isinstance(fp, str):
178
+ fp = open(fp, "w")
179
+ fp.write("# Palette\n")
180
+ fp.write(f"# Mode: {self.mode}\n")
181
+ for i in range(256):
182
+ fp.write(f"{i}")
183
+ for j in range(i * len(self.mode), (i + 1) * len(self.mode)):
184
+ try:
185
+ fp.write(f" {self.palette[j]}")
186
+ except IndexError:
187
+ fp.write(" 0")
188
+ fp.write("\n")
189
+ fp.close()
190
+
191
+
192
+ # --------------------------------------------------------------------
193
+ # Internal
194
+
195
+
196
+ def raw(rawmode, data) -> ImagePalette:
197
+ palette = ImagePalette()
198
+ palette.rawmode = rawmode
199
+ palette.palette = data
200
+ palette.dirty = 1
201
+ return palette
202
+
203
+
204
+ # --------------------------------------------------------------------
205
+ # Factories
206
+
207
+
208
+ def make_linear_lut(black, white):
209
+ if black == 0:
210
+ return [white * i // 255 for i in range(256)]
211
+
212
+ msg = "unavailable when black is non-zero"
213
+ raise NotImplementedError(msg) # FIXME
214
+
215
+
216
+ def make_gamma_lut(exp):
217
+ return [int(((i / 255.0) ** exp) * 255.0 + 0.5) for i in range(256)]
218
+
219
+
220
+ def negative(mode="RGB"):
221
+ palette = list(range(256 * len(mode)))
222
+ palette.reverse()
223
+ return ImagePalette(mode, [i // len(mode) for i in palette])
224
+
225
+
226
+ def random(mode="RGB"):
227
+ from random import randint
228
+
229
+ palette = [randint(0, 255) for _ in range(256 * len(mode))]
230
+ return ImagePalette(mode, palette)
231
+
232
+
233
+ def sepia(white="#fff0c0"):
234
+ bands = [make_linear_lut(0, band) for band in ImageColor.getrgb(white)]
235
+ return ImagePalette("RGB", [bands[i % 3][i // 3] for i in range(256 * 3)])
236
+
237
+
238
+ def wedge(mode="RGB"):
239
+ palette = list(range(256 * len(mode)))
240
+ return ImagePalette(mode, [i // len(mode) for i in palette])
241
+
242
+
243
+ def load(filename):
244
+ # FIXME: supports GIMP gradients only
245
+
246
+ with open(filename, "rb") as fp:
247
+ for paletteHandler in [
248
+ GimpPaletteFile.GimpPaletteFile,
249
+ GimpGradientFile.GimpGradientFile,
250
+ PaletteFile.PaletteFile,
251
+ ]:
252
+ try:
253
+ fp.seek(0)
254
+ lut = paletteHandler(fp).getpalette()
255
+ if lut:
256
+ break
257
+ except (SyntaxError, ValueError):
258
+ pass
259
+ else:
260
+ msg = "cannot load palette"
261
+ raise OSError(msg)
262
+
263
+ return lut # data, rawmode
.venv/Lib/site-packages/PIL/ImagePath.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library
3
+ # $Id$
4
+ #
5
+ # path interface
6
+ #
7
+ # History:
8
+ # 1996-11-04 fl Created
9
+ # 2002-04-14 fl Added documentation stub class
10
+ #
11
+ # Copyright (c) Secret Labs AB 1997.
12
+ # Copyright (c) Fredrik Lundh 1996.
13
+ #
14
+ # See the README file for information on usage and redistribution.
15
+ #
16
+ from __future__ import annotations
17
+
18
+ from . import Image
19
+
20
+ Path = Image.core.path