mj064 commited on
Commit
21d8a45
·
verified ·
1 Parent(s): acfa14b

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. .gitattributes +189 -0
  2. .kombai/resources/lofi-wireframe-20260409_174154_575770-option-1.html +372 -0
  3. .kombai/resources/lofi-wireframe-20260409_174154_575770-option-2.html +307 -0
  4. .kombai/resources/lofi-wireframe-20260409_174154_575770-option-3.html +358 -0
  5. .pytest_cache/.gitignore +2 -0
  6. .pytest_cache/CACHEDIR.TAG +4 -0
  7. .pytest_cache/README.md +8 -0
  8. .pytest_cache/v/cache/lastfailed +1 -0
  9. .pytest_cache/v/cache/nodeids +6 -0
  10. .venv/.gitignore +1 -0
  11. .venv/Lib/site-packages/3c22db458360489351e4__mypyc.cp312-win_amd64.pyd +3 -0
  12. .venv/Lib/site-packages/81d243bd2c585b0f4821__mypyc.cp312-win_amd64.pyd +3 -0
  13. .venv/Lib/site-packages/PIL/AvifImagePlugin.py +293 -0
  14. .venv/Lib/site-packages/PIL/BdfFontFile.py +123 -0
  15. .venv/Lib/site-packages/PIL/BlpImagePlugin.py +498 -0
  16. .venv/Lib/site-packages/PIL/BmpImagePlugin.py +514 -0
  17. .venv/Lib/site-packages/PIL/BufrStubImagePlugin.py +72 -0
  18. .venv/Lib/site-packages/PIL/ContainerIO.py +173 -0
  19. .venv/Lib/site-packages/PIL/CurImagePlugin.py +75 -0
  20. .venv/Lib/site-packages/PIL/DcxImagePlugin.py +84 -0
  21. .venv/Lib/site-packages/PIL/DdsImagePlugin.py +625 -0
  22. .venv/Lib/site-packages/PIL/EpsImagePlugin.py +481 -0
  23. .venv/Lib/site-packages/PIL/ExifTags.py +384 -0
  24. .venv/Lib/site-packages/PIL/FitsImagePlugin.py +153 -0
  25. .venv/Lib/site-packages/PIL/FliImagePlugin.py +184 -0
  26. .venv/Lib/site-packages/PIL/FontFile.py +159 -0
  27. .venv/Lib/site-packages/PIL/FpxImagePlugin.py +258 -0
  28. .venv/Lib/site-packages/PIL/FtexImagePlugin.py +115 -0
  29. .venv/Lib/site-packages/PIL/GbrImagePlugin.py +103 -0
  30. .venv/Lib/site-packages/PIL/GdImageFile.py +103 -0
  31. .venv/Lib/site-packages/PIL/GifImagePlugin.py +1223 -0
  32. .venv/Lib/site-packages/PIL/GimpGradientFile.py +154 -0
  33. .venv/Lib/site-packages/PIL/GimpPaletteFile.py +75 -0
  34. .venv/Lib/site-packages/PIL/GribStubImagePlugin.py +72 -0
  35. .venv/Lib/site-packages/PIL/Hdf5StubImagePlugin.py +72 -0
  36. .venv/Lib/site-packages/PIL/IcnsImagePlugin.py +401 -0
  37. .venv/Lib/site-packages/PIL/IcoImagePlugin.py +396 -0
  38. .venv/Lib/site-packages/PIL/ImImagePlugin.py +390 -0
  39. .venv/Lib/site-packages/PIL/Image.py +0 -0
  40. .venv/Lib/site-packages/PIL/ImageChops.py +311 -0
  41. .venv/Lib/site-packages/PIL/ImageCms.py +1076 -0
  42. .venv/Lib/site-packages/PIL/ImageColor.py +320 -0
  43. .venv/Lib/site-packages/PIL/ImageDraw.py +1035 -0
  44. .venv/Lib/site-packages/PIL/ImageDraw2.py +244 -0
  45. .venv/Lib/site-packages/PIL/ImageEnhance.py +113 -0
  46. .venv/Lib/site-packages/PIL/ImageFile.py +935 -0
  47. .venv/Lib/site-packages/PIL/ImageFilter.py +607 -0
  48. .venv/Lib/site-packages/PIL/ImageFont.py +1309 -0
  49. .venv/Lib/site-packages/PIL/ImageGrab.py +231 -0
  50. .venv/Lib/site-packages/PIL/ImageMath.py +314 -0
.gitattributes ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .venv/Lib/site-packages/3c22db458360489351e4__mypyc.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
2
+ .venv/Lib/site-packages/81d243bd2c585b0f4821__mypyc.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
3
+ .venv/Lib/site-packages/_brotli.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
4
+ .venv/Lib/site-packages/_cffi_backend.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
5
+ .venv/Lib/site-packages/aiohttp/_http_parser.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
6
+ .venv/Lib/site-packages/aiohttp/_websocket/reader_c.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
7
+ .venv/Lib/site-packages/cryptography/hazmat/bindings/_rust.pyd filter=lfs diff=lfs merge=lfs -text
8
+ .venv/Lib/site-packages/dateutil/zoneinfo/dateutil-zoneinfo.tar.gz filter=lfs diff=lfs merge=lfs -text
9
+ .venv/Lib/site-packages/gradio/media_assets/audio/cantina.wav filter=lfs diff=lfs merge=lfs -text
10
+ .venv/Lib/site-packages/gradio/media_assets/audio/recording1.wav filter=lfs diff=lfs merge=lfs -text
11
+ .venv/Lib/site-packages/gradio/media_assets/audio/sax.wav filter=lfs diff=lfs merge=lfs -text
12
+ .venv/Lib/site-packages/gradio/media_assets/images/groot.jpeg filter=lfs diff=lfs merge=lfs -text
13
+ .venv/Lib/site-packages/gradio/media_assets/images/tower.jpg filter=lfs diff=lfs merge=lfs -text
14
+ .venv/Lib/site-packages/gradio/media_assets/models3d/Duck.glb filter=lfs diff=lfs merge=lfs -text
15
+ .venv/Lib/site-packages/gradio/media_assets/models3d/sofia.stl filter=lfs diff=lfs merge=lfs -text
16
+ .venv/Lib/site-packages/gradio/media_assets/videos/a.mp4 filter=lfs diff=lfs merge=lfs -text
17
+ .venv/Lib/site-packages/gradio/media_assets/videos/b.mp4 filter=lfs diff=lfs merge=lfs -text
18
+ .venv/Lib/site-packages/gradio/media_assets/videos/world.mp4 filter=lfs diff=lfs merge=lfs -text
19
+ .venv/Lib/site-packages/gradio/templates/frontend/static/fonts/Source[[:space:]]Sans[[:space:]]Pro/SourceSansPro-Bold.woff2 filter=lfs diff=lfs merge=lfs -text
20
+ .venv/Lib/site-packages/gradio/templates/frontend/static/fonts/Source[[:space:]]Sans[[:space:]]Pro/SourceSansPro-Regular.woff2 filter=lfs diff=lfs merge=lfs -text
21
+ .venv/Lib/site-packages/gradio/templates/node/build/client/_app/immutable/chunks/5J0xJHOV.js.br filter=lfs diff=lfs merge=lfs -text
22
+ .venv/Lib/site-packages/gradio/templates/node/build/client/_app/immutable/chunks/Bav8QHfD.js.br filter=lfs diff=lfs merge=lfs -text
23
+ .venv/Lib/site-packages/gradio/templates/node/build/client/_app/immutable/chunks/C7SxAlTc.js.br filter=lfs diff=lfs merge=lfs -text
24
+ .venv/Lib/site-packages/gradio/templates/node/build/client/_app/immutable/chunks/CLj6IfqE.js.br filter=lfs diff=lfs merge=lfs -text
25
+ .venv/Lib/site-packages/gradio/templates/node/build/client/_app/immutable/chunks/Co9o20xq.js.br filter=lfs diff=lfs merge=lfs -text
26
+ .venv/Lib/site-packages/gradio/templates/node/build/client/_app/immutable/chunks/Crx4SQdK.js.br filter=lfs diff=lfs merge=lfs -text
27
+ .venv/Lib/site-packages/gradio/templates/node/build/client/_app/immutable/chunks/D0XGvtj7.js.br filter=lfs diff=lfs merge=lfs -text
28
+ .venv/Lib/site-packages/gradio/templates/node/build/client/_app/immutable/chunks/DHbIDdPW.js.br filter=lfs diff=lfs merge=lfs -text
29
+ .venv/Lib/site-packages/gradio/templates/node/build/client/_app/immutable/chunks/DmAaxH5s.js.br filter=lfs diff=lfs merge=lfs -text
30
+ .venv/Lib/site-packages/gradio/templates/node/build/client/_app/immutable/chunks/x-0WiWxh.js.br filter=lfs diff=lfs merge=lfs -text
31
+ .venv/Lib/site-packages/hf_xet/hf_xet.pyd filter=lfs diff=lfs merge=lfs -text
32
+ .venv/Lib/site-packages/jiter/jiter.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
33
+ .venv/Lib/site-packages/numpy/_core/_multiarray_umath.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
34
+ .venv/Lib/site-packages/numpy/_core/_simd.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
35
+ .venv/Lib/site-packages/numpy/_core/lib/npymath.lib filter=lfs diff=lfs merge=lfs -text
36
+ .venv/Lib/site-packages/numpy/fft/_pocketfft_umath.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
37
+ .venv/Lib/site-packages/numpy/linalg/_umath_linalg.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
38
+ .venv/Lib/site-packages/numpy/random/_bounded_integers.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
39
+ .venv/Lib/site-packages/numpy/random/_common.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
40
+ .venv/Lib/site-packages/numpy/random/_generator.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
41
+ .venv/Lib/site-packages/numpy/random/bit_generator.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
42
+ .venv/Lib/site-packages/numpy/random/lib/npyrandom.lib filter=lfs diff=lfs merge=lfs -text
43
+ .venv/Lib/site-packages/numpy/random/mtrand.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
44
+ .venv/Lib/site-packages/numpy.libs/libscipy_openblas64_-63c857e738469261263c764a36be9436.dll filter=lfs diff=lfs merge=lfs -text
45
+ .venv/Lib/site-packages/numpy.libs/msvcp140-a4c2229bdc2a2a630acdc095b4d86008.dll filter=lfs diff=lfs merge=lfs -text
46
+ .venv/Lib/site-packages/orjson/orjson.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
47
+ .venv/Lib/site-packages/pandas/_libs/_cyutility.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
48
+ .venv/Lib/site-packages/pandas/_libs/algos.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
49
+ .venv/Lib/site-packages/pandas/_libs/groupby.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
50
+ .venv/Lib/site-packages/pandas/_libs/hashtable.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
51
+ .venv/Lib/site-packages/pandas/_libs/index.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
52
+ .venv/Lib/site-packages/pandas/_libs/internals.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
53
+ .venv/Lib/site-packages/pandas/_libs/interval.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
54
+ .venv/Lib/site-packages/pandas/_libs/join.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
55
+ .venv/Lib/site-packages/pandas/_libs/lib.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
56
+ .venv/Lib/site-packages/pandas/_libs/missing.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
57
+ .venv/Lib/site-packages/pandas/_libs/parsers.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
58
+ .venv/Lib/site-packages/pandas/_libs/reshape.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
59
+ .venv/Lib/site-packages/pandas/_libs/sparse.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
60
+ .venv/Lib/site-packages/pandas/_libs/tslib.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
61
+ .venv/Lib/site-packages/pandas/_libs/tslibs/conversion.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
62
+ .venv/Lib/site-packages/pandas/_libs/tslibs/dtypes.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
63
+ .venv/Lib/site-packages/pandas/_libs/tslibs/fields.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
64
+ .venv/Lib/site-packages/pandas/_libs/tslibs/nattype.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
65
+ .venv/Lib/site-packages/pandas/_libs/tslibs/offsets.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
66
+ .venv/Lib/site-packages/pandas/_libs/tslibs/parsing.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
67
+ .venv/Lib/site-packages/pandas/_libs/tslibs/period.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
68
+ .venv/Lib/site-packages/pandas/_libs/tslibs/strptime.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
69
+ .venv/Lib/site-packages/pandas/_libs/tslibs/timedeltas.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
70
+ .venv/Lib/site-packages/pandas/_libs/tslibs/timestamps.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
71
+ .venv/Lib/site-packages/pandas/_libs/tslibs/tzconversion.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
72
+ .venv/Lib/site-packages/pandas/_libs/window/aggregations.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
73
+ .venv/Lib/site-packages/pandas/_libs/window/indexers.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
74
+ .venv/Lib/site-packages/pandas.libs/msvcp140-a4c2229bdc2a2a630acdc095b4d86008.dll filter=lfs diff=lfs merge=lfs -text
75
+ .venv/Lib/site-packages/PIL/_avif.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
76
+ .venv/Lib/site-packages/PIL/_imaging.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
77
+ .venv/Lib/site-packages/PIL/_imagingcms.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
78
+ .venv/Lib/site-packages/PIL/_imagingft.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
79
+ .venv/Lib/site-packages/PIL/_webp.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
80
+ .venv/Lib/site-packages/pip/_vendor/distlib/t64-arm.exe filter=lfs diff=lfs merge=lfs -text
81
+ .venv/Lib/site-packages/pip/_vendor/distlib/t64.exe filter=lfs diff=lfs merge=lfs -text
82
+ .venv/Lib/site-packages/pip/_vendor/distlib/w64-arm.exe filter=lfs diff=lfs merge=lfs -text
83
+ .venv/Lib/site-packages/pip/_vendor/distlib/w64.exe filter=lfs diff=lfs merge=lfs -text
84
+ .venv/Lib/site-packages/pyarrow/_acero.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
85
+ .venv/Lib/site-packages/pyarrow/_compute.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
86
+ .venv/Lib/site-packages/pyarrow/_csv.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
87
+ .venv/Lib/site-packages/pyarrow/_dataset.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
88
+ .venv/Lib/site-packages/pyarrow/_dataset_parquet.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
89
+ .venv/Lib/site-packages/pyarrow/_flight.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
90
+ .venv/Lib/site-packages/pyarrow/_fs.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
91
+ .venv/Lib/site-packages/pyarrow/_orc.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
92
+ .venv/Lib/site-packages/pyarrow/_parquet.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
93
+ .venv/Lib/site-packages/pyarrow/_parquet_encryption.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
94
+ .venv/Lib/site-packages/pyarrow/_s3fs.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
95
+ .venv/Lib/site-packages/pyarrow/_substrait.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
96
+ .venv/Lib/site-packages/pyarrow/arrow.dll filter=lfs diff=lfs merge=lfs -text
97
+ .venv/Lib/site-packages/pyarrow/arrow.lib filter=lfs diff=lfs merge=lfs -text
98
+ .venv/Lib/site-packages/pyarrow/arrow_acero.dll filter=lfs diff=lfs merge=lfs -text
99
+ .venv/Lib/site-packages/pyarrow/arrow_acero.lib filter=lfs diff=lfs merge=lfs -text
100
+ .venv/Lib/site-packages/pyarrow/arrow_compute.dll filter=lfs diff=lfs merge=lfs -text
101
+ .venv/Lib/site-packages/pyarrow/arrow_compute.lib filter=lfs diff=lfs merge=lfs -text
102
+ .venv/Lib/site-packages/pyarrow/arrow_dataset.dll filter=lfs diff=lfs merge=lfs -text
103
+ .venv/Lib/site-packages/pyarrow/arrow_dataset.lib filter=lfs diff=lfs merge=lfs -text
104
+ .venv/Lib/site-packages/pyarrow/arrow_flight.dll filter=lfs diff=lfs merge=lfs -text
105
+ .venv/Lib/site-packages/pyarrow/arrow_flight.lib filter=lfs diff=lfs merge=lfs -text
106
+ .venv/Lib/site-packages/pyarrow/arrow_python.dll filter=lfs diff=lfs merge=lfs -text
107
+ .venv/Lib/site-packages/pyarrow/arrow_python.lib filter=lfs diff=lfs merge=lfs -text
108
+ .venv/Lib/site-packages/pyarrow/arrow_substrait.dll filter=lfs diff=lfs merge=lfs -text
109
+ .venv/Lib/site-packages/pyarrow/arrow_substrait.lib filter=lfs diff=lfs merge=lfs -text
110
+ .venv/Lib/site-packages/pyarrow/lib.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
111
+ .venv/Lib/site-packages/pyarrow/parquet.dll filter=lfs diff=lfs merge=lfs -text
112
+ .venv/Lib/site-packages/pyarrow/parquet.lib filter=lfs diff=lfs merge=lfs -text
113
+ .venv/Lib/site-packages/pyarrow/tests/data/orc/TestOrcFile.testDate1900.jsn.gz filter=lfs diff=lfs merge=lfs -text
114
+ .venv/Lib/site-packages/pyarrow.libs/msvcp140-2a7008da6f9aae43c7a434835dcaf31e.dll filter=lfs diff=lfs merge=lfs -text
115
+ .venv/Lib/site-packages/pydantic_core/_pydantic_core.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
116
+ .venv/Lib/site-packages/pythonwin/mfc140u.dll filter=lfs diff=lfs merge=lfs -text
117
+ .venv/Lib/site-packages/pythonwin/scintilla.dll filter=lfs diff=lfs merge=lfs -text
118
+ .venv/Lib/site-packages/pythonwin/win32ui.pyd filter=lfs diff=lfs merge=lfs -text
119
+ .venv/Lib/site-packages/PyWin32.chm filter=lfs diff=lfs merge=lfs -text
120
+ .venv/Lib/site-packages/pywin32_system32/pythoncom312.dll filter=lfs diff=lfs merge=lfs -text
121
+ .venv/Lib/site-packages/pywin32_system32/pywintypes312.dll filter=lfs diff=lfs merge=lfs -text
122
+ .venv/Lib/site-packages/rpds/rpds.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
123
+ .venv/Lib/site-packages/watchfiles/_rust_notify.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
124
+ .venv/Lib/site-packages/win32/libs/pywintypes.lib filter=lfs diff=lfs merge=lfs -text
125
+ .venv/Lib/site-packages/win32/win32api.pyd filter=lfs diff=lfs merge=lfs -text
126
+ .venv/Lib/site-packages/win32/win32crypt.pyd filter=lfs diff=lfs merge=lfs -text
127
+ .venv/Lib/site-packages/win32/win32file.pyd filter=lfs diff=lfs merge=lfs -text
128
+ .venv/Lib/site-packages/win32/win32gui.pyd filter=lfs diff=lfs merge=lfs -text
129
+ .venv/Lib/site-packages/win32/win32security.pyd filter=lfs diff=lfs merge=lfs -text
130
+ .venv/Lib/site-packages/win32com/libs/pythoncom.lib filter=lfs diff=lfs merge=lfs -text
131
+ .venv/Lib/site-packages/win32comext/adsi/adsi.pyd filter=lfs diff=lfs merge=lfs -text
132
+ .venv/Lib/site-packages/win32comext/axcontrol/axcontrol.pyd filter=lfs diff=lfs merge=lfs -text
133
+ .venv/Lib/site-packages/win32comext/mapi/exchange.pyd filter=lfs diff=lfs merge=lfs -text
134
+ .venv/Lib/site-packages/win32comext/mapi/mapi.pyd filter=lfs diff=lfs merge=lfs -text
135
+ .venv/Lib/site-packages/win32comext/propsys/propsys.pyd filter=lfs diff=lfs merge=lfs -text
136
+ .venv/Lib/site-packages/win32comext/shell/shell.pyd filter=lfs diff=lfs merge=lfs -text
137
+ .venv/Lib/site-packages/yaml/_yaml.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
138
+ .venv/Scripts/content-guard-env.exe filter=lfs diff=lfs merge=lfs -text
139
+ .venv/Scripts/cyclopts.exe filter=lfs diff=lfs merge=lfs -text
140
+ .venv/Scripts/datasets-cli.exe filter=lfs diff=lfs merge=lfs -text
141
+ .venv/Scripts/distro.exe filter=lfs diff=lfs merge=lfs -text
142
+ .venv/Scripts/docutils.exe filter=lfs diff=lfs merge=lfs -text
143
+ .venv/Scripts/dotenv.exe filter=lfs diff=lfs merge=lfs -text
144
+ .venv/Scripts/email_validator.exe filter=lfs diff=lfs merge=lfs -text
145
+ .venv/Scripts/f2py.exe filter=lfs diff=lfs merge=lfs -text
146
+ .venv/Scripts/fastapi.exe filter=lfs diff=lfs merge=lfs -text
147
+ .venv/Scripts/fastmcp.exe filter=lfs diff=lfs merge=lfs -text
148
+ .venv/Scripts/gradio.exe filter=lfs diff=lfs merge=lfs -text
149
+ .venv/Scripts/hf-gradio.exe filter=lfs diff=lfs merge=lfs -text
150
+ .venv/Scripts/hf.exe filter=lfs diff=lfs merge=lfs -text
151
+ .venv/Scripts/httpx.exe filter=lfs diff=lfs merge=lfs -text
152
+ .venv/Scripts/huggingface-cli.exe filter=lfs diff=lfs merge=lfs -text
153
+ .venv/Scripts/jsonschema.exe filter=lfs diff=lfs merge=lfs -text
154
+ .venv/Scripts/keyring.exe filter=lfs diff=lfs merge=lfs -text
155
+ .venv/Scripts/markdown-it.exe filter=lfs diff=lfs merge=lfs -text
156
+ .venv/Scripts/mcp.exe filter=lfs diff=lfs merge=lfs -text
157
+ .venv/Scripts/normalizer.exe filter=lfs diff=lfs merge=lfs -text
158
+ .venv/Scripts/numpy-config.exe filter=lfs diff=lfs merge=lfs -text
159
+ .venv/Scripts/openai.exe filter=lfs diff=lfs merge=lfs -text
160
+ .venv/Scripts/openenv.exe filter=lfs diff=lfs merge=lfs -text
161
+ .venv/Scripts/pip.exe filter=lfs diff=lfs merge=lfs -text
162
+ .venv/Scripts/pip3.12.exe filter=lfs diff=lfs merge=lfs -text
163
+ .venv/Scripts/pip3.exe filter=lfs diff=lfs merge=lfs -text
164
+ .venv/Scripts/py.test.exe filter=lfs diff=lfs merge=lfs -text
165
+ .venv/Scripts/pygmentize.exe filter=lfs diff=lfs merge=lfs -text
166
+ .venv/Scripts/pytest.exe filter=lfs diff=lfs merge=lfs -text
167
+ .venv/Scripts/python.exe filter=lfs diff=lfs merge=lfs -text
168
+ .venv/Scripts/pythonw.exe filter=lfs diff=lfs merge=lfs -text
169
+ .venv/Scripts/pywin32_postinstall.exe filter=lfs diff=lfs merge=lfs -text
170
+ .venv/Scripts/pywin32_testall.exe filter=lfs diff=lfs merge=lfs -text
171
+ .venv/Scripts/rst2html.exe filter=lfs diff=lfs merge=lfs -text
172
+ .venv/Scripts/rst2html4.exe filter=lfs diff=lfs merge=lfs -text
173
+ .venv/Scripts/rst2html5.exe filter=lfs diff=lfs merge=lfs -text
174
+ .venv/Scripts/rst2latex.exe filter=lfs diff=lfs merge=lfs -text
175
+ .venv/Scripts/rst2man.exe filter=lfs diff=lfs merge=lfs -text
176
+ .venv/Scripts/rst2odt.exe filter=lfs diff=lfs merge=lfs -text
177
+ .venv/Scripts/rst2pseudoxml.exe filter=lfs diff=lfs merge=lfs -text
178
+ .venv/Scripts/rst2s5.exe filter=lfs diff=lfs merge=lfs -text
179
+ .venv/Scripts/rst2xetex.exe filter=lfs diff=lfs merge=lfs -text
180
+ .venv/Scripts/rst2xml.exe filter=lfs diff=lfs merge=lfs -text
181
+ .venv/Scripts/server.exe filter=lfs diff=lfs merge=lfs -text
182
+ .venv/Scripts/tiny-agents.exe filter=lfs diff=lfs merge=lfs -text
183
+ .venv/Scripts/tqdm.exe filter=lfs diff=lfs merge=lfs -text
184
+ .venv/Scripts/typer.exe filter=lfs diff=lfs merge=lfs -text
185
+ .venv/Scripts/upload_theme.exe filter=lfs diff=lfs merge=lfs -text
186
+ .venv/Scripts/uvicorn.exe filter=lfs diff=lfs merge=lfs -text
187
+ .venv/Scripts/watchfiles.exe filter=lfs diff=lfs merge=lfs -text
188
+ .venv/Scripts/websockets.exe filter=lfs diff=lfs merge=lfs -text
189
+ server/static/hero_bg.png filter=lfs diff=lfs merge=lfs -text
.kombai/resources/lofi-wireframe-20260409_174154_575770-option-1.html ADDED
@@ -0,0 +1,372 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Option 1: Sidebar Navigation — Conservative Layout</title>
7
+ <style>
8
+ * { box-sizing: border-box; margin: 0; padding: 0; }
9
+ body { font-family: 'Comic Sans MS', 'Marker Felt', cursive; background: #fff; color: #333; padding: 20px; }
10
+ h1 { font-size: 22px; margin-bottom: 6px; }
11
+ h2 { font-size: 16px; margin-bottom: 10px; color: #666; }
12
+ h3 { font-size: 14px; margin-bottom: 8px; }
13
+ h4 { font-size: 12px; color: #666; margin-bottom: 6px; text-transform: uppercase; letter-spacing: 1px; }
14
+ p, span, label { font-size: 13px; }
15
+ .desc { font-size: 13px; color: #999; margin-bottom: 20px; border-bottom: 2px dashed #ccc; padding-bottom: 12px; }
16
+
17
+ /* Layout */
18
+ .app-shell { display: flex; min-height: calc(100vh - 40px); border: 2px solid #333; border-radius: 8px; overflow: hidden; }
19
+
20
+ /* Sidebar */
21
+ .sidebar { width: 240px; background: #f5f5f5; border-right: 2px solid #ccc; display: flex; flex-direction: column; }
22
+ .sidebar-header { padding: 16px; border-bottom: 2px solid #ccc; display: flex; align-items: center; gap: 8px; }
23
+ .sidebar-header .logo { width: 28px; height: 28px; background: #ccc; border-radius: 6px; display: flex; align-items: center; justify-content: center; font-size: 14px; }
24
+ .sidebar-nav { flex: 1; padding: 12px; }
25
+ .nav-section { margin-bottom: 16px; }
26
+ .nav-section h4 { font-size: 10px; color: #999; margin-bottom: 8px; text-transform: uppercase; letter-spacing: 1.5px; }
27
+ .nav-item { padding: 10px 12px; border-radius: 6px; cursor: pointer; display: flex; align-items: center; gap: 8px; font-size: 13px; margin-bottom: 4px; border: 1px solid transparent; }
28
+ .nav-item:hover { background: #e8e8e8; }
29
+ .nav-item.active { background: #e0e0e0; border: 1px solid #ccc; font-weight: bold; }
30
+ .nav-item .icon { width: 18px; text-align: center; color: #666; }
31
+ .nav-item .badge-sm { margin-left: auto; background: #ccc; padding: 2px 6px; border-radius: 10px; font-size: 10px; }
32
+ .sidebar-footer { padding: 12px; border-top: 2px solid #ccc; }
33
+
34
+ /* Main Content */
35
+ .main { flex: 1; display: flex; flex-direction: column; }
36
+
37
+ /* Top Bar */
38
+ .topbar { padding: 12px 20px; border-bottom: 2px solid #ccc; display: flex; justify-content: space-between; align-items: center; background: #fafafa; }
39
+ .topbar-left { display: flex; align-items: center; gap: 12px; }
40
+ .breadcrumb { font-size: 12px; color: #999; }
41
+ .breadcrumb span { color: #333; font-weight: bold; }
42
+ .topbar-right { display: flex; align-items: center; gap: 12px; }
43
+ .status-dot { width: 10px; height: 10px; border-radius: 50%; border: 2px solid #333; display: inline-block; }
44
+ .status-label { font-size: 12px; color: #666; }
45
+
46
+ /* Workspace */
47
+ .workspace { flex: 1; display: grid; grid-template-columns: 1fr 1fr; gap: 0; }
48
+
49
+ /* Panels */
50
+ .panel { border: 1px solid #ccc; display: flex; flex-direction: column; }
51
+ .panel-head { padding: 12px 16px; background: #f5f5f5; border-bottom: 1px solid #ccc; display: flex; justify-content: space-between; align-items: center; }
52
+ .panel-body { padding: 16px; flex: 1; overflow-y: auto; }
53
+
54
+ /* Alert Banner */
55
+ .alert-bar { padding: 10px 14px; border: 2px dashed #999; border-radius: 6px; margin-bottom: 14px; display: flex; align-items: center; gap: 10px; background: #f9f9f9; }
56
+ .alert-badge { padding: 3px 8px; border: 1px solid #333; border-radius: 4px; font-size: 10px; font-weight: bold; }
57
+ .alert-text { font-size: 12px; color: #666; }
58
+
59
+ /* Content Preview */
60
+ .content-block { border: 2px solid #ccc; border-left: 4px solid #999; padding: 14px; border-radius: 6px; margin-bottom: 14px; background: #fafafa; min-height: 80px; font-size: 13px; line-height: 1.6; color: #555; }
61
+
62
+ /* Stat Grid */
63
+ .stat-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin-bottom: 14px; }
64
+ .stat-card { border: 1px solid #ccc; border-radius: 6px; padding: 10px; background: #fafafa; }
65
+ .stat-card .lbl { font-size: 10px; color: #999; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 4px; }
66
+ .stat-card .val { font-size: 16px; font-weight: bold; }
67
+
68
+ /* Form */
69
+ .form-row { margin-bottom: 12px; }
70
+ .form-row label { display: block; font-size: 11px; color: #999; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 4px; }
71
+ .form-row select, .form-row input, .form-row textarea { width: 100%; padding: 8px 10px; border: 2px solid #ccc; border-radius: 4px; font-family: inherit; font-size: 13px; background: #fff; }
72
+
73
+ /* Buttons */
74
+ .btn { padding: 8px 16px; border: 2px solid #333; border-radius: 6px; font-family: inherit; font-size: 13px; cursor: pointer; background: #fff; display: inline-flex; align-items: center; gap: 6px; }
75
+ .btn:hover { background: #f0f0f0; }
76
+ .btn-filled { background: #333; color: #fff; }
77
+ .btn-filled:hover { background: #555; }
78
+ .btn-full { width: 100%; justify-content: center; }
79
+ .btn-sm { padding: 5px 10px; font-size: 11px; }
80
+
81
+ /* Terminal */
82
+ .terminal-area { border-top: 2px solid #ccc; display: flex; flex-direction: column; }
83
+ .term-head { padding: 8px 16px; background: #333; color: #fff; display: flex; align-items: center; gap: 6px; font-size: 12px; }
84
+ .term-dot { width: 10px; height: 10px; border-radius: 50%; border: 1.5px solid #fff; display: inline-block; }
85
+ .term-body { background: #f5f5f5; padding: 12px 16px; font-family: 'Courier New', monospace; font-size: 11px; color: #555; min-height: 120px; border: 1px solid #ccc; line-height: 1.8; }
86
+
87
+ /* Agent Box */
88
+ .agent-box { border: 2px dashed #999; border-radius: 8px; padding: 14px; margin-top: 14px; background: #f9f9f9; }
89
+ .agent-box h4 { margin-bottom: 6px; font-size: 13px; }
90
+ .agent-box p { font-size: 11px; color: #888; margin-bottom: 10px; }
91
+ .agent-btns { display: flex; gap: 6px; }
92
+
93
+ /* HUD */
94
+ .hud-strip { display: flex; gap: 20px; padding: 8px 16px; background: #f5f5f5; border-bottom: 1px solid #ccc; font-size: 12px; }
95
+ .hud-item { display: flex; gap: 6px; }
96
+ .hud-lbl { color: #999; }
97
+ .hud-val { font-weight: bold; }
98
+
99
+ /* Reward Overlay */
100
+ .reward-mock { border: 2px dashed #999; border-radius: 8px; padding: 20px; text-align: center; margin-top: 14px; background: #fafafa; }
101
+ .reward-circle { width: 80px; height: 80px; border: 3px solid #333; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 22px; font-weight: bold; margin: 0 auto 10px; }
102
+
103
+ /* Reuse / New badge */
104
+ .tag { position: absolute; top: -8px; right: -8px; padding: 2px 6px; border-radius: 3px; font-size: 10px; font-family: Arial, sans-serif; font-weight: bold; z-index: 10; color: #fff; }
105
+ .tag-reuse { background: #4CAF50; }
106
+ .tag-new { background: #FF9800; }
107
+ .tagged { position: relative; }
108
+
109
+ /* Bottom Bar */
110
+ .bottom-bar { padding: 10px 20px; border-top: 2px solid #ccc; background: #fafafa; display: flex; justify-content: space-between; align-items: center; font-size: 11px; color: #999; }
111
+
112
+ /* Responsive */
113
+ @media (max-width: 900px) {
114
+ .app-shell { flex-direction: column; }
115
+ .sidebar { width: 100%; flex-direction: row; overflow-x: auto; }
116
+ .sidebar-nav { display: flex; gap: 4px; padding: 8px; }
117
+ .nav-section { display: flex; gap: 4px; margin: 0; }
118
+ .nav-section h4 { display: none; }
119
+ .workspace { grid-template-columns: 1fr; }
120
+ }
121
+ </style>
122
+ </head>
123
+ <body>
124
+
125
+ <h1>Option 1: Sidebar Navigation</h1>
126
+ <p class="desc">Conservative layout — persistent sidebar for task selection & navigation. Two-column workspace (Case + Actions on left, Terminal on right). Familiar pattern for tool-heavy dashboards.</p>
127
+
128
+ <div class="app-shell">
129
+
130
+ <!-- SIDEBAR -->
131
+ <!-- NEW COMPONENT: Sidebar (to be created at server/static/components or inline) -->
132
+ <aside class="sidebar tagged">
133
+ <span class="tag tag-new" title="New reusable sidebar navigation">[NEW] Sidebar</span>
134
+ <div class="sidebar-header">
135
+ <div class="logo">🛡</div>
136
+ <div>
137
+ <strong style="font-size: 14px;">ContentGuard</strong>
138
+ <div style="font-size: 10px; color: #999;">v1.0</div>
139
+ </div>
140
+ </div>
141
+ <nav class="sidebar-nav">
142
+ <div class="nav-section">
143
+ <h4>Tasks</h4>
144
+ <div class="nav-item" title="Easy: Detect violations">
145
+ <span class="icon">🔍</span> Easy (Detect)
146
+ <span class="badge-sm">Lv.1</span>
147
+ </div>
148
+ <div class="nav-item active" title="Medium: Take action">
149
+ <span class="icon">⚖️</span> Medium (Action)
150
+ <span class="badge-sm">Lv.2</span>
151
+ </div>
152
+ <div class="nav-item" title="Hard: Handle appeals">
153
+ <span class="icon">📝</span> Hard (Appeal)
154
+ <span class="badge-sm">Lv.3</span>
155
+ </div>
156
+ </div>
157
+ <div class="nav-section">
158
+ <h4>Tools</h4>
159
+ <div class="nav-item">
160
+ <span class="icon">⚙️</span> Settings
161
+ </div>
162
+ <div class="nav-item">
163
+ <span class="icon">📊</span> History
164
+ </div>
165
+ </div>
166
+ </nav>
167
+ <div class="sidebar-footer">
168
+ <div style="display: flex; align-items: center; gap: 6px; font-size: 12px;">
169
+ <span class="status-dot"></span>
170
+ <span>API Status: Live</span>
171
+ </div>
172
+ </div>
173
+ </aside>
174
+
175
+ <!-- MAIN -->
176
+ <div class="main">
177
+
178
+ <!-- TOP BAR -->
179
+ <div class="topbar">
180
+ <div class="topbar-left">
181
+ <span class="breadcrumb">Workspace &gt; <span>Medium (Action)</span></span>
182
+ </div>
183
+ <div class="topbar-right">
184
+ <button class="btn btn-sm">⚙ Settings</button>
185
+ <div style="display: flex; align-items: center; gap: 4px;">
186
+ <span class="status-dot" style="background: #ccc;"></span>
187
+ <span class="status-label">Connected</span>
188
+ </div>
189
+ </div>
190
+ </div>
191
+
192
+ <!-- HUD STRIP -->
193
+ <!-- REUSABLE: HUD from current global-hud -->
194
+ <div class="hud-strip tagged">
195
+ <span class="tag tag-reuse" title="Existing HUD metrics strip">[REUSE] HUD Strip</span>
196
+ <div class="hud-item"><span class="hud-lbl">Episodes:</span><span class="hud-val">12</span></div>
197
+ <div class="hud-item"><span class="hud-lbl">Accuracy:</span><span class="hud-val">72.3%</span></div>
198
+ <div class="hud-item"><span class="hud-lbl">Avg Reward:</span><span class="hud-val">0.68</span></div>
199
+ <div class="hud-item"><span class="hud-lbl">Session Time:</span><span class="hud-val">14m</span></div>
200
+ </div>
201
+
202
+ <!-- WORKSPACE -->
203
+ <div class="workspace">
204
+
205
+ <!-- LEFT: Case Data + Actions -->
206
+ <div class="panel" style="border-right: 2px solid #ccc;">
207
+
208
+ <!-- Alert Banner -->
209
+ <!-- REUSABLE: AlertBanner from current alert-banner -->
210
+ <div style="padding: 12px 16px;" class="tagged">
211
+ <span class="tag tag-reuse" title="Existing alert-banner component">[REUSE] AlertBanner</span>
212
+ <div class="alert-bar">
213
+ <div class="alert-badge">YELLOW</div>
214
+ <div>
215
+ <strong style="font-size: 12px;">Hate Speech Surge</strong>
216
+ <div class="alert-text">Elevated reports in region. Apply strict standards.</div>
217
+ </div>
218
+ </div>
219
+ </div>
220
+
221
+ <div class="panel-head">
222
+ <h3>📄 Content Case <span style="background: #e0e0e0; padding: 2px 8px; border-radius: 4px; font-size: 10px; margin-left: 6px;">ACTION</span></h3>
223
+ <span style="font-family: monospace; color: #999; font-size: 12px;">#POST-4829</span>
224
+ </div>
225
+ <div class="panel-body">
226
+
227
+ <!-- Content Preview -->
228
+ <!-- REUSABLE: ContentPreview from current content-preview -->
229
+ <div class="content-block tagged">
230
+ <span class="tag tag-reuse" title="Existing content-preview block">[REUSE] ContentPreview</span>
231
+ "This group of people should be banned from our neighborhood. They don't belong here and are ruining everything. We need to take matters into our own hands."
232
+ </div>
233
+
234
+ <!-- Metadata Grid -->
235
+ <!-- REUSABLE: StatGrid from current meta-grid -->
236
+ <div class="stat-grid tagged">
237
+ <span class="tag tag-reuse" title="Existing meta-grid stat boxes">[REUSE] StatGrid</span>
238
+ <div class="stat-card">
239
+ <div class="lbl">Platform 🌐</div>
240
+ <div class="val">Facebook</div>
241
+ </div>
242
+ <div class="stat-card">
243
+ <div class="lbl">Acc. Age 🕐</div>
244
+ <div class="val">342 days</div>
245
+ </div>
246
+ <div class="stat-card">
247
+ <div class="lbl">Violations ⚠️</div>
248
+ <div class="val" style="color: #333;">3</div>
249
+ </div>
250
+ <div class="stat-card">
251
+ <div class="lbl">Reports 🚩</div>
252
+ <div class="val">7</div>
253
+ </div>
254
+ </div>
255
+
256
+ <!-- Telemetry -->
257
+ <h4>Platform Risk Telemetry</h4>
258
+ <div class="stat-grid" style="margin-top: 6px;">
259
+ <div class="stat-card">
260
+ <div class="lbl">Queue Depth</div>
261
+ <div class="val">1,247</div>
262
+ </div>
263
+ <div class="stat-card">
264
+ <div class="lbl">Avg Harm</div>
265
+ <div class="val">6.2</div>
266
+ </div>
267
+ </div>
268
+
269
+ <hr style="border: 1px dashed #ddd; margin: 16px 0;">
270
+
271
+ <!-- Action Form -->
272
+ <div class="panel-head" style="background: transparent; padding: 0; border: none; margin-bottom: 10px;">
273
+ <h3>🎛 Moderation Override</h3>
274
+ </div>
275
+
276
+ <!-- REUSABLE: ActionForm from current renderActionForm -->
277
+ <div class="tagged">
278
+ <span class="tag tag-reuse" title="Existing dynamic action form">[REUSE] ActionForm</span>
279
+ <div class="form-row">
280
+ <label>Violation Type</label>
281
+ <select><option>hate_speech</option><option>harassment</option><option>safe</option></select>
282
+ </div>
283
+ <div class="form-row">
284
+ <label>Severity (1-5)</label>
285
+ <input type="number" value="4" min="1" max="5">
286
+ </div>
287
+ <div class="form-row">
288
+ <label>Action</label>
289
+ <select><option>remove</option><option>warn</option><option>restrict</option><option>no_action</option></select>
290
+ </div>
291
+ <div class="form-row">
292
+ <label>Explanation</label>
293
+ <textarea rows="2" placeholder="Brief rationale for decision..." style="resize: vertical;"></textarea>
294
+ </div>
295
+ <button class="btn btn-full" style="margin-top: 4px;">✅ Manual Commit</button>
296
+ </div>
297
+
298
+ <!-- Agent Box -->
299
+ <!-- REUSABLE: AgentBox from current auto-agent-box -->
300
+ <div class="agent-box tagged">
301
+ <span class="tag tag-reuse" title="Existing auto-agent-box">[REUSE] AgentBox</span>
302
+ <h4>🤖 Advanced Execution</h4>
303
+ <p>Transfer control to the autonomous agent. Single step or enable Continuous RL Training mode.</p>
304
+ <div class="agent-btns">
305
+ <button class="btn btn-sm">▶ Single Step</button>
306
+ <button class="btn btn-filled btn-sm" style="flex: 1;">♾ Start Auto-Training Loop</button>
307
+ </div>
308
+ </div>
309
+ </div>
310
+ </div>
311
+
312
+ <!-- RIGHT: Terminal -->
313
+ <div class="panel">
314
+ <div class="panel-head">
315
+ <h3>💻 Agent Trace Terminal</h3>
316
+ <button class="btn btn-sm">Clear</button>
317
+ </div>
318
+ <div class="panel-body" style="padding: 0; display: flex; flex-direction: column;">
319
+ <div class="term-head">
320
+ <span class="term-dot"></span>
321
+ <span class="term-dot"></span>
322
+ <span class="term-dot"></span>
323
+ <span style="margin-left: 8px;">agent-trace.sh</span>
324
+ </div>
325
+ <div class="term-body" style="flex: 1;">
326
+ > Env reset requested. Task: MEDIUM
327
+ > OpenEnv API connection established.
328
+ > Env context initialized. Operational Status: YELLOW
329
+
330
+ > Autonomous agent invoked.
331
+ [START] ep=ep_4829 task=medium
332
+
333
+ Expert Safety Moderator analyzing content...
334
+ Content contains potential hate speech patterns.
335
+ Detected: group-targeted exclusionary language
336
+ Severity assessment: 4/5 (high)
337
+
338
+ [STEP] Policy Ingested: {"violation":"hate_speech","severity":4,"action":"remove"}
339
+ [END] Result: Success. Reward: 0.8500
340
+
341
+ === OPENENV GRADER METRICS ===
342
+ > Final Score: 85.0%
343
+ > Evaluated Task: MEDIUM
344
+ > Policy Rationale: Content uses group-targeted language
345
+ > System Feedback: Correct identification and action.
346
+ ==============================
347
+ </div>
348
+
349
+ <!-- Reward Overlay Mock -->
350
+ <div class="reward-mock tagged">
351
+ <span class="tag tag-reuse" title="Existing reward-overlay">[REUSE] RewardOverlay</span>
352
+ <div class="reward-circle">0.85</div>
353
+ <strong>Grade Received</strong>
354
+ <p style="font-size: 11px; color: #888; margin-top: 4px;">Correct identification. Severity well-calibrated.</p>
355
+ <button class="btn btn-sm" style="margin-top: 10px;">Dismiss</button>
356
+ </div>
357
+ </div>
358
+ </div>
359
+
360
+ </div><!-- /workspace -->
361
+
362
+ <!-- Bottom Bar -->
363
+ <div class="bottom-bar">
364
+ <span>ContentGuardEnv v1.0 — Meta Hackathon</span>
365
+ <span>Session: ep_4829 | Task: Medium</span>
366
+ </div>
367
+
368
+ </div><!-- /main -->
369
+ </div><!-- /app-shell -->
370
+
371
+ </body>
372
+ </html>
.kombai/resources/lofi-wireframe-20260409_174154_575770-option-2.html ADDED
@@ -0,0 +1,307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Option 2: Tabbed Dashboard — Balanced Layout</title>
7
+ <style>
8
+ * { box-sizing: border-box; margin: 0; padding: 0; }
9
+ body { font-family: 'Comic Sans MS', 'Marker Felt', cursive; background: #fff; color: #333; padding: 20px; }
10
+ h1 { font-size: 22px; margin-bottom: 6px; }
11
+ h2 { font-size: 16px; margin-bottom: 10px; color: #666; }
12
+ h3 { font-size: 14px; margin-bottom: 8px; }
13
+ h4 { font-size: 12px; color: #666; margin-bottom: 6px; text-transform: uppercase; letter-spacing: 1px; }
14
+ p, span, label { font-size: 13px; }
15
+ .desc { font-size: 13px; color: #999; margin-bottom: 20px; border-bottom: 2px dashed #ccc; padding-bottom: 12px; }
16
+
17
+ /* Shell */
18
+ .shell { border: 2px solid #333; border-radius: 8px; overflow: hidden; min-height: calc(100vh - 40px); display: flex; flex-direction: column; }
19
+
20
+ /* Top Nav */
21
+ .topnav { padding: 12px 20px; border-bottom: 2px solid #ccc; display: flex; justify-content: space-between; align-items: center; background: #fafafa; }
22
+ .topnav-brand { display: flex; align-items: center; gap: 8px; font-size: 16px; font-weight: bold; }
23
+ .topnav-brand .logo { width: 28px; height: 28px; background: #ccc; border-radius: 6px; display: flex; align-items: center; justify-content: center; }
24
+ .topnav-right { display: flex; align-items: center; gap: 12px; }
25
+
26
+ /* Tab Bar */
27
+ .tab-bar { display: flex; border-bottom: 2px solid #ccc; background: #f5f5f5; }
28
+ .tab { padding: 10px 20px; cursor: pointer; font-size: 13px; border-bottom: 3px solid transparent; display: flex; align-items: center; gap: 6px; }
29
+ .tab:hover { background: #eee; }
30
+ .tab.active { border-bottom-color: #333; font-weight: bold; background: #fff; }
31
+ .tab .tab-badge { background: #ccc; padding: 1px 6px; border-radius: 10px; font-size: 10px; }
32
+
33
+ /* Status */
34
+ .status-pill { display: flex; align-items: center; gap: 6px; padding: 4px 12px; border: 1px solid #ccc; border-radius: 20px; font-size: 12px; }
35
+ .status-dot { width: 8px; height: 8px; border-radius: 50%; background: #ccc; border: 1.5px solid #999; }
36
+
37
+ /* Buttons */
38
+ .btn { padding: 8px 16px; border: 2px solid #333; border-radius: 6px; font-family: inherit; font-size: 13px; cursor: pointer; background: #fff; display: inline-flex; align-items: center; gap: 6px; }
39
+ .btn:hover { background: #f0f0f0; }
40
+ .btn-filled { background: #333; color: #fff; }
41
+ .btn-filled:hover { background: #555; }
42
+ .btn-sm { padding: 5px 10px; font-size: 11px; }
43
+ .btn-full { width: 100%; justify-content: center; }
44
+
45
+ /* Main layout: 2/3 + 1/3 */
46
+ .content-area { flex: 1; display: flex; }
47
+ .main-col { flex: 2; display: flex; flex-direction: column; border-right: 2px solid #ccc; }
48
+ .side-col { flex: 1; display: flex; flex-direction: column; min-width: 320px; }
49
+
50
+ /* Summary Cards Row */
51
+ .summary-row { display: flex; gap: 0; border-bottom: 2px solid #ccc; }
52
+ .summary-card { flex: 1; padding: 14px 16px; border-right: 1px solid #ccc; }
53
+ .summary-card:last-child { border-right: none; }
54
+ .summary-card .lbl { font-size: 10px; color: #999; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 4px; }
55
+ .summary-card .val { font-size: 20px; font-weight: bold; }
56
+ .summary-card .sub { font-size: 10px; color: #888; margin-top: 2px; }
57
+
58
+ /* Panel sections */
59
+ .section { padding: 16px; border-bottom: 1px solid #ccc; }
60
+ .section:last-child { border-bottom: none; }
61
+ .section-head { display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; }
62
+
63
+ /* Alert */
64
+ .alert-bar { padding: 10px 14px; border: 2px dashed #999; border-radius: 6px; display: flex; align-items: center; gap: 10px; background: #f9f9f9; }
65
+ .alert-badge { padding: 3px 8px; border: 1px solid #333; border-radius: 4px; font-size: 10px; font-weight: bold; }
66
+
67
+ /* Content Preview */
68
+ .content-block { border: 2px solid #ccc; border-left: 4px solid #999; padding: 14px; border-radius: 6px; background: #fafafa; min-height: 60px; font-size: 13px; line-height: 1.6; color: #555; }
69
+
70
+ /* Metadata */
71
+ .meta-row { display: flex; gap: 12px; flex-wrap: wrap; margin-top: 10px; }
72
+ .meta-chip { display: flex; align-items: center; gap: 4px; padding: 4px 10px; border: 1px solid #ccc; border-radius: 20px; font-size: 11px; background: #fafafa; }
73
+
74
+ /* Form */
75
+ .form-row { margin-bottom: 12px; }
76
+ .form-row label { display: block; font-size: 11px; color: #999; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 4px; }
77
+ .form-row select, .form-row input, .form-row textarea { width: 100%; padding: 8px 10px; border: 2px solid #ccc; border-radius: 4px; font-family: inherit; font-size: 13px; background: #fff; }
78
+
79
+ /* Terminal */
80
+ .term-head { padding: 8px 12px; background: #333; color: #fff; display: flex; align-items: center; gap: 6px; font-size: 12px; }
81
+ .term-dot { width: 10px; height: 10px; border-radius: 50%; border: 1.5px solid #fff; display: inline-block; }
82
+ .term-body { background: #f5f5f5; padding: 12px; font-family: 'Courier New', monospace; font-size: 11px; color: #555; flex: 1; overflow-y: auto; line-height: 1.8; }
83
+
84
+ /* Agent section */
85
+ .agent-box { border: 2px dashed #999; border-radius: 8px; padding: 14px; background: #f9f9f9; }
86
+ .agent-box h4 { margin-bottom: 6px; }
87
+ .agent-box p { font-size: 11px; color: #888; margin-bottom: 10px; }
88
+ .agent-btns { display: flex; gap: 6px; }
89
+
90
+ /* Reward */
91
+ .reward-mock { border: 2px dashed #999; border-radius: 8px; padding: 16px; text-align: center; background: #fafafa; }
92
+ .reward-circle { width: 70px; height: 70px; border: 3px solid #333; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 20px; font-weight: bold; margin: 0 auto 8px; }
93
+
94
+ /* Tags */
95
+ .tag { position: absolute; top: -8px; right: -8px; padding: 2px 6px; border-radius: 3px; font-size: 10px; font-family: Arial, sans-serif; font-weight: bold; z-index: 10; color: #fff; }
96
+ .tag-reuse { background: #4CAF50; }
97
+ .tag-new { background: #FF9800; }
98
+ .tagged { position: relative; }
99
+
100
+ /* Responsive */
101
+ @media (max-width: 900px) {
102
+ .content-area { flex-direction: column; }
103
+ .main-col { border-right: none; border-bottom: 2px solid #ccc; }
104
+ .side-col { min-width: 100%; }
105
+ .summary-row { flex-wrap: wrap; }
106
+ .summary-card { min-width: 50%; }
107
+ }
108
+ </style>
109
+ </head>
110
+ <body>
111
+
112
+ <h1>Option 2: Tabbed Dashboard</h1>
113
+ <p class="desc">Balanced layout — top navigation with task tabs. Main area split into 2/3 content + 1/3 terminal sidebar. Summary stats as a persistent top strip. Focuses on clear information hierarchy and scanability.</p>
114
+
115
+ <div class="shell">
116
+
117
+ <!-- TOP NAV -->
118
+ <div class="topnav">
119
+ <div class="topnav-brand">
120
+ <div class="logo">🛡</div>
121
+ <span>ContentGuardEnv</span>
122
+ </div>
123
+ <div class="topnav-right">
124
+ <button class="btn btn-sm">⚙ Settings</button>
125
+ <div class="status-pill">
126
+ <span class="status-dot" style="background: #ccc;"></span>
127
+ API Connected
128
+ </div>
129
+ </div>
130
+ </div>
131
+
132
+ <!-- TAB BAR -->
133
+ <!-- NEW COMPONENT: TabBar for task switching -->
134
+ <div class="tab-bar tagged">
135
+ <span class="tag tag-new" title="New tab bar component for task selection">[NEW] TabBar</span>
136
+ <div class="tab">
137
+ 🔍 Easy (Detect) <span class="tab-badge">Lv.1</span>
138
+ </div>
139
+ <div class="tab active">
140
+ ⚖️ Medium (Action) <span class="tab-badge">Lv.2</span>
141
+ </div>
142
+ <div class="tab">
143
+ 📝 Hard (Appeal) <span class="tab-badge">Lv.3</span>
144
+ </div>
145
+ <div style="flex: 1;"></div>
146
+ <div class="tab" style="color: #999;">
147
+ 📊 History
148
+ </div>
149
+ </div>
150
+
151
+ <!-- SUMMARY CARDS -->
152
+ <!-- NEW COMPONENT: SummaryStrip — persistent metrics at a glance -->
153
+ <div class="summary-row tagged">
154
+ <span class="tag tag-new" title="New summary metrics strip">[NEW] SummaryStrip</span>
155
+ <div class="summary-card">
156
+ <div class="lbl">Current Task</div>
157
+ <div class="val">Medium</div>
158
+ <div class="sub">Action Decision Required</div>
159
+ </div>
160
+ <div class="summary-card">
161
+ <div class="lbl">Episodes</div>
162
+ <div class="val">12</div>
163
+ <div class="sub">this session</div>
164
+ </div>
165
+ <div class="summary-card">
166
+ <div class="lbl">Accuracy</div>
167
+ <div class="val">72.3%</div>
168
+ <div class="sub">avg reward: 0.68</div>
169
+ </div>
170
+ <div class="summary-card">
171
+ <div class="lbl">Alert Level</div>
172
+ <div class="val" style="color: #333;">⚠ YELLOW</div>
173
+ <div class="sub">Hate Speech Surge</div>
174
+ </div>
175
+ </div>
176
+
177
+ <!-- MAIN CONTENT AREA -->
178
+ <div class="content-area">
179
+
180
+ <!-- LEFT: Case + Actions (2/3) -->
181
+ <div class="main-col">
182
+
183
+ <!-- Policy Alert -->
184
+ <div class="section tagged">
185
+ <span class="tag tag-reuse" title="Existing alert-banner">[REUSE] AlertBanner</span>
186
+ <div class="alert-bar">
187
+ <div class="alert-badge">YELLOW</div>
188
+ <div>
189
+ <strong style="font-size: 12px;">Hate Speech Surge — Regional Alert</strong>
190
+ <div style="font-size: 11px; color: #888;">Apply strict community standards. Cross-reference recent policy updates.</div>
191
+ </div>
192
+ </div>
193
+ </div>
194
+
195
+ <!-- Case Content -->
196
+ <div class="section">
197
+ <div class="section-head">
198
+ <h3>📄 Content Case</h3>
199
+ <span style="font-family: monospace; color: #999; font-size: 12px;">#POST-4829</span>
200
+ </div>
201
+
202
+ <!-- REUSABLE: ContentPreview -->
203
+ <div class="content-block tagged">
204
+ <span class="tag tag-reuse" title="Existing content preview">[REUSE] ContentPreview</span>
205
+ "This group of people should be banned from our neighborhood. They don't belong here and are ruining everything. We need to take matters into our own hands."
206
+ </div>
207
+
208
+ <!-- Metadata as chips instead of grid -->
209
+ <!-- NEW COMPONENT: MetaChips — compact inline metadata -->
210
+ <div class="meta-row tagged">
211
+ <span class="tag tag-new" title="New compact metadata chips">[NEW] MetaChips</span>
212
+ <div class="meta-chip">🌐 <strong>Facebook</strong></div>
213
+ <div class="meta-chip">🕐 <strong>342</strong> days</div>
214
+ <div class="meta-chip">⚠️ <strong>3</strong> violations</div>
215
+ <div class="meta-chip">🚩 <strong>7</strong> reports</div>
216
+ <div class="meta-chip">📊 Queue: <strong>1,247</strong></div>
217
+ <div class="meta-chip">🔥 Harm: <strong>6.2</strong></div>
218
+ </div>
219
+ </div>
220
+
221
+ <!-- Moderation Form — Horizontally laid out -->
222
+ <div class="section">
223
+ <div class="section-head">
224
+ <h3>🎛 Moderation Override</h3>
225
+ </div>
226
+
227
+ <!-- REUSABLE: ActionForm -->
228
+ <div class="tagged" style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
229
+ <span class="tag tag-reuse" title="Existing action form">[REUSE] ActionForm</span>
230
+ <div class="form-row">
231
+ <label>Violation Type</label>
232
+ <select><option>hate_speech</option><option>harassment</option><option>safe</option></select>
233
+ </div>
234
+ <div class="form-row">
235
+ <label>Severity (1-5)</label>
236
+ <input type="number" value="4" min="1" max="5">
237
+ </div>
238
+ <div class="form-row">
239
+ <label>Action</label>
240
+ <select><option>remove</option><option>warn</option><option>restrict</option></select>
241
+ </div>
242
+ <div class="form-row">
243
+ <label>Explanation</label>
244
+ <input type="text" placeholder="Brief rationale...">
245
+ </div>
246
+ </div>
247
+ <div style="display: flex; gap: 8px; margin-top: 8px;">
248
+ <button class="btn" style="flex: 1;">✅ Manual Commit</button>
249
+ <button class="btn btn-sm">▶ Single Step</button>
250
+ <button class="btn btn-filled btn-sm" style="flex: 1;">♾ Auto-Train</button>
251
+ </div>
252
+ </div>
253
+
254
+ </div><!-- /main-col -->
255
+
256
+ <!-- RIGHT: Terminal Sidebar (1/3) -->
257
+ <div class="side-col">
258
+ <div class="term-head">
259
+ <span class="term-dot"></span>
260
+ <span class="term-dot"></span>
261
+ <span class="term-dot"></span>
262
+ <span style="margin-left: 8px;">agent-trace.sh</span>
263
+ <span style="flex: 1;"></span>
264
+ <button class="btn btn-sm" style="border-color: #fff; color: #fff; padding: 2px 8px; font-size: 10px;">Clear</button>
265
+ </div>
266
+ <!-- REUSABLE: Terminal -->
267
+ <div class="term-body tagged" style="min-height: 200px;">
268
+ <span class="tag tag-reuse" title="Existing terminal output">[REUSE] Terminal</span>
269
+ > Env reset requested. Task: MEDIUM
270
+ > OpenEnv API connection established.
271
+ > Env context initialized. Status: YELLOW
272
+
273
+ > Autonomous agent invoked.
274
+ [START] ep=ep_4829 task=medium
275
+
276
+ Analyzing content for policy violations...
277
+ Detected: group-targeted exclusionary language
278
+ Severity: 4/5 (high)
279
+
280
+ [STEP] {"violation":"hate_speech","severity":4,"action":"remove"}
281
+ [END] Reward: 0.8500
282
+
283
+ === GRADER METRICS ===
284
+ > Score: 85.0%
285
+ > Task: MEDIUM
286
+ > Feedback: Correct identification.
287
+ ======================
288
+ </div>
289
+
290
+ <!-- Inline Reward Display -->
291
+ <div style="padding: 12px;">
292
+ <!-- REUSABLE: RewardOverlay (adapted as inline card) -->
293
+ <div class="reward-mock tagged">
294
+ <span class="tag tag-reuse" title="Existing reward overlay, adapted inline">[REUSE] RewardOverlay</span>
295
+ <div class="reward-circle">0.85</div>
296
+ <strong>Grade: 85%</strong>
297
+ <p style="font-size: 11px; color: #888; margin-top: 4px;">Correct identification. Severity well-calibrated.</p>
298
+ <button class="btn btn-sm" style="margin-top: 8px;">Next Case →</button>
299
+ </div>
300
+ </div>
301
+ </div>
302
+
303
+ </div><!-- /content-area -->
304
+ </div><!-- /shell -->
305
+
306
+ </body>
307
+ </html>
.kombai/resources/lofi-wireframe-20260409_174154_575770-option-3.html ADDED
@@ -0,0 +1,358 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Option 3: Command Center — Innovative Layout</title>
7
+ <style>
8
+ * { box-sizing: border-box; margin: 0; padding: 0; }
9
+ body { font-family: 'Comic Sans MS', 'Marker Felt', cursive; background: #fff; color: #333; padding: 20px; }
10
+ h1 { font-size: 22px; margin-bottom: 6px; }
11
+ p.desc { font-size: 13px; color: #999; margin-bottom: 20px; border-bottom: 2px dashed #ccc; padding-bottom: 12px; }
12
+ h3 { font-size: 14px; margin-bottom: 8px; }
13
+ h4 { font-size: 12px; color: #666; margin-bottom: 6px; text-transform: uppercase; letter-spacing: 1px; }
14
+ p, span, label { font-size: 13px; }
15
+
16
+ /* Shell */
17
+ .shell { border: 2px solid #333; border-radius: 8px; overflow: hidden; min-height: calc(100vh - 40px); display: flex; flex-direction: column; }
18
+
19
+ /* Compact Header */
20
+ .header { padding: 8px 20px; border-bottom: 2px solid #ccc; display: flex; justify-content: space-between; align-items: center; background: #fafafa; }
21
+ .header-left { display: flex; align-items: center; gap: 16px; }
22
+ .header-brand { display: flex; align-items: center; gap: 6px; font-weight: bold; font-size: 14px; }
23
+ .header-brand .logo { width: 24px; height: 24px; background: #ccc; border-radius: 4px; display: flex; align-items: center; justify-content: center; font-size: 12px; }
24
+ .header-right { display: flex; align-items: center; gap: 10px; }
25
+
26
+ /* Task Switcher (pill toggle) */
27
+ .task-toggle { display: flex; border: 2px solid #ccc; border-radius: 20px; overflow: hidden; }
28
+ .task-pill { padding: 6px 14px; font-size: 11px; cursor: pointer; display: flex; align-items: center; gap: 4px; border-right: 1px solid #ccc; }
29
+ .task-pill:last-child { border-right: none; }
30
+ .task-pill:hover { background: #f0f0f0; }
31
+ .task-pill.active { background: #333; color: #fff; font-weight: bold; }
32
+
33
+ /* Status */
34
+ .status-pill { display: flex; align-items: center; gap: 4px; padding: 4px 10px; border: 1px solid #ccc; border-radius: 14px; font-size: 11px; }
35
+ .status-dot { width: 6px; height: 6px; border-radius: 50%; background: #ccc; border: 1px solid #999; }
36
+
37
+ /* Buttons */
38
+ .btn { padding: 6px 12px; border: 2px solid #333; border-radius: 6px; font-family: inherit; font-size: 12px; cursor: pointer; background: #fff; display: inline-flex; align-items: center; gap: 4px; }
39
+ .btn:hover { background: #f0f0f0; }
40
+ .btn-filled { background: #333; color: #fff; }
41
+ .btn-sm { padding: 4px 8px; font-size: 10px; }
42
+
43
+ /* Main Grid: 3 rows — top strip, main content, bottom terminal */
44
+ .content-grid { flex: 1; display: flex; flex-direction: column; }
45
+
46
+ /* Context Strip (collapsible) */
47
+ .context-strip { display: flex; border-bottom: 2px solid #ccc; }
48
+ .ctx-card { flex: 1; padding: 10px 14px; border-right: 1px solid #ccc; display: flex; flex-direction: column; }
49
+ .ctx-card:last-child { border-right: none; }
50
+ .ctx-lbl { font-size: 9px; color: #999; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 2px; }
51
+ .ctx-val { font-size: 16px; font-weight: bold; }
52
+ .ctx-sub { font-size: 10px; color: #888; }
53
+
54
+ /* Center: Split View */
55
+ .center-area { flex: 1; display: flex; }
56
+
57
+ /* Evidence Panel */
58
+ .evidence-panel { flex: 3; display: flex; flex-direction: column; border-right: 2px solid #ccc; }
59
+ .evidence-header { padding: 10px 16px; border-bottom: 1px solid #ccc; display: flex; justify-content: space-between; align-items: center; background: #fafafa; }
60
+ .evidence-body { padding: 16px; flex: 1; overflow-y: auto; }
61
+
62
+ /* Decision Panel */
63
+ .decision-panel { flex: 2; display: flex; flex-direction: column; }
64
+ .decision-header { padding: 10px 16px; border-bottom: 1px solid #ccc; display: flex; justify-content: space-between; align-items: center; background: #fafafa; }
65
+ .decision-body { padding: 16px; flex: 1; overflow-y: auto; display: flex; flex-direction: column; }
66
+
67
+ /* Content block */
68
+ .content-block { border: 2px solid #ccc; border-left: 4px solid #999; padding: 12px; border-radius: 6px; background: #fafafa; font-size: 13px; line-height: 1.6; color: #555; margin-bottom: 12px; }
69
+
70
+ /* Evidence details */
71
+ .evidence-grid { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 8px; margin-bottom: 12px; }
72
+ .ev-item { padding: 8px; border: 1px solid #ccc; border-radius: 4px; background: #fafafa; }
73
+ .ev-item .lbl { font-size: 9px; color: #999; text-transform: uppercase; margin-bottom: 2px; }
74
+ .ev-item .val { font-size: 14px; font-weight: bold; }
75
+
76
+ /* Alert inline */
77
+ .alert-inline { padding: 8px 12px; border: 2px dashed #999; border-radius: 6px; display: flex; align-items: center; gap: 8px; font-size: 12px; background: #f9f9f9; margin-bottom: 12px; }
78
+ .alert-badge { padding: 2px 6px; border: 1px solid #333; border-radius: 3px; font-size: 9px; font-weight: bold; }
79
+
80
+ /* Form compact */
81
+ .form-compact { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }
82
+ .form-row { margin-bottom: 0; }
83
+ .form-row label { display: block; font-size: 10px; color: #999; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 3px; }
84
+ .form-row select, .form-row input { width: 100%; padding: 6px 8px; border: 2px solid #ccc; border-radius: 4px; font-family: inherit; font-size: 12px; }
85
+ .form-row.full { grid-column: 1 / -1; }
86
+
87
+ /* Quick Action Buttons */
88
+ .quick-actions { display: grid; grid-template-columns: 1fr 1fr; gap: 6px; margin-top: auto; padding-top: 12px; }
89
+
90
+ /* Bottom Terminal Drawer */
91
+ .terminal-drawer { border-top: 2px solid #333; display: flex; flex-direction: column; height: 180px; }
92
+ .term-toolbar { padding: 6px 16px; background: #333; color: #fff; display: flex; align-items: center; justify-content: space-between; font-size: 12px; }
93
+ .term-toolbar-left { display: flex; align-items: center; gap: 8px; }
94
+ .term-dots { display: flex; gap: 4px; }
95
+ .term-dot { width: 8px; height: 8px; border-radius: 50%; border: 1.5px solid #fff; }
96
+ .term-tabs { display: flex; gap: 0; margin-left: 12px; }
97
+ .term-tab { padding: 3px 10px; font-size: 10px; border: 1px solid #555; cursor: pointer; }
98
+ .term-tab.active { background: #555; }
99
+ .term-body { background: #f5f5f5; padding: 10px 16px; font-family: 'Courier New', monospace; font-size: 11px; color: #555; flex: 1; overflow-y: auto; line-height: 1.6; display: flex; }
100
+ .term-output { flex: 3; border-right: 1px solid #ddd; padding-right: 12px; }
101
+ .term-result { flex: 1; padding-left: 12px; text-align: center; display: flex; flex-direction: column; align-items: center; justify-content: center; }
102
+
103
+ /* Reward inline */
104
+ .reward-circle-sm { width: 50px; height: 50px; border: 2px solid #333; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 16px; font-weight: bold; margin-bottom: 4px; }
105
+
106
+ /* Tags */
107
+ .tag { position: absolute; top: -8px; right: -8px; padding: 2px 6px; border-radius: 3px; font-size: 10px; font-family: Arial, sans-serif; font-weight: bold; z-index: 10; color: #fff; }
108
+ .tag-reuse { background: #4CAF50; }
109
+ .tag-new { background: #FF9800; }
110
+ .tagged { position: relative; }
111
+
112
+ /* Keyboard shortcut hints */
113
+ .kbd { display: inline-block; padding: 1px 5px; border: 1px solid #ccc; border-radius: 3px; font-size: 10px; font-family: monospace; background: #f5f5f5; color: #666; }
114
+
115
+ /* Responsive */
116
+ @media (max-width: 900px) {
117
+ .center-area { flex-direction: column; }
118
+ .evidence-panel { border-right: none; border-bottom: 2px solid #ccc; }
119
+ .evidence-grid { grid-template-columns: 1fr 1fr; }
120
+ .form-compact { grid-template-columns: 1fr; }
121
+ .context-strip { flex-wrap: wrap; }
122
+ .ctx-card { min-width: 50%; }
123
+ .term-body { flex-direction: column; }
124
+ .term-result { padding: 8px 0; border-top: 1px solid #ddd; }
125
+ .term-output { border-right: none; padding-right: 0; }
126
+ .task-toggle { display: none; }
127
+ }
128
+ </style>
129
+ </head>
130
+ <body>
131
+
132
+ <h1>Option 3: Command Center</h1>
133
+ <p class="desc">Innovative layout — compact header with pill-toggle task switcher. Split-view evidence + decision panels. Persistent bottom terminal drawer with inline reward display. Keyboard shortcuts. Designed for power users running continuous training loops.</p>
134
+
135
+ <div class="shell">
136
+
137
+ <!-- COMPACT HEADER -->
138
+ <div class="header">
139
+ <div class="header-left">
140
+ <div class="header-brand">
141
+ <div class="logo">🛡</div>
142
+ ContentGuard
143
+ </div>
144
+ <!-- NEW COMPONENT: TaskToggle — compact pill-style task switcher -->
145
+ <div class="task-toggle tagged">
146
+ <span class="tag tag-new" title="New pill-toggle task selector">[NEW] TaskToggle</span>
147
+ <div class="task-pill">🔍 Easy</div>
148
+ <div class="task-pill active">⚖️ Medium</div>
149
+ <div class="task-pill">📝 Hard</div>
150
+ </div>
151
+ </div>
152
+ <div class="header-right">
153
+ <span style="font-size: 10px; color: #999;">Shortcuts: <span class="kbd">E</span> <span class="kbd">M</span> <span class="kbd">H</span> to switch tasks | <span class="kbd">⌘↵</span> submit</span>
154
+ <button class="btn btn-sm">⚙</button>
155
+ <div class="status-pill">
156
+ <span class="status-dot" style="background: #ccc;"></span>
157
+ Live
158
+ </div>
159
+ </div>
160
+ </div>
161
+
162
+ <!-- CONTEXT STRIP (metrics at a glance) -->
163
+ <!-- NEW COMPONENT: ContextStrip — collapsible top metrics bar -->
164
+ <div class="context-strip tagged">
165
+ <span class="tag tag-new" title="New collapsible context metrics strip">[NEW] ContextStrip</span>
166
+ <div class="ctx-card">
167
+ <span class="ctx-lbl">Alert</span>
168
+ <span class="ctx-val">⚠ YELLOW</span>
169
+ <span class="ctx-sub">Hate Speech Surge</span>
170
+ </div>
171
+ <div class="ctx-card">
172
+ <span class="ctx-lbl">Episodes</span>
173
+ <span class="ctx-val">12</span>
174
+ <span class="ctx-sub">72.3% accuracy</span>
175
+ </div>
176
+ <div class="ctx-card">
177
+ <span class="ctx-lbl">Queue</span>
178
+ <span class="ctx-val">1,247</span>
179
+ <span class="ctx-sub">avg harm: 6.2</span>
180
+ </div>
181
+ <div class="ctx-card">
182
+ <span class="ctx-lbl">Session</span>
183
+ <span class="ctx-val">14m</span>
184
+ <span class="ctx-sub">avg time/case: 1.2m</span>
185
+ </div>
186
+ <div class="ctx-card" style="min-width: 40px; max-width: 40px; display: flex; align-items: center; justify-content: center; cursor: pointer; color: #999;">
187
+
188
+ </div>
189
+ </div>
190
+
191
+ <div class="content-grid">
192
+
193
+ <!-- CENTER SPLIT VIEW -->
194
+ <div class="center-area">
195
+
196
+ <!-- EVIDENCE PANEL (left, wider) -->
197
+ <div class="evidence-panel">
198
+ <div class="evidence-header">
199
+ <h3>📄 Evidence Review <span style="background: #e0e0e0; padding: 1px 6px; border-radius: 3px; font-size: 9px; margin-left: 4px;">ACTION</span></h3>
200
+ <span style="font-family: monospace; font-size: 11px; color: #999;">#POST-4829</span>
201
+ </div>
202
+ <div class="evidence-body">
203
+
204
+ <!-- Alert -->
205
+ <!-- REUSABLE: AlertBanner -->
206
+ <div class="alert-inline tagged">
207
+ <span class="tag tag-reuse" title="Existing alert-banner">[REUSE] AlertBanner</span>
208
+ <div class="alert-badge">YELLOW</div>
209
+ <span>Hate Speech Surge — Apply strict community standards</span>
210
+ </div>
211
+
212
+ <!-- Content -->
213
+ <!-- REUSABLE: ContentPreview -->
214
+ <div class="content-block tagged">
215
+ <span class="tag tag-reuse" title="Existing content preview">[REUSE] ContentPreview</span>
216
+ "This group of people should be banned from our neighborhood. They don't belong here and are ruining everything. We need to take matters into our own hands."
217
+ </div>
218
+
219
+ <!-- Evidence Details — 3-column grid -->
220
+ <!-- REUSABLE: StatGrid (reimagined as 3-col) -->
221
+ <div class="evidence-grid tagged">
222
+ <span class="tag tag-reuse" title="Existing meta-grid reimagined">[REUSE] StatGrid</span>
223
+ <div class="ev-item">
224
+ <div class="lbl">Platform</div>
225
+ <div class="val">Facebook</div>
226
+ </div>
227
+ <div class="ev-item">
228
+ <div class="lbl">Account Age</div>
229
+ <div class="val">342 days</div>
230
+ </div>
231
+ <div class="ev-item">
232
+ <div class="lbl">Prior Violations</div>
233
+ <div class="val">3</div>
234
+ </div>
235
+ <div class="ev-item">
236
+ <div class="lbl">Reports</div>
237
+ <div class="val">7</div>
238
+ </div>
239
+ <div class="ev-item">
240
+ <div class="lbl">Queue Depth</div>
241
+ <div class="val">1,247</div>
242
+ </div>
243
+ <div class="ev-item">
244
+ <div class="lbl">Avg Harm</div>
245
+ <div class="val">6.2</div>
246
+ </div>
247
+ </div>
248
+
249
+ <!-- AI Risk Summary — new feature -->
250
+ <!-- NEW COMPONENT: RiskSummary — AI-generated context summary -->
251
+ <div class="tagged" style="border: 2px dashed #999; border-radius: 6px; padding: 10px; background: #f9f9f9;">
252
+ <span class="tag tag-new" title="New AI risk summary component">[NEW] RiskSummary</span>
253
+ <h4 style="margin-bottom: 4px;">🧠 AI Risk Assessment</h4>
254
+ <p style="font-size: 11px; color: #666; line-height: 1.5;">
255
+ Content exhibits <strong>group-targeted exclusionary language</strong> with escalation indicators ("take matters into our own hands"). User has 3 prior violations across 342 days. Combined with 7 community reports, this case has <strong>high confidence</strong> for hate speech classification.
256
+ </p>
257
+ </div>
258
+
259
+ </div>
260
+ </div>
261
+
262
+ <!-- DECISION PANEL (right, narrower) -->
263
+ <div class="decision-panel">
264
+ <div class="decision-header">
265
+ <h3>🎛 Decision</h3>
266
+ <span class="kbd">⌘↵</span>
267
+ </div>
268
+ <div class="decision-body">
269
+
270
+ <!-- Compact Form -->
271
+ <!-- REUSABLE: ActionForm (compact 2-col layout) -->
272
+ <div class="form-compact tagged">
273
+ <span class="tag tag-reuse" title="Existing action form, compact">[REUSE] ActionForm</span>
274
+ <div class="form-row">
275
+ <label>Violation</label>
276
+ <select><option>hate_speech</option><option>harassment</option><option>safe</option></select>
277
+ </div>
278
+ <div class="form-row">
279
+ <label>Severity</label>
280
+ <input type="number" value="4" min="1" max="5">
281
+ </div>
282
+ <div class="form-row">
283
+ <label>Action</label>
284
+ <select><option>remove</option><option>warn</option><option>restrict</option></select>
285
+ </div>
286
+ <div class="form-row">
287
+ <label>Policy Refs</label>
288
+ <input type="text" placeholder="e.g. 3.1, 4.2">
289
+ </div>
290
+ <div class="form-row full">
291
+ <label>Rationale</label>
292
+ <input type="text" placeholder="Brief explanation...">
293
+ </div>
294
+ </div>
295
+
296
+ <!-- Quick Actions -->
297
+ <div class="quick-actions">
298
+ <button class="btn" style="justify-content: center;">✅ Commit <span class="kbd" style="margin-left: 4px;">⌘↵</span></button>
299
+ <button class="btn" style="justify-content: center;">▶ Single Step <span class="kbd" style="margin-left: 4px;">S</span></button>
300
+ <button class="btn btn-filled" style="justify-content: center; grid-column: 1 / -1;">♾ Auto-Training Loop <span class="kbd" style="margin-left: 4px; border-color: #999;">A</span></button>
301
+ </div>
302
+
303
+ </div>
304
+ </div>
305
+
306
+ </div><!-- /center-area -->
307
+
308
+ <!-- BOTTOM TERMINAL DRAWER -->
309
+ <div class="terminal-drawer">
310
+ <div class="term-toolbar">
311
+ <div class="term-toolbar-left">
312
+ <div class="term-dots">
313
+ <span class="term-dot"></span>
314
+ <span class="term-dot"></span>
315
+ <span class="term-dot"></span>
316
+ </div>
317
+ <div class="term-tabs">
318
+ <div class="term-tab active">Trace</div>
319
+ <div class="term-tab">Logs</div>
320
+ <div class="term-tab">History</div>
321
+ </div>
322
+ </div>
323
+ <div style="display: flex; gap: 8px; align-items: center;">
324
+ <button class="btn btn-sm" style="border-color: #666; color: #ccc; padding: 2px 6px; font-size: 9px;">Clear</button>
325
+ <span style="cursor: pointer; font-size: 14px;" title="Expand terminal">▼</span>
326
+ </div>
327
+ </div>
328
+ <!-- REUSABLE: Terminal -->
329
+ <div class="term-body tagged">
330
+ <span class="tag tag-reuse" title="Existing terminal">[REUSE] Terminal</span>
331
+ <div class="term-output">
332
+ > Env reset. Task: MEDIUM
333
+ > API connected. Status: YELLOW
334
+ > Agent invoked.
335
+ [START] ep=ep_4829 task=medium
336
+ Analyzing... Detected: group-targeted language
337
+ Severity: 4/5 (high)
338
+ [STEP] {"violation":"hate_speech","severity":4,"action":"remove"}
339
+ [END] Reward: 0.8500
340
+ === SCORE: 85.0% | Task: MEDIUM ===
341
+ </div>
342
+ <!-- Inline Reward in Terminal -->
343
+ <!-- REUSABLE: RewardOverlay (adapted as terminal inline) -->
344
+ <div class="term-result tagged">
345
+ <span class="tag tag-reuse" title="Existing reward overlay, adapted">[REUSE] RewardOverlay</span>
346
+ <div class="reward-circle-sm">0.85</div>
347
+ <strong style="font-size: 12px;">85%</strong>
348
+ <span style="font-size: 10px; color: #888;">Correct</span>
349
+ <button class="btn btn-sm" style="margin-top: 6px; font-size: 9px;">Next →</button>
350
+ </div>
351
+ </div>
352
+ </div>
353
+
354
+ </div><!-- /content-grid -->
355
+ </div><!-- /shell -->
356
+
357
+ </body>
358
+ </html>
.pytest_cache/.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # Created by pytest automatically.
2
+ *
.pytest_cache/CACHEDIR.TAG ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ Signature: 8a477f597d28d172789f06886806bc55
2
+ # This file is a cache directory tag created by pytest.
3
+ # For information about cache directory tags, see:
4
+ # https://bford.info/cachedir/spec.html
.pytest_cache/README.md ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # pytest cache directory #
2
+
3
+ This directory contains data from the pytest's cache plugin,
4
+ which provides the `--lf` and `--ff` options, as well as the `cache` fixture.
5
+
6
+ **Do not** commit this to version control.
7
+
8
+ See [the docs](https://docs.pytest.org/en/stable/how-to/cache.html) for more information.
.pytest_cache/v/cache/lastfailed ADDED
@@ -0,0 +1 @@
 
 
1
+ {}
.pytest_cache/v/cache/nodeids ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ [
2
+ "tests/test_graders.py::test_grade_easy_cluster_match",
3
+ "tests/test_graders.py::test_grade_easy_perfect_match",
4
+ "tests/test_graders.py::test_grade_hard_with_evidence",
5
+ "tests/test_graders.py::test_grade_medium_action_proximity"
6
+ ]
.venv/.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ *
.venv/Lib/site-packages/3c22db458360489351e4__mypyc.cp312-win_amd64.pyd ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7c750f2ac06915e4b4b28342abae832c8f66207e4a547281607e924ae1673da1
3
+ size 169472
.venv/Lib/site-packages/81d243bd2c585b0f4821__mypyc.cp312-win_amd64.pyd ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:52056f4b964f1bc0419064a374a32e56ef85ccb161166971d26f46a7490bd238
3
+ size 219136
.venv/Lib/site-packages/PIL/AvifImagePlugin.py ADDED
@@ -0,0 +1,293 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ from io import BytesIO
5
+ from typing import IO
6
+
7
+ from . import ExifTags, Image, ImageFile
8
+
9
+ try:
10
+ from . import _avif
11
+
12
+ SUPPORTED = True
13
+ except ImportError:
14
+ SUPPORTED = False
15
+
16
+ # Decoder options as module globals, until there is a way to pass parameters
17
+ # to Image.open (see https://github.com/python-pillow/Pillow/issues/569)
18
+ DECODE_CODEC_CHOICE = "auto"
19
+ DEFAULT_MAX_THREADS = 0
20
+
21
+
22
+ def get_codec_version(codec_name: str) -> str | None:
23
+ versions = _avif.codec_versions()
24
+ for version in versions.split(", "):
25
+ if version.split(" [")[0] == codec_name:
26
+ return version.split(":")[-1].split(" ")[0]
27
+ return None
28
+
29
+
30
+ def _accept(prefix: bytes) -> bool | str:
31
+ if prefix[4:8] != b"ftyp":
32
+ return False
33
+ major_brand = prefix[8:12]
34
+ if major_brand in (
35
+ # coding brands
36
+ b"avif",
37
+ b"avis",
38
+ # We accept files with AVIF container brands; we can't yet know if
39
+ # the ftyp box has the correct compatible brands, but if it doesn't
40
+ # then the plugin will raise a SyntaxError which Pillow will catch
41
+ # before moving on to the next plugin that accepts the file.
42
+ #
43
+ # Also, because this file might not actually be an AVIF file, we
44
+ # don't raise an error if AVIF support isn't properly compiled.
45
+ b"mif1",
46
+ b"msf1",
47
+ ):
48
+ if not SUPPORTED:
49
+ return (
50
+ "image file could not be identified because AVIF support not installed"
51
+ )
52
+ return True
53
+ return False
54
+
55
+
56
+ def _get_default_max_threads() -> int:
57
+ if DEFAULT_MAX_THREADS:
58
+ return DEFAULT_MAX_THREADS
59
+ if hasattr(os, "sched_getaffinity"):
60
+ return len(os.sched_getaffinity(0))
61
+ else:
62
+ return os.cpu_count() or 1
63
+
64
+
65
+ class AvifImageFile(ImageFile.ImageFile):
66
+ format = "AVIF"
67
+ format_description = "AVIF image"
68
+ __frame = -1
69
+
70
+ def _open(self) -> None:
71
+ if not SUPPORTED:
72
+ msg = "image file could not be opened because AVIF support not installed"
73
+ raise SyntaxError(msg)
74
+
75
+ if DECODE_CODEC_CHOICE != "auto" and not _avif.decoder_codec_available(
76
+ DECODE_CODEC_CHOICE
77
+ ):
78
+ msg = "Invalid opening codec"
79
+ raise ValueError(msg)
80
+
81
+ assert self.fp is not None
82
+ self._decoder = _avif.AvifDecoder(
83
+ self.fp.read(),
84
+ DECODE_CODEC_CHOICE,
85
+ _get_default_max_threads(),
86
+ )
87
+
88
+ # Get info from decoder
89
+ self._size, self.n_frames, self._mode, icc, exif, exif_orientation, xmp = (
90
+ self._decoder.get_info()
91
+ )
92
+ self.is_animated = self.n_frames > 1
93
+
94
+ if icc:
95
+ self.info["icc_profile"] = icc
96
+ if xmp:
97
+ self.info["xmp"] = xmp
98
+
99
+ if exif_orientation != 1 or exif:
100
+ exif_data = Image.Exif()
101
+ if exif:
102
+ exif_data.load(exif)
103
+ original_orientation = exif_data.get(ExifTags.Base.Orientation, 1)
104
+ else:
105
+ original_orientation = 1
106
+ if exif_orientation != original_orientation:
107
+ exif_data[ExifTags.Base.Orientation] = exif_orientation
108
+ exif = exif_data.tobytes()
109
+ if exif:
110
+ self.info["exif"] = exif
111
+ self.seek(0)
112
+
113
+ def seek(self, frame: int) -> None:
114
+ if not self._seek_check(frame):
115
+ return
116
+
117
+ # Set tile
118
+ self.__frame = frame
119
+ self.tile = [ImageFile._Tile("raw", (0, 0) + self.size, 0, self.mode)]
120
+
121
+ def load(self) -> Image.core.PixelAccess | None:
122
+ if self.tile:
123
+ # We need to load the image data for this frame
124
+ data, timescale, pts_in_timescales, duration_in_timescales = (
125
+ self._decoder.get_frame(self.__frame)
126
+ )
127
+ self.info["timestamp"] = round(1000 * (pts_in_timescales / timescale))
128
+ self.info["duration"] = round(1000 * (duration_in_timescales / timescale))
129
+
130
+ if self.fp and self._exclusive_fp:
131
+ self.fp.close()
132
+ self.fp = BytesIO(data)
133
+
134
+ return super().load()
135
+
136
+ def load_seek(self, pos: int) -> None:
137
+ pass
138
+
139
+ def tell(self) -> int:
140
+ return self.__frame
141
+
142
+
143
+ def _save_all(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
144
+ _save(im, fp, filename, save_all=True)
145
+
146
+
147
+ def _save(
148
+ im: Image.Image, fp: IO[bytes], filename: str | bytes, save_all: bool = False
149
+ ) -> None:
150
+ info = im.encoderinfo.copy()
151
+ if save_all:
152
+ append_images = list(info.get("append_images", []))
153
+ else:
154
+ append_images = []
155
+
156
+ total = 0
157
+ for ims in [im] + append_images:
158
+ total += getattr(ims, "n_frames", 1)
159
+
160
+ quality = info.get("quality", 75)
161
+ if not isinstance(quality, int) or quality < 0 or quality > 100:
162
+ msg = "Invalid quality setting"
163
+ raise ValueError(msg)
164
+
165
+ duration = info.get("duration", 0)
166
+ subsampling = info.get("subsampling", "4:2:0")
167
+ speed = info.get("speed", 6)
168
+ max_threads = info.get("max_threads", _get_default_max_threads())
169
+ codec = info.get("codec", "auto")
170
+ if codec != "auto" and not _avif.encoder_codec_available(codec):
171
+ msg = "Invalid saving codec"
172
+ raise ValueError(msg)
173
+ range_ = info.get("range", "full")
174
+ tile_rows_log2 = info.get("tile_rows", 0)
175
+ tile_cols_log2 = info.get("tile_cols", 0)
176
+ alpha_premultiplied = bool(info.get("alpha_premultiplied", False))
177
+ autotiling = bool(info.get("autotiling", tile_rows_log2 == tile_cols_log2 == 0))
178
+
179
+ icc_profile = info.get("icc_profile", im.info.get("icc_profile"))
180
+ exif_orientation = 1
181
+ if exif := info.get("exif"):
182
+ if isinstance(exif, Image.Exif):
183
+ exif_data = exif
184
+ else:
185
+ exif_data = Image.Exif()
186
+ exif_data.load(exif)
187
+ if ExifTags.Base.Orientation in exif_data:
188
+ exif_orientation = exif_data.pop(ExifTags.Base.Orientation)
189
+ exif = exif_data.tobytes() if exif_data else b""
190
+ elif isinstance(exif, Image.Exif):
191
+ exif = exif_data.tobytes()
192
+
193
+ xmp = info.get("xmp")
194
+
195
+ if isinstance(xmp, str):
196
+ xmp = xmp.encode("utf-8")
197
+
198
+ advanced = info.get("advanced")
199
+ if advanced is not None:
200
+ if isinstance(advanced, dict):
201
+ advanced = advanced.items()
202
+ try:
203
+ advanced = tuple(advanced)
204
+ except TypeError:
205
+ invalid = True
206
+ else:
207
+ invalid = any(not isinstance(v, tuple) or len(v) != 2 for v in advanced)
208
+ if invalid:
209
+ msg = (
210
+ "advanced codec options must be a dict of key-value string "
211
+ "pairs or a series of key-value two-tuples"
212
+ )
213
+ raise ValueError(msg)
214
+
215
+ # Setup the AVIF encoder
216
+ enc = _avif.AvifEncoder(
217
+ im.size,
218
+ subsampling,
219
+ quality,
220
+ speed,
221
+ max_threads,
222
+ codec,
223
+ range_,
224
+ tile_rows_log2,
225
+ tile_cols_log2,
226
+ alpha_premultiplied,
227
+ autotiling,
228
+ icc_profile or b"",
229
+ exif or b"",
230
+ exif_orientation,
231
+ xmp or b"",
232
+ advanced,
233
+ )
234
+
235
+ # Add each frame
236
+ frame_idx = 0
237
+ frame_duration = 0
238
+ cur_idx = im.tell()
239
+ is_single_frame = total == 1
240
+ try:
241
+ for ims in [im] + append_images:
242
+ # Get number of frames in this image
243
+ nfr = getattr(ims, "n_frames", 1)
244
+
245
+ for idx in range(nfr):
246
+ ims.seek(idx)
247
+
248
+ # Make sure image mode is supported
249
+ frame = ims
250
+ rawmode = ims.mode
251
+ if ims.mode not in {"RGB", "RGBA"}:
252
+ rawmode = "RGBA" if ims.has_transparency_data else "RGB"
253
+ frame = ims.convert(rawmode)
254
+
255
+ # Update frame duration
256
+ if isinstance(duration, (list, tuple)):
257
+ frame_duration = duration[frame_idx]
258
+ else:
259
+ frame_duration = duration
260
+
261
+ # Append the frame to the animation encoder
262
+ enc.add(
263
+ frame.tobytes("raw", rawmode),
264
+ frame_duration,
265
+ frame.size,
266
+ rawmode,
267
+ is_single_frame,
268
+ )
269
+
270
+ # Update frame index
271
+ frame_idx += 1
272
+
273
+ if not save_all:
274
+ break
275
+
276
+ finally:
277
+ im.seek(cur_idx)
278
+
279
+ # Get the final output from the encoder
280
+ data = enc.finish()
281
+ if data is None:
282
+ msg = "cannot write file as AVIF (encoder returned None)"
283
+ raise OSError(msg)
284
+
285
+ fp.write(data)
286
+
287
+
288
+ Image.register_open(AvifImageFile.format, AvifImageFile, _accept)
289
+ if SUPPORTED:
290
+ Image.register_save(AvifImageFile.format, _save)
291
+ Image.register_save_all(AvifImageFile.format, _save_all)
292
+ Image.register_extensions(AvifImageFile.format, [".avif", ".avifs"])
293
+ Image.register_mime(AvifImageFile.format, "image/avif")
.venv/Lib/site-packages/PIL/BdfFontFile.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
24
+ from __future__ import annotations
25
+
26
+ from typing import BinaryIO
27
+
28
+ from . import FontFile, Image
29
+
30
+
31
+ def bdf_char(
32
+ f: BinaryIO,
33
+ ) -> (
34
+ tuple[
35
+ str,
36
+ int,
37
+ tuple[tuple[int, int], tuple[int, int, int, int], tuple[int, int, int, int]],
38
+ Image.Image,
39
+ ]
40
+ | None
41
+ ):
42
+ # skip to STARTCHAR
43
+ while True:
44
+ s = f.readline()
45
+ if not s:
46
+ return None
47
+ if s.startswith(b"STARTCHAR"):
48
+ break
49
+ id = s[9:].strip().decode("ascii")
50
+
51
+ # load symbol properties
52
+ props = {}
53
+ while True:
54
+ s = f.readline()
55
+ if not s or s.startswith(b"BITMAP"):
56
+ break
57
+ i = s.find(b" ")
58
+ props[s[:i].decode("ascii")] = s[i + 1 : -1].decode("ascii")
59
+
60
+ # load bitmap
61
+ bitmap = bytearray()
62
+ while True:
63
+ s = f.readline()
64
+ if not s or s.startswith(b"ENDCHAR"):
65
+ break
66
+ bitmap += s[:-1]
67
+
68
+ # The word BBX
69
+ # followed by the width in x (BBw), height in y (BBh),
70
+ # and x and y displacement (BBxoff0, BByoff0)
71
+ # of the lower left corner from the origin of the character.
72
+ width, height, x_disp, y_disp = (int(p) for p in props["BBX"].split())
73
+
74
+ # The word DWIDTH
75
+ # followed by the width in x and y of the character in device pixels.
76
+ dwx, dwy = (int(p) for p in props["DWIDTH"].split())
77
+
78
+ bbox = (
79
+ (dwx, dwy),
80
+ (x_disp, -y_disp - height, width + x_disp, -y_disp),
81
+ (0, 0, width, height),
82
+ )
83
+
84
+ try:
85
+ im = Image.frombytes("1", (width, height), bitmap, "hex", "1")
86
+ except ValueError:
87
+ # deal with zero-width characters
88
+ im = Image.new("1", (width, height))
89
+
90
+ return id, int(props["ENCODING"]), bbox, im
91
+
92
+
93
+ class BdfFontFile(FontFile.FontFile):
94
+ """Font file plugin for the X11 BDF format."""
95
+
96
+ def __init__(self, fp: BinaryIO) -> None:
97
+ super().__init__()
98
+
99
+ s = fp.readline()
100
+ if not s.startswith(b"STARTFONT 2.1"):
101
+ msg = "not a valid BDF file"
102
+ raise SyntaxError(msg)
103
+
104
+ props = {}
105
+ comments = []
106
+
107
+ while True:
108
+ s = fp.readline()
109
+ if not s or s.startswith(b"ENDPROPERTIES"):
110
+ break
111
+ i = s.find(b" ")
112
+ props[s[:i].decode("ascii")] = s[i + 1 : -1].decode("ascii")
113
+ if s[:i] in [b"COMMENT", b"COPYRIGHT"]:
114
+ if s.find(b"LogicalFontDescription") < 0:
115
+ comments.append(s[i + 1 : -1].decode("ascii"))
116
+
117
+ while True:
118
+ c = bdf_char(fp)
119
+ if not c:
120
+ break
121
+ id, ch, (xy, dst, src), im = c
122
+ if 0 <= ch < len(self.glyph):
123
+ self.glyph[ch] = xy, dst, src, im
.venv/Lib/site-packages/PIL/BlpImagePlugin.py ADDED
@@ -0,0 +1,498 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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C0)
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 abc
35
+ import os
36
+ import struct
37
+ from enum import IntEnum
38
+ from io import BytesIO
39
+ from typing import IO
40
+
41
+ from . import Image, ImageFile
42
+
43
+
44
+ class Format(IntEnum):
45
+ JPEG = 0
46
+
47
+
48
+ class Encoding(IntEnum):
49
+ UNCOMPRESSED = 1
50
+ DXT = 2
51
+ UNCOMPRESSED_RAW_BGRA = 3
52
+
53
+
54
+ class AlphaEncoding(IntEnum):
55
+ DXT1 = 0
56
+ DXT3 = 1
57
+ DXT5 = 7
58
+
59
+
60
+ def unpack_565(i: int) -> tuple[int, int, int]:
61
+ return ((i >> 11) & 0x1F) << 3, ((i >> 5) & 0x3F) << 2, (i & 0x1F) << 3
62
+
63
+
64
+ def decode_dxt1(
65
+ data: bytes, alpha: bool = False
66
+ ) -> tuple[bytearray, bytearray, bytearray, bytearray]:
67
+ """
68
+ input: one "row" of data (i.e. will produce 4*width pixels)
69
+ """
70
+
71
+ blocks = len(data) // 8 # number of blocks in row
72
+ ret = (bytearray(), bytearray(), bytearray(), bytearray())
73
+
74
+ for block_index in range(blocks):
75
+ # Decode next 8-byte block.
76
+ idx = block_index * 8
77
+ color0, color1, bits = struct.unpack_from("<HHI", data, idx)
78
+
79
+ r0, g0, b0 = unpack_565(color0)
80
+ r1, g1, b1 = unpack_565(color1)
81
+
82
+ # Decode this block into 4x4 pixels
83
+ # Accumulate the results onto our 4 row accumulators
84
+ for j in range(4):
85
+ for i in range(4):
86
+ # get next control op and generate a pixel
87
+
88
+ control = bits & 3
89
+ bits = bits >> 2
90
+
91
+ a = 0xFF
92
+ if control == 0:
93
+ r, g, b = r0, g0, b0
94
+ elif control == 1:
95
+ r, g, b = r1, g1, b1
96
+ elif control == 2:
97
+ if color0 > color1:
98
+ r = (2 * r0 + r1) // 3
99
+ g = (2 * g0 + g1) // 3
100
+ b = (2 * b0 + b1) // 3
101
+ else:
102
+ r = (r0 + r1) // 2
103
+ g = (g0 + g1) // 2
104
+ b = (b0 + b1) // 2
105
+ elif control == 3:
106
+ if color0 > color1:
107
+ r = (2 * r1 + r0) // 3
108
+ g = (2 * g1 + g0) // 3
109
+ b = (2 * b1 + b0) // 3
110
+ else:
111
+ r, g, b, a = 0, 0, 0, 0
112
+
113
+ if alpha:
114
+ ret[j].extend([r, g, b, a])
115
+ else:
116
+ ret[j].extend([r, g, b])
117
+
118
+ return ret
119
+
120
+
121
+ def decode_dxt3(data: bytes) -> tuple[bytearray, bytearray, bytearray, bytearray]:
122
+ """
123
+ input: one "row" of data (i.e. will produce 4*width pixels)
124
+ """
125
+
126
+ blocks = len(data) // 16 # number of blocks in row
127
+ ret = (bytearray(), bytearray(), bytearray(), bytearray())
128
+
129
+ for block_index in range(blocks):
130
+ idx = block_index * 16
131
+ block = data[idx : idx + 16]
132
+ # Decode next 16-byte block.
133
+ bits = struct.unpack_from("<8B", block)
134
+ color0, color1 = struct.unpack_from("<HH", block, 8)
135
+
136
+ (code,) = struct.unpack_from("<I", block, 12)
137
+
138
+ r0, g0, b0 = unpack_565(color0)
139
+ r1, g1, b1 = unpack_565(color1)
140
+
141
+ for j in range(4):
142
+ high = False # Do we want the higher bits?
143
+ for i in range(4):
144
+ alphacode_index = (4 * j + i) // 2
145
+ a = bits[alphacode_index]
146
+ if high:
147
+ high = False
148
+ a >>= 4
149
+ else:
150
+ high = True
151
+ a &= 0xF
152
+ a *= 17 # We get a value between 0 and 15
153
+
154
+ color_code = (code >> 2 * (4 * j + i)) & 0x03
155
+
156
+ if color_code == 0:
157
+ r, g, b = r0, g0, b0
158
+ elif color_code == 1:
159
+ r, g, b = r1, g1, b1
160
+ elif color_code == 2:
161
+ r = (2 * r0 + r1) // 3
162
+ g = (2 * g0 + g1) // 3
163
+ b = (2 * b0 + b1) // 3
164
+ elif color_code == 3:
165
+ r = (2 * r1 + r0) // 3
166
+ g = (2 * g1 + g0) // 3
167
+ b = (2 * b1 + b0) // 3
168
+
169
+ ret[j].extend([r, g, b, a])
170
+
171
+ return ret
172
+
173
+
174
+ def decode_dxt5(data: bytes) -> tuple[bytearray, bytearray, bytearray, bytearray]:
175
+ """
176
+ input: one "row" of data (i.e. will produce 4 * width pixels)
177
+ """
178
+
179
+ blocks = len(data) // 16 # number of blocks in row
180
+ ret = (bytearray(), bytearray(), bytearray(), bytearray())
181
+
182
+ for block_index in range(blocks):
183
+ idx = block_index * 16
184
+ block = data[idx : idx + 16]
185
+ # Decode next 16-byte block.
186
+ a0, a1 = struct.unpack_from("<BB", block)
187
+
188
+ bits = struct.unpack_from("<6B", block, 2)
189
+ alphacode1 = bits[2] | (bits[3] << 8) | (bits[4] << 16) | (bits[5] << 24)
190
+ alphacode2 = bits[0] | (bits[1] << 8)
191
+
192
+ color0, color1 = struct.unpack_from("<HH", block, 8)
193
+
194
+ (code,) = struct.unpack_from("<I", block, 12)
195
+
196
+ r0, g0, b0 = unpack_565(color0)
197
+ r1, g1, b1 = unpack_565(color1)
198
+
199
+ for j in range(4):
200
+ for i in range(4):
201
+ # get next control op and generate a pixel
202
+ alphacode_index = 3 * (4 * j + i)
203
+
204
+ if alphacode_index <= 12:
205
+ alphacode = (alphacode2 >> alphacode_index) & 0x07
206
+ elif alphacode_index == 15:
207
+ alphacode = (alphacode2 >> 15) | ((alphacode1 << 1) & 0x06)
208
+ else: # alphacode_index >= 18 and alphacode_index <= 45
209
+ alphacode = (alphacode1 >> (alphacode_index - 16)) & 0x07
210
+
211
+ if alphacode == 0:
212
+ a = a0
213
+ elif alphacode == 1:
214
+ a = a1
215
+ elif a0 > a1:
216
+ a = ((8 - alphacode) * a0 + (alphacode - 1) * a1) // 7
217
+ elif alphacode == 6:
218
+ a = 0
219
+ elif alphacode == 7:
220
+ a = 255
221
+ else:
222
+ a = ((6 - alphacode) * a0 + (alphacode - 1) * a1) // 5
223
+
224
+ color_code = (code >> 2 * (4 * j + i)) & 0x03
225
+
226
+ if color_code == 0:
227
+ r, g, b = r0, g0, b0
228
+ elif color_code == 1:
229
+ r, g, b = r1, g1, b1
230
+ elif color_code == 2:
231
+ r = (2 * r0 + r1) // 3
232
+ g = (2 * g0 + g1) // 3
233
+ b = (2 * b0 + b1) // 3
234
+ elif color_code == 3:
235
+ r = (2 * r1 + r0) // 3
236
+ g = (2 * g1 + g0) // 3
237
+ b = (2 * b1 + b0) // 3
238
+
239
+ ret[j].extend([r, g, b, a])
240
+
241
+ return ret
242
+
243
+
244
+ class BLPFormatError(NotImplementedError):
245
+ pass
246
+
247
+
248
+ def _accept(prefix: bytes) -> bool:
249
+ return prefix.startswith((b"BLP1", b"BLP2"))
250
+
251
+
252
+ class BlpImageFile(ImageFile.ImageFile):
253
+ """
254
+ Blizzard Mipmap Format
255
+ """
256
+
257
+ format = "BLP"
258
+ format_description = "Blizzard Mipmap Format"
259
+
260
+ def _open(self) -> None:
261
+ assert self.fp is not None
262
+ self.magic = self.fp.read(4)
263
+ if not _accept(self.magic):
264
+ msg = f"Bad BLP magic {repr(self.magic)}"
265
+ raise BLPFormatError(msg)
266
+
267
+ compression = struct.unpack("<i", self.fp.read(4))[0]
268
+ if self.magic == b"BLP1":
269
+ alpha = struct.unpack("<I", self.fp.read(4))[0] != 0
270
+ else:
271
+ encoding = struct.unpack("<b", self.fp.read(1))[0]
272
+ alpha = struct.unpack("<b", self.fp.read(1))[0] != 0
273
+ alpha_encoding = struct.unpack("<b", self.fp.read(1))[0]
274
+ self.fp.seek(1, os.SEEK_CUR) # mips
275
+
276
+ self._size = struct.unpack("<II", self.fp.read(8))
277
+
278
+ args: tuple[int, int, bool] | tuple[int, int, bool, int]
279
+ if self.magic == b"BLP1":
280
+ encoding = struct.unpack("<i", self.fp.read(4))[0]
281
+ self.fp.seek(4, os.SEEK_CUR) # subtype
282
+
283
+ args = (compression, encoding, alpha)
284
+ offset = 28
285
+ else:
286
+ args = (compression, encoding, alpha, alpha_encoding)
287
+ offset = 20
288
+
289
+ decoder = self.magic.decode()
290
+
291
+ self._mode = "RGBA" if alpha else "RGB"
292
+ self.tile = [ImageFile._Tile(decoder, (0, 0) + self.size, offset, args)]
293
+
294
+
295
+ class _BLPBaseDecoder(abc.ABC, ImageFile.PyDecoder):
296
+ _pulls_fd = True
297
+
298
+ def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:
299
+ try:
300
+ self._read_header()
301
+ self._load()
302
+ except struct.error as e:
303
+ msg = "Truncated BLP file"
304
+ raise OSError(msg) from e
305
+ return -1, 0
306
+
307
+ @abc.abstractmethod
308
+ def _load(self) -> None:
309
+ pass
310
+
311
+ def _read_header(self) -> None:
312
+ self._offsets = struct.unpack("<16I", self._safe_read(16 * 4))
313
+ self._lengths = struct.unpack("<16I", self._safe_read(16 * 4))
314
+
315
+ def _safe_read(self, length: int) -> bytes:
316
+ assert self.fd is not None
317
+ return ImageFile._safe_read(self.fd, length)
318
+
319
+ def _read_palette(self) -> list[tuple[int, int, int, int]]:
320
+ ret = []
321
+ for i in range(256):
322
+ try:
323
+ b, g, r, a = struct.unpack("<4B", self._safe_read(4))
324
+ except struct.error:
325
+ break
326
+ ret.append((b, g, r, a))
327
+ return ret
328
+
329
+ def _read_bgra(
330
+ self, palette: list[tuple[int, int, int, int]], alpha: bool
331
+ ) -> bytearray:
332
+ data = bytearray()
333
+ _data = BytesIO(self._safe_read(self._lengths[0]))
334
+ while True:
335
+ try:
336
+ (offset,) = struct.unpack("<B", _data.read(1))
337
+ except struct.error:
338
+ break
339
+ b, g, r, a = palette[offset]
340
+ d: tuple[int, ...] = (r, g, b)
341
+ if alpha:
342
+ d += (a,)
343
+ data.extend(d)
344
+ return data
345
+
346
+
347
+ class BLP1Decoder(_BLPBaseDecoder):
348
+ def _load(self) -> None:
349
+ self._compression, self._encoding, alpha = self.args
350
+
351
+ if self._compression == Format.JPEG:
352
+ self._decode_jpeg_stream()
353
+
354
+ elif self._compression == 1:
355
+ if self._encoding in (4, 5):
356
+ palette = self._read_palette()
357
+ data = self._read_bgra(palette, alpha)
358
+ self.set_as_raw(data)
359
+ else:
360
+ msg = f"Unsupported BLP encoding {repr(self._encoding)}"
361
+ raise BLPFormatError(msg)
362
+ else:
363
+ msg = f"Unsupported BLP compression {repr(self._encoding)}"
364
+ raise BLPFormatError(msg)
365
+
366
+ def _decode_jpeg_stream(self) -> None:
367
+ from .JpegImagePlugin import JpegImageFile
368
+
369
+ (jpeg_header_size,) = struct.unpack("<I", self._safe_read(4))
370
+ jpeg_header = self._safe_read(jpeg_header_size)
371
+ assert self.fd is not None
372
+ self._safe_read(self._offsets[0] - self.fd.tell()) # What IS this?
373
+ data = self._safe_read(self._lengths[0])
374
+ data = jpeg_header + data
375
+ image = JpegImageFile(BytesIO(data))
376
+ Image._decompression_bomb_check(image.size)
377
+ if image.mode == "CMYK":
378
+ args = image.tile[0].args
379
+ assert isinstance(args, tuple)
380
+ image.tile = [image.tile[0]._replace(args=(args[0], "CMYK"))]
381
+ self.set_as_raw(image.convert("RGB").tobytes(), "BGR")
382
+
383
+
384
+ class BLP2Decoder(_BLPBaseDecoder):
385
+ def _load(self) -> None:
386
+ self._compression, self._encoding, alpha, self._alpha_encoding = self.args
387
+
388
+ palette = self._read_palette()
389
+
390
+ assert self.fd is not None
391
+ self.fd.seek(self._offsets[0])
392
+
393
+ if self._compression == 1:
394
+ # Uncompressed or DirectX compression
395
+
396
+ if self._encoding == Encoding.UNCOMPRESSED:
397
+ data = self._read_bgra(palette, alpha)
398
+
399
+ elif self._encoding == Encoding.DXT:
400
+ data = bytearray()
401
+ if self._alpha_encoding == AlphaEncoding.DXT1:
402
+ linesize = (self.state.xsize + 3) // 4 * 8
403
+ for yb in range((self.state.ysize + 3) // 4):
404
+ for d in decode_dxt1(self._safe_read(linesize), alpha):
405
+ data += d
406
+
407
+ elif self._alpha_encoding == AlphaEncoding.DXT3:
408
+ linesize = (self.state.xsize + 3) // 4 * 16
409
+ for yb in range((self.state.ysize + 3) // 4):
410
+ for d in decode_dxt3(self._safe_read(linesize)):
411
+ data += d
412
+
413
+ elif self._alpha_encoding == AlphaEncoding.DXT5:
414
+ linesize = (self.state.xsize + 3) // 4 * 16
415
+ for yb in range((self.state.ysize + 3) // 4):
416
+ for d in decode_dxt5(self._safe_read(linesize)):
417
+ data += d
418
+ else:
419
+ msg = f"Unsupported alpha encoding {repr(self._alpha_encoding)}"
420
+ raise BLPFormatError(msg)
421
+ else:
422
+ msg = f"Unknown BLP encoding {repr(self._encoding)}"
423
+ raise BLPFormatError(msg)
424
+
425
+ else:
426
+ msg = f"Unknown BLP compression {repr(self._compression)}"
427
+ raise BLPFormatError(msg)
428
+
429
+ self.set_as_raw(data)
430
+
431
+
432
+ class BLPEncoder(ImageFile.PyEncoder):
433
+ _pushes_fd = True
434
+
435
+ def _write_palette(self) -> bytes:
436
+ data = b""
437
+ assert self.im is not None
438
+ palette = self.im.getpalette("RGBA", "RGBA")
439
+ for i in range(len(palette) // 4):
440
+ r, g, b, a = palette[i * 4 : (i + 1) * 4]
441
+ data += struct.pack("<4B", b, g, r, a)
442
+ while len(data) < 256 * 4:
443
+ data += b"\x00" * 4
444
+ return data
445
+
446
+ def encode(self, bufsize: int) -> tuple[int, int, bytes]:
447
+ palette_data = self._write_palette()
448
+
449
+ offset = 20 + 16 * 4 * 2 + len(palette_data)
450
+ data = struct.pack("<16I", offset, *((0,) * 15))
451
+
452
+ assert self.im is not None
453
+ w, h = self.im.size
454
+ data += struct.pack("<16I", w * h, *((0,) * 15))
455
+
456
+ data += palette_data
457
+
458
+ for y in range(h):
459
+ for x in range(w):
460
+ data += struct.pack("<B", self.im.getpixel((x, y)))
461
+
462
+ return len(data), 0, data
463
+
464
+
465
+ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
466
+ if im.mode != "P":
467
+ msg = "Unsupported BLP image mode"
468
+ raise ValueError(msg)
469
+
470
+ magic = b"BLP1" if im.encoderinfo.get("blp_version") == "BLP1" else b"BLP2"
471
+ fp.write(magic)
472
+
473
+ assert im.palette is not None
474
+ fp.write(struct.pack("<i", 1)) # Uncompressed or DirectX compression
475
+
476
+ alpha_depth = 1 if im.palette.mode == "RGBA" else 0
477
+ if magic == b"BLP1":
478
+ fp.write(struct.pack("<L", alpha_depth))
479
+ else:
480
+ fp.write(struct.pack("<b", Encoding.UNCOMPRESSED))
481
+ fp.write(struct.pack("<b", alpha_depth))
482
+ fp.write(struct.pack("<b", 0)) # alpha encoding
483
+ fp.write(struct.pack("<b", 0)) # mips
484
+ fp.write(struct.pack("<II", *im.size))
485
+ if magic == b"BLP1":
486
+ fp.write(struct.pack("<i", 5))
487
+ fp.write(struct.pack("<i", 0))
488
+
489
+ ImageFile._save(im, fp, [ImageFile._Tile("BLP", (0, 0) + im.size, 0, im.mode)])
490
+
491
+
492
+ Image.register_open(BlpImageFile.format, BlpImageFile, _accept)
493
+ Image.register_extension(BlpImageFile.format, ".blp")
494
+ Image.register_decoder("BLP1", BLP1Decoder)
495
+ Image.register_decoder("BLP2", BLP2Decoder)
496
+
497
+ Image.register_save(BlpImageFile.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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from typing import IO, Any
29
+
30
+ from . import Image, ImageFile, ImagePalette
31
+ from ._binary import i16le as i16
32
+ from ._binary import i32le as i32
33
+ from ._binary import o8
34
+ from ._binary import o16le as o16
35
+ from ._binary import o32le as o32
36
+
37
+ #
38
+ # --------------------------------------------------------------------
39
+ # Read BMP file
40
+
41
+ BIT2MODE = {
42
+ # bits => mode, rawmode
43
+ 1: ("P", "P;1"),
44
+ 4: ("P", "P;4"),
45
+ 8: ("P", "P"),
46
+ 16: ("RGB", "BGR;15"),
47
+ 24: ("RGB", "BGR"),
48
+ 32: ("RGB", "BGRX"),
49
+ }
50
+
51
+ USE_RAW_ALPHA = False
52
+
53
+
54
+ def _accept(prefix: bytes) -> bool:
55
+ return prefix.startswith(b"BM")
56
+
57
+
58
+ def _dib_accept(prefix: bytes) -> bool:
59
+ return i32(prefix) in [12, 40, 52, 56, 64, 108, 124]
60
+
61
+
62
+ # =============================================================================
63
+ # Image plugin for the Windows BMP format.
64
+ # =============================================================================
65
+ class BmpImageFile(ImageFile.ImageFile):
66
+ """Image plugin for the Windows Bitmap format (BMP)"""
67
+
68
+ # ------------------------------------------------------------- Description
69
+ format_description = "Windows Bitmap"
70
+ format = "BMP"
71
+
72
+ # -------------------------------------------------- BMP Compression values
73
+ COMPRESSIONS = {"RAW": 0, "RLE8": 1, "RLE4": 2, "BITFIELDS": 3, "JPEG": 4, "PNG": 5}
74
+ for k, v in COMPRESSIONS.items():
75
+ vars()[k] = v
76
+
77
+ def _bitmap(self, header: int = 0, offset: int = 0) -> None:
78
+ """Read relevant info about the BMP"""
79
+ assert self.fp is not None
80
+ read, seek = self.fp.read, self.fp.seek
81
+ if header:
82
+ seek(header)
83
+ # read bmp header size @offset 14 (this is part of the header size)
84
+ file_info: dict[str, bool | int | tuple[int, ...]] = {
85
+ "header_size": i32(read(4)),
86
+ "direction": -1,
87
+ }
88
+
89
+ # -------------------- If requested, read header at a specific position
90
+ # read the rest of the bmp header, without its size
91
+ assert isinstance(file_info["header_size"], int)
92
+ header_data = ImageFile._safe_read(self.fp, file_info["header_size"] - 4)
93
+
94
+ # ------------------------------- Windows Bitmap v2, IBM OS/2 Bitmap v1
95
+ # ----- This format has different offsets because of width/height types
96
+ # 12: BITMAPCOREHEADER/OS21XBITMAPHEADER
97
+ if file_info["header_size"] == 12:
98
+ file_info["width"] = i16(header_data, 0)
99
+ file_info["height"] = i16(header_data, 2)
100
+ file_info["planes"] = i16(header_data, 4)
101
+ file_info["bits"] = i16(header_data, 6)
102
+ file_info["compression"] = self.COMPRESSIONS["RAW"]
103
+ file_info["palette_padding"] = 3
104
+
105
+ # --------------------------------------------- Windows Bitmap v3 to v5
106
+ # 40: BITMAPINFOHEADER
107
+ # 52: BITMAPV2HEADER
108
+ # 56: BITMAPV3HEADER
109
+ # 64: BITMAPCOREHEADER2/OS22XBITMAPHEADER
110
+ # 108: BITMAPV4HEADER
111
+ # 124: BITMAPV5HEADER
112
+ elif file_info["header_size"] in (40, 52, 56, 64, 108, 124):
113
+ file_info["y_flip"] = header_data[7] == 0xFF
114
+ file_info["direction"] = 1 if file_info["y_flip"] else -1
115
+ file_info["width"] = i32(header_data, 0)
116
+ file_info["height"] = (
117
+ i32(header_data, 4)
118
+ if not file_info["y_flip"]
119
+ else 2**32 - i32(header_data, 4)
120
+ )
121
+ file_info["planes"] = i16(header_data, 8)
122
+ file_info["bits"] = i16(header_data, 10)
123
+ file_info["compression"] = i32(header_data, 12)
124
+ # byte size of pixel data
125
+ file_info["data_size"] = i32(header_data, 16)
126
+ file_info["pixels_per_meter"] = (
127
+ i32(header_data, 20),
128
+ i32(header_data, 24),
129
+ )
130
+ file_info["colors"] = i32(header_data, 28)
131
+ file_info["palette_padding"] = 4
132
+ assert isinstance(file_info["pixels_per_meter"], tuple)
133
+ self.info["dpi"] = tuple(x / 39.3701 for x in file_info["pixels_per_meter"])
134
+ if file_info["compression"] == self.COMPRESSIONS["BITFIELDS"]:
135
+ masks = ["r_mask", "g_mask", "b_mask"]
136
+ if len(header_data) >= 48:
137
+ if len(header_data) >= 52:
138
+ masks.append("a_mask")
139
+ else:
140
+ file_info["a_mask"] = 0x0
141
+ for idx, mask in enumerate(masks):
142
+ file_info[mask] = i32(header_data, 36 + idx * 4)
143
+ else:
144
+ # 40 byte headers only have the three components in the
145
+ # bitfields masks, ref:
146
+ # https://msdn.microsoft.com/en-us/library/windows/desktop/dd183376(v=vs.85).aspx
147
+ # See also
148
+ # https://github.com/python-pillow/Pillow/issues/1293
149
+ # There is a 4th component in the RGBQuad, in the alpha
150
+ # location, but it is listed as a reserved component,
151
+ # and it is not generally an alpha channel
152
+ file_info["a_mask"] = 0x0
153
+ for mask in masks:
154
+ file_info[mask] = i32(read(4))
155
+ assert isinstance(file_info["r_mask"], int)
156
+ assert isinstance(file_info["g_mask"], int)
157
+ assert isinstance(file_info["b_mask"], int)
158
+ assert isinstance(file_info["a_mask"], int)
159
+ file_info["rgb_mask"] = (
160
+ file_info["r_mask"],
161
+ file_info["g_mask"],
162
+ file_info["b_mask"],
163
+ )
164
+ file_info["rgba_mask"] = (
165
+ file_info["r_mask"],
166
+ file_info["g_mask"],
167
+ file_info["b_mask"],
168
+ file_info["a_mask"],
169
+ )
170
+ else:
171
+ msg = f"Unsupported BMP header type ({file_info['header_size']})"
172
+ raise OSError(msg)
173
+
174
+ # ------------------ Special case : header is reported 40, which
175
+ # ---------------------- is shorter than real size for bpp >= 16
176
+ assert isinstance(file_info["width"], int)
177
+ assert isinstance(file_info["height"], int)
178
+ self._size = file_info["width"], file_info["height"]
179
+
180
+ # ------- If color count was not found in the header, compute from bits
181
+ assert isinstance(file_info["bits"], int)
182
+ if not file_info.get("colors", 0):
183
+ file_info["colors"] = 1 << file_info["bits"]
184
+ assert isinstance(file_info["palette_padding"], int)
185
+ assert isinstance(file_info["colors"], int)
186
+ if offset == 14 + file_info["header_size"] and file_info["bits"] <= 8:
187
+ offset += file_info["palette_padding"] * file_info["colors"]
188
+
189
+ # ---------------------- Check bit depth for unusual unsupported values
190
+ self._mode, raw_mode = BIT2MODE.get(file_info["bits"], ("", ""))
191
+ if not self.mode:
192
+ msg = f"Unsupported BMP pixel depth ({file_info['bits']})"
193
+ raise OSError(msg)
194
+
195
+ # ---------------- Process BMP with Bitfields compression (not palette)
196
+ decoder_name = "raw"
197
+ if file_info["compression"] == self.COMPRESSIONS["BITFIELDS"]:
198
+ SUPPORTED: dict[int, list[tuple[int, ...]]] = {
199
+ 32: [
200
+ (0xFF0000, 0xFF00, 0xFF, 0x0),
201
+ (0xFF000000, 0xFF0000, 0xFF00, 0x0),
202
+ (0xFF000000, 0xFF00, 0xFF, 0x0),
203
+ (0xFF000000, 0xFF0000, 0xFF00, 0xFF),
204
+ (0xFF, 0xFF00, 0xFF0000, 0xFF000000),
205
+ (0xFF0000, 0xFF00, 0xFF, 0xFF000000),
206
+ (0xFF000000, 0xFF00, 0xFF, 0xFF0000),
207
+ (0x0, 0x0, 0x0, 0x0),
208
+ ],
209
+ 24: [(0xFF0000, 0xFF00, 0xFF)],
210
+ 16: [(0xF800, 0x7E0, 0x1F), (0x7C00, 0x3E0, 0x1F)],
211
+ }
212
+ MASK_MODES = {
213
+ (32, (0xFF0000, 0xFF00, 0xFF, 0x0)): "BGRX",
214
+ (32, (0xFF000000, 0xFF0000, 0xFF00, 0x0)): "XBGR",
215
+ (32, (0xFF000000, 0xFF00, 0xFF, 0x0)): "BGXR",
216
+ (32, (0xFF000000, 0xFF0000, 0xFF00, 0xFF)): "ABGR",
217
+ (32, (0xFF, 0xFF00, 0xFF0000, 0xFF000000)): "RGBA",
218
+ (32, (0xFF0000, 0xFF00, 0xFF, 0xFF000000)): "BGRA",
219
+ (32, (0xFF000000, 0xFF00, 0xFF, 0xFF0000)): "BGAR",
220
+ (32, (0x0, 0x0, 0x0, 0x0)): "BGRA",
221
+ (24, (0xFF0000, 0xFF00, 0xFF)): "BGR",
222
+ (16, (0xF800, 0x7E0, 0x1F)): "BGR;16",
223
+ (16, (0x7C00, 0x3E0, 0x1F)): "BGR;15",
224
+ }
225
+ if file_info["bits"] in SUPPORTED:
226
+ if (
227
+ file_info["bits"] == 32
228
+ and file_info["rgba_mask"] in SUPPORTED[file_info["bits"]]
229
+ ):
230
+ assert isinstance(file_info["rgba_mask"], tuple)
231
+ raw_mode = MASK_MODES[(file_info["bits"], file_info["rgba_mask"])]
232
+ self._mode = "RGBA" if "A" in raw_mode else self.mode
233
+ elif (
234
+ file_info["bits"] in (24, 16)
235
+ and file_info["rgb_mask"] in SUPPORTED[file_info["bits"]]
236
+ ):
237
+ assert isinstance(file_info["rgb_mask"], tuple)
238
+ raw_mode = MASK_MODES[(file_info["bits"], file_info["rgb_mask"])]
239
+ else:
240
+ msg = "Unsupported BMP bitfields layout"
241
+ raise OSError(msg)
242
+ else:
243
+ msg = "Unsupported BMP bitfields layout"
244
+ raise OSError(msg)
245
+ elif file_info["compression"] == self.COMPRESSIONS["RAW"]:
246
+ if file_info["bits"] == 32 and (
247
+ header == 22 or USE_RAW_ALPHA # 32-bit .cur offset
248
+ ):
249
+ raw_mode, self._mode = "BGRA", "RGBA"
250
+ elif file_info["compression"] in (
251
+ self.COMPRESSIONS["RLE8"],
252
+ self.COMPRESSIONS["RLE4"],
253
+ ):
254
+ decoder_name = "bmp_rle"
255
+ else:
256
+ msg = f"Unsupported BMP compression ({file_info['compression']})"
257
+ raise OSError(msg)
258
+
259
+ # --------------- Once the header is processed, process the palette/LUT
260
+ if self.mode == "P": # Paletted for 1, 4 and 8 bit images
261
+ # ---------------------------------------------------- 1-bit images
262
+ if not (0 < file_info["colors"] <= 65536):
263
+ msg = f"Unsupported BMP Palette size ({file_info['colors']})"
264
+ raise OSError(msg)
265
+ else:
266
+ padding = file_info["palette_padding"]
267
+ palette = read(padding * file_info["colors"])
268
+ grayscale = True
269
+ indices = (
270
+ (0, 255)
271
+ if file_info["colors"] == 2
272
+ else list(range(file_info["colors"]))
273
+ )
274
+
275
+ # ----------------- Check if grayscale and ignore palette if so
276
+ for ind, val in enumerate(indices):
277
+ rgb = palette[ind * padding : ind * padding + 3]
278
+ if rgb != o8(val) * 3:
279
+ grayscale = False
280
+
281
+ # ------- If all colors are gray, white or black, ditch palette
282
+ if grayscale:
283
+ self._mode = "1" if file_info["colors"] == 2 else "L"
284
+ raw_mode = self.mode
285
+ else:
286
+ self._mode = "P"
287
+ self.palette = ImagePalette.raw(
288
+ "BGRX" if padding == 4 else "BGR", palette
289
+ )
290
+
291
+ # ---------------------------- Finally set the tile data for the plugin
292
+ self.info["compression"] = file_info["compression"]
293
+ args: list[Any] = [raw_mode]
294
+ if decoder_name == "bmp_rle":
295
+ args.append(file_info["compression"] == self.COMPRESSIONS["RLE4"])
296
+ else:
297
+ assert isinstance(file_info["width"], int)
298
+ args.append(((file_info["width"] * file_info["bits"] + 31) >> 3) & (~3))
299
+ args.append(file_info["direction"])
300
+ self.tile = [
301
+ ImageFile._Tile(
302
+ decoder_name,
303
+ (0, 0, file_info["width"], file_info["height"]),
304
+ offset or self.fp.tell(),
305
+ tuple(args),
306
+ )
307
+ ]
308
+
309
+ def _open(self) -> None:
310
+ """Open file, check magic number and read header"""
311
+ # read 14 bytes: magic number, filesize, reserved, header final offset
312
+ assert self.fp is not None
313
+ head_data = self.fp.read(14)
314
+ # choke if the file does not have the required magic bytes
315
+ if not _accept(head_data):
316
+ msg = "Not a BMP file"
317
+ raise SyntaxError(msg)
318
+ # read the start position of the BMP image data (u32)
319
+ offset = i32(head_data, 10)
320
+ # load bitmap information (offset=raster info)
321
+ self._bitmap(offset=offset)
322
+
323
+
324
+ class BmpRleDecoder(ImageFile.PyDecoder):
325
+ _pulls_fd = True
326
+
327
+ def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:
328
+ assert self.fd is not None
329
+ rle4 = self.args[1]
330
+ data = bytearray()
331
+ x = 0
332
+ dest_length = self.state.xsize * self.state.ysize
333
+ while len(data) < dest_length:
334
+ pixels = self.fd.read(1)
335
+ byte = self.fd.read(1)
336
+ if not pixels or not byte:
337
+ break
338
+ num_pixels = pixels[0]
339
+ if num_pixels:
340
+ # encoded mode
341
+ if x + num_pixels > self.state.xsize:
342
+ # Too much data for row
343
+ num_pixels = max(0, self.state.xsize - x)
344
+ if rle4:
345
+ first_pixel = o8(byte[0] >> 4)
346
+ second_pixel = o8(byte[0] & 0x0F)
347
+ for index in range(num_pixels):
348
+ if index % 2 == 0:
349
+ data += first_pixel
350
+ else:
351
+ data += second_pixel
352
+ else:
353
+ data += byte * num_pixels
354
+ x += num_pixels
355
+ else:
356
+ if byte[0] == 0:
357
+ # end of line
358
+ while len(data) % self.state.xsize != 0:
359
+ data += b"\x00"
360
+ x = 0
361
+ elif byte[0] == 1:
362
+ # end of bitmap
363
+ break
364
+ elif byte[0] == 2:
365
+ # delta
366
+ bytes_read = self.fd.read(2)
367
+ if len(bytes_read) < 2:
368
+ break
369
+ right, up = bytes_read
370
+ data += b"\x00" * (right + up * self.state.xsize)
371
+ x = len(data) % self.state.xsize
372
+ else:
373
+ # absolute mode
374
+ if rle4:
375
+ # 2 pixels per byte
376
+ byte_count = byte[0] // 2
377
+ bytes_read = self.fd.read(byte_count)
378
+ for byte_read in bytes_read:
379
+ data += o8(byte_read >> 4)
380
+ data += o8(byte_read & 0x0F)
381
+ else:
382
+ byte_count = byte[0]
383
+ bytes_read = self.fd.read(byte_count)
384
+ data += bytes_read
385
+ if len(bytes_read) < byte_count:
386
+ break
387
+ x += byte[0]
388
+
389
+ # align to 16-bit word boundary
390
+ if self.fd.tell() % 2 != 0:
391
+ self.fd.seek(1, os.SEEK_CUR)
392
+ rawmode = "L" if self.mode == "L" else "P"
393
+ self.set_as_raw(bytes(data), rawmode, (0, self.args[-1]))
394
+ return -1, 0
395
+
396
+
397
+ # =============================================================================
398
+ # Image plugin for the DIB format (BMP alias)
399
+ # =============================================================================
400
+ class DibImageFile(BmpImageFile):
401
+ format = "DIB"
402
+ format_description = "Windows Bitmap"
403
+
404
+ def _open(self) -> None:
405
+ self._bitmap()
406
+
407
+
408
+ #
409
+ # --------------------------------------------------------------------
410
+ # Write BMP file
411
+
412
+
413
+ SAVE = {
414
+ "1": ("1", 1, 2),
415
+ "L": ("L", 8, 256),
416
+ "P": ("P", 8, 256),
417
+ "RGB": ("BGR", 24, 0),
418
+ "RGBA": ("BGRA", 32, 0),
419
+ }
420
+
421
+
422
+ def _dib_save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
423
+ _save(im, fp, filename, False)
424
+
425
+
426
+ def _save(
427
+ im: Image.Image, fp: IO[bytes], filename: str | bytes, bitmap_header: bool = True
428
+ ) -> None:
429
+ try:
430
+ rawmode, bits, colors = SAVE[im.mode]
431
+ except KeyError as e:
432
+ msg = f"cannot write mode {im.mode} as BMP"
433
+ raise OSError(msg) from e
434
+
435
+ info = im.encoderinfo
436
+
437
+ dpi = info.get("dpi", (96, 96))
438
+
439
+ # 1 meter == 39.3701 inches
440
+ ppm = tuple(int(x * 39.3701 + 0.5) for x in dpi)
441
+
442
+ stride = ((im.size[0] * bits + 7) // 8 + 3) & (~3)
443
+ header = 40 # or 64 for OS/2 version 2
444
+ image = stride * im.size[1]
445
+
446
+ if im.mode == "1":
447
+ palette = b"".join(o8(i) * 3 + b"\x00" for i in (0, 255))
448
+ elif im.mode == "L":
449
+ palette = b"".join(o8(i) * 3 + b"\x00" for i in range(256))
450
+ elif im.mode == "P":
451
+ palette = im.im.getpalette("RGB", "BGRX")
452
+ colors = len(palette) // 4
453
+ else:
454
+ palette = None
455
+
456
+ # bitmap header
457
+ if bitmap_header:
458
+ offset = 14 + header + colors * 4
459
+ file_size = offset + image
460
+ if file_size > 2**32 - 1:
461
+ msg = "File size is too large for the BMP format"
462
+ raise ValueError(msg)
463
+ fp.write(
464
+ b"BM" # file type (magic)
465
+ + o32(file_size) # file size
466
+ + o32(0) # reserved
467
+ + o32(offset) # image data offset
468
+ )
469
+
470
+ # bitmap info header
471
+ fp.write(
472
+ o32(header) # info header size
473
+ + o32(im.size[0]) # width
474
+ + o32(im.size[1]) # height
475
+ + o16(1) # planes
476
+ + o16(bits) # depth
477
+ + o32(0) # compression (0=uncompressed)
478
+ + o32(image) # size of bitmap
479
+ + o32(ppm[0]) # resolution
480
+ + o32(ppm[1]) # resolution
481
+ + o32(colors) # colors used
482
+ + o32(colors) # colors important
483
+ )
484
+
485
+ fp.write(b"\0" * (header - 40)) # padding (for OS/2 format)
486
+
487
+ if palette:
488
+ fp.write(palette)
489
+
490
+ ImageFile._save(
491
+ im, fp, [ImageFile._Tile("raw", (0, 0) + im.size, 0, (rawmode, stride, -1))]
492
+ )
493
+
494
+
495
+ #
496
+ # --------------------------------------------------------------------
497
+ # Registry
498
+
499
+
500
+ Image.register_open(BmpImageFile.format, BmpImageFile, _accept)
501
+ Image.register_save(BmpImageFile.format, _save)
502
+
503
+ Image.register_extension(BmpImageFile.format, ".bmp")
504
+
505
+ Image.register_mime(BmpImageFile.format, "image/bmp")
506
+
507
+ Image.register_decoder("bmp_rle", BmpRleDecoder)
508
+
509
+ Image.register_open(DibImageFile.format, DibImageFile, _dib_accept)
510
+ Image.register_save(DibImageFile.format, _dib_save)
511
+
512
+ Image.register_extension(DibImageFile.format, ".dib")
513
+
514
+ Image.register_mime(DibImageFile.format, "image/bmp")
.venv/Lib/site-packages/PIL/BufrStubImagePlugin.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import os
14
+ from typing import IO
15
+
16
+ from . import Image, ImageFile
17
+
18
+ _handler = None
19
+
20
+
21
+ def register_handler(handler: ImageFile.StubHandler | None) -> None:
22
+ """
23
+ Install application-specific BUFR image handler.
24
+
25
+ :param handler: Handler object.
26
+ """
27
+ global _handler
28
+ _handler = handler
29
+
30
+
31
+ # --------------------------------------------------------------------
32
+ # Image adapter
33
+
34
+
35
+ def _accept(prefix: bytes) -> bool:
36
+ return prefix.startswith((b"BUFR", b"ZCZC"))
37
+
38
+
39
+ class BufrStubImageFile(ImageFile.StubImageFile):
40
+ format = "BUFR"
41
+ format_description = "BUFR"
42
+
43
+ def _open(self) -> None:
44
+ assert self.fp is not None
45
+ if not _accept(self.fp.read(4)):
46
+ msg = "Not a BUFR file"
47
+ raise SyntaxError(msg)
48
+
49
+ self.fp.seek(-4, os.SEEK_CUR)
50
+
51
+ # make something up
52
+ self._mode = "F"
53
+ self._size = 1, 1
54
+
55
+ def _load(self) -> ImageFile.StubHandler | None:
56
+ return _handler
57
+
58
+
59
+ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
60
+ if _handler is None or not hasattr(_handler, "save"):
61
+ msg = "BUFR save handler not installed"
62
+ raise OSError(msg)
63
+ _handler.save(im, fp, filename)
64
+
65
+
66
+ # --------------------------------------------------------------------
67
+ # Registry
68
+
69
+ Image.register_open(BufrStubImageFile.format, BufrStubImageFile, _accept)
70
+ Image.register_save(BufrStubImageFile.format, _save)
71
+
72
+ Image.register_extension(BufrStubImageFile.format, ".bufr")
.venv/Lib/site-packages/PIL/ContainerIO.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 collections.abc import Iterable
20
+ from typing import IO, AnyStr, NoReturn
21
+
22
+
23
+ class ContainerIO(IO[AnyStr]):
24
+ """
25
+ A file object that provides read access to a part of an existing
26
+ file (for example a TAR file).
27
+ """
28
+
29
+ def __init__(self, file: IO[AnyStr], offset: int, length: int) -> None:
30
+ """
31
+ Create file object.
32
+
33
+ :param file: Existing file.
34
+ :param offset: Start of region, in bytes.
35
+ :param length: Size of region, in bytes.
36
+ """
37
+ self.fh: IO[AnyStr] = file
38
+ self.pos = 0
39
+ self.offset = offset
40
+ self.length = length
41
+ self.fh.seek(offset)
42
+
43
+ ##
44
+ # Always false.
45
+
46
+ def isatty(self) -> bool:
47
+ return False
48
+
49
+ def seekable(self) -> bool:
50
+ return True
51
+
52
+ def seek(self, offset: int, mode: int = io.SEEK_SET) -> int:
53
+ """
54
+ Move file pointer.
55
+
56
+ :param offset: Offset in bytes.
57
+ :param mode: Starting position. Use 0 for beginning of region, 1
58
+ for current offset, and 2 for end of region. You cannot move
59
+ the pointer outside the defined region.
60
+ :returns: Offset from start of region, in bytes.
61
+ """
62
+ if mode == 1:
63
+ self.pos = self.pos + offset
64
+ elif mode == 2:
65
+ self.pos = self.length + offset
66
+ else:
67
+ self.pos = offset
68
+ # clamp
69
+ self.pos = max(0, min(self.pos, self.length))
70
+ self.fh.seek(self.offset + self.pos)
71
+ return self.pos
72
+
73
+ def tell(self) -> int:
74
+ """
75
+ Get current file pointer.
76
+
77
+ :returns: Offset from start of region, in bytes.
78
+ """
79
+ return self.pos
80
+
81
+ def readable(self) -> bool:
82
+ return True
83
+
84
+ def read(self, n: int = -1) -> AnyStr:
85
+ """
86
+ Read data.
87
+
88
+ :param n: Number of bytes to read. If omitted, zero or negative,
89
+ read until end of region.
90
+ :returns: An 8-bit string.
91
+ """
92
+ if n > 0:
93
+ n = min(n, self.length - self.pos)
94
+ else:
95
+ n = self.length - self.pos
96
+ if n <= 0: # EOF
97
+ return b"" if "b" in self.fh.mode else "" # type: ignore[return-value]
98
+ self.pos = self.pos + n
99
+ return self.fh.read(n)
100
+
101
+ def readline(self, n: int = -1) -> AnyStr:
102
+ """
103
+ Read a line of text.
104
+
105
+ :param n: Number of bytes to read. If omitted, zero or negative,
106
+ read until end of line.
107
+ :returns: An 8-bit string.
108
+ """
109
+ s: AnyStr = b"" if "b" in self.fh.mode else "" # type: ignore[assignment]
110
+ newline_character = b"\n" if "b" in self.fh.mode else "\n"
111
+ while True:
112
+ c = self.read(1)
113
+ if not c:
114
+ break
115
+ s = s + c
116
+ if c == newline_character or len(s) == n:
117
+ break
118
+ return s
119
+
120
+ def readlines(self, n: int | None = -1) -> list[AnyStr]:
121
+ """
122
+ Read multiple lines of text.
123
+
124
+ :param n: Number of lines to read. If omitted, zero, negative or None,
125
+ read until end of region.
126
+ :returns: A list of 8-bit strings.
127
+ """
128
+ lines = []
129
+ while True:
130
+ s = self.readline()
131
+ if not s:
132
+ break
133
+ lines.append(s)
134
+ if len(lines) == n:
135
+ break
136
+ return lines
137
+
138
+ def writable(self) -> bool:
139
+ return False
140
+
141
+ def write(self, b: AnyStr) -> NoReturn:
142
+ raise NotImplementedError()
143
+
144
+ def writelines(self, lines: Iterable[AnyStr]) -> NoReturn:
145
+ raise NotImplementedError()
146
+
147
+ def truncate(self, size: int | None = None) -> int:
148
+ raise NotImplementedError()
149
+
150
+ def __enter__(self) -> ContainerIO[AnyStr]:
151
+ return self
152
+
153
+ def __exit__(self, *args: object) -> None:
154
+ self.close()
155
+
156
+ def __iter__(self) -> ContainerIO[AnyStr]:
157
+ return self
158
+
159
+ def __next__(self) -> AnyStr:
160
+ line = self.readline()
161
+ if not line:
162
+ msg = "end of region"
163
+ raise StopIteration(msg)
164
+ return line
165
+
166
+ def fileno(self) -> int:
167
+ return self.fh.fileno()
168
+
169
+ def flush(self) -> None:
170
+ self.fh.flush()
171
+
172
+ def close(self) -> None:
173
+ self.fh.close()
.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: bytes) -> bool:
29
+ return prefix.startswith(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) -> None:
41
+ assert self.fp is not None
42
+ offset = self.fp.tell()
43
+
44
+ # check magic
45
+ s = self.fp.read(6)
46
+ if not _accept(s):
47
+ msg = "not a CUR file"
48
+ raise SyntaxError(msg)
49
+
50
+ # pick the largest cursor in the file
51
+ m = b""
52
+ for i in range(i16(s, 4)):
53
+ s = self.fp.read(16)
54
+ if not m:
55
+ m = s
56
+ elif s[0] > m[0] and s[1] > m[1]:
57
+ m = s
58
+ if not m:
59
+ msg = "No cursors were found"
60
+ raise TypeError(msg)
61
+
62
+ # load as bitmap
63
+ self._bitmap(i32(m, 12) + offset)
64
+
65
+ # patch up the bitmap height
66
+ self._size = self.size[0], self.size[1] // 2
67
+ self.tile = [self.tile[0]._replace(extents=(0, 0) + self.size)]
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,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ._util import DeferredError
28
+ from .PcxImagePlugin import PcxImageFile
29
+
30
+ MAGIC = 0x3ADE68B1 # QUIZ: what's this value, then?
31
+
32
+
33
+ def _accept(prefix: bytes) -> bool:
34
+ return len(prefix) >= 4 and i32(prefix) == MAGIC
35
+
36
+
37
+ ##
38
+ # Image plugin for the Intel DCX format.
39
+
40
+
41
+ class DcxImageFile(PcxImageFile):
42
+ format = "DCX"
43
+ format_description = "Intel DCX"
44
+ _close_exclusive_fp_after_loading = False
45
+
46
+ def _open(self) -> None:
47
+ # Header
48
+ assert self.fp is not None
49
+ s = self.fp.read(4)
50
+ if not _accept(s):
51
+ msg = "not a DCX file"
52
+ raise SyntaxError(msg)
53
+
54
+ # Component directory
55
+ self._offset = []
56
+ for i in range(1024):
57
+ offset = i32(self.fp.read(4))
58
+ if not offset:
59
+ break
60
+ self._offset.append(offset)
61
+
62
+ self._fp = self.fp
63
+ self.frame = -1
64
+ self.n_frames = len(self._offset)
65
+ self.is_animated = self.n_frames > 1
66
+ self.seek(0)
67
+
68
+ def seek(self, frame: int) -> None:
69
+ if not self._seek_check(frame):
70
+ return
71
+ if isinstance(self._fp, DeferredError):
72
+ raise self._fp.ex
73
+ self.frame = frame
74
+ self.fp = self._fp
75
+ self.fp.seek(self._offset[frame])
76
+ PcxImageFile._open(self)
77
+
78
+ def tell(self) -> int:
79
+ return self.frame
80
+
81
+
82
+ Image.register_open(DcxImageFile.format, DcxImageFile, _accept)
83
+
84
+ Image.register_extension(DcxImageFile.format, ".dcx")
.venv/Lib/site-packages/PIL/DdsImagePlugin.py ADDED
@@ -0,0 +1,625 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A Pillow plugin 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 struct
16
+ import sys
17
+ from enum import IntEnum, IntFlag
18
+ from typing import IO
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, f"DDSD_{item.name}", item.value)
275
+ for item1 in DDSCAPS:
276
+ assert item1.name is not None
277
+ setattr(module, f"DDSCAPS_{item1.name}", item1.value)
278
+ for item2 in DDSCAPS2:
279
+ assert item2.name is not None
280
+ setattr(module, f"DDSCAPS2_{item2.name}", item2.value)
281
+ for item3 in DDPF:
282
+ assert item3.name is not None
283
+ setattr(module, f"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) -> None:
335
+ assert self.fp is not None
336
+ if not _accept(self.fp.read(4)):
337
+ msg = "not a DDS file"
338
+ raise SyntaxError(msg)
339
+ (header_size,) = struct.unpack("<I", self.fp.read(4))
340
+ if header_size != 124:
341
+ msg = f"Unsupported header size {repr(header_size)}"
342
+ raise OSError(msg)
343
+ header = self.fp.read(header_size - 4)
344
+ if len(header) != 120:
345
+ msg = f"Incomplete header: {len(header)} bytes"
346
+ raise OSError(msg)
347
+
348
+ flags, height, width = struct.unpack("<3I", header[:12])
349
+ self._size = (width, height)
350
+ extents = (0, 0) + self.size
351
+
352
+ pitch, depth, mipmaps = struct.unpack("<3I", header[12:24])
353
+ struct.unpack("<11I", header[24:68]) # reserved
354
+
355
+ # pixel format
356
+ pfsize, pfflags, fourcc, bitcount = struct.unpack("<4I", header[68:84])
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[84 : 84 + mask_count * 4])
369
+ self.tile = [ImageFile._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
+ self.palette.mode = "RGBA"
383
+ elif pfflags & DDPF.FOURCC:
384
+ offset = header_size + 4
385
+ if fourcc == D3DFMT.DXT1:
386
+ self._mode = "RGBA"
387
+ self.pixel_format = "DXT1"
388
+ n = 1
389
+ elif fourcc == D3DFMT.DXT3:
390
+ self._mode = "RGBA"
391
+ self.pixel_format = "DXT3"
392
+ n = 2
393
+ elif fourcc == D3DFMT.DXT5:
394
+ self._mode = "RGBA"
395
+ self.pixel_format = "DXT5"
396
+ n = 3
397
+ elif fourcc in (D3DFMT.BC4U, D3DFMT.ATI1):
398
+ self._mode = "L"
399
+ self.pixel_format = "BC4"
400
+ n = 4
401
+ elif fourcc == D3DFMT.BC5S:
402
+ self._mode = "RGB"
403
+ self.pixel_format = "BC5S"
404
+ n = 5
405
+ elif fourcc in (D3DFMT.BC5U, D3DFMT.ATI2):
406
+ self._mode = "RGB"
407
+ self.pixel_format = "BC5"
408
+ n = 5
409
+ elif fourcc == D3DFMT.DX10:
410
+ offset += 20
411
+ # ignoring flags which pertain to volume textures and cubemaps
412
+ (dxgi_format,) = struct.unpack("<I", self.fp.read(4))
413
+ self.fp.read(16)
414
+ if dxgi_format in (
415
+ DXGI_FORMAT.BC1_UNORM,
416
+ DXGI_FORMAT.BC1_TYPELESS,
417
+ ):
418
+ self._mode = "RGBA"
419
+ self.pixel_format = "BC1"
420
+ n = 1
421
+ elif dxgi_format in (DXGI_FORMAT.BC2_TYPELESS, DXGI_FORMAT.BC2_UNORM):
422
+ self._mode = "RGBA"
423
+ self.pixel_format = "BC2"
424
+ n = 2
425
+ elif dxgi_format in (DXGI_FORMAT.BC3_TYPELESS, DXGI_FORMAT.BC3_UNORM):
426
+ self._mode = "RGBA"
427
+ self.pixel_format = "BC3"
428
+ n = 3
429
+ elif dxgi_format in (DXGI_FORMAT.BC4_TYPELESS, DXGI_FORMAT.BC4_UNORM):
430
+ self._mode = "L"
431
+ self.pixel_format = "BC4"
432
+ n = 4
433
+ elif dxgi_format in (DXGI_FORMAT.BC5_TYPELESS, DXGI_FORMAT.BC5_UNORM):
434
+ self._mode = "RGB"
435
+ self.pixel_format = "BC5"
436
+ n = 5
437
+ elif dxgi_format == DXGI_FORMAT.BC5_SNORM:
438
+ self._mode = "RGB"
439
+ self.pixel_format = "BC5S"
440
+ n = 5
441
+ elif dxgi_format == DXGI_FORMAT.BC6H_UF16:
442
+ self._mode = "RGB"
443
+ self.pixel_format = "BC6H"
444
+ n = 6
445
+ elif dxgi_format == DXGI_FORMAT.BC6H_SF16:
446
+ self._mode = "RGB"
447
+ self.pixel_format = "BC6HS"
448
+ n = 6
449
+ elif dxgi_format in (
450
+ DXGI_FORMAT.BC7_TYPELESS,
451
+ DXGI_FORMAT.BC7_UNORM,
452
+ DXGI_FORMAT.BC7_UNORM_SRGB,
453
+ ):
454
+ self._mode = "RGBA"
455
+ self.pixel_format = "BC7"
456
+ n = 7
457
+ if dxgi_format == DXGI_FORMAT.BC7_UNORM_SRGB:
458
+ self.info["gamma"] = 1 / 2.2
459
+ elif dxgi_format in (
460
+ DXGI_FORMAT.R8G8B8A8_TYPELESS,
461
+ DXGI_FORMAT.R8G8B8A8_UNORM,
462
+ DXGI_FORMAT.R8G8B8A8_UNORM_SRGB,
463
+ ):
464
+ self._mode = "RGBA"
465
+ if dxgi_format == DXGI_FORMAT.R8G8B8A8_UNORM_SRGB:
466
+ self.info["gamma"] = 1 / 2.2
467
+ else:
468
+ msg = f"Unimplemented DXGI format {dxgi_format}"
469
+ raise NotImplementedError(msg)
470
+ else:
471
+ msg = f"Unimplemented pixel format {repr(fourcc)}"
472
+ raise NotImplementedError(msg)
473
+ else:
474
+ msg = f"Unknown pixel format flags {pfflags}"
475
+ raise NotImplementedError(msg)
476
+
477
+ if n:
478
+ self.tile = [
479
+ ImageFile._Tile("bcn", extents, offset, (n, self.pixel_format))
480
+ ]
481
+ else:
482
+ self.tile = [ImageFile._Tile("raw", extents, 0, rawmode or self.mode)]
483
+
484
+ def load_seek(self, pos: int) -> None:
485
+ pass
486
+
487
+
488
+ class DdsRgbDecoder(ImageFile.PyDecoder):
489
+ _pulls_fd = True
490
+
491
+ def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:
492
+ assert self.fd is not None
493
+ bitcount, masks = self.args
494
+
495
+ # Some masks will be padded with zeros, e.g. R 0b11 G 0b1100
496
+ # Calculate how many zeros each mask is padded with
497
+ mask_offsets = []
498
+ # And the maximum value of each channel without the padding
499
+ mask_totals = []
500
+ for mask in masks:
501
+ offset = 0
502
+ if mask != 0:
503
+ while mask >> (offset + 1) << (offset + 1) == mask:
504
+ offset += 1
505
+ mask_offsets.append(offset)
506
+ mask_totals.append(mask >> offset)
507
+
508
+ data = bytearray()
509
+ bytecount = bitcount // 8
510
+ dest_length = self.state.xsize * self.state.ysize * len(masks)
511
+ while len(data) < dest_length:
512
+ value = int.from_bytes(self.fd.read(bytecount), "little")
513
+ for i, mask in enumerate(masks):
514
+ masked_value = value & mask
515
+ # Remove the zero padding, and scale it to 8 bits
516
+ data += o8(
517
+ int(((masked_value >> mask_offsets[i]) / mask_totals[i]) * 255)
518
+ if mask_totals[i]
519
+ else 0
520
+ )
521
+ self.set_as_raw(data)
522
+ return -1, 0
523
+
524
+
525
+ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
526
+ if im.mode not in ("RGB", "RGBA", "L", "LA"):
527
+ msg = f"cannot write mode {im.mode} as DDS"
528
+ raise OSError(msg)
529
+
530
+ flags = DDSD.CAPS | DDSD.HEIGHT | DDSD.WIDTH | DDSD.PIXELFORMAT
531
+ bitcount = len(im.getbands()) * 8
532
+ pixel_format = im.encoderinfo.get("pixel_format")
533
+ args: tuple[int] | str
534
+ if pixel_format:
535
+ codec_name = "bcn"
536
+ flags |= DDSD.LINEARSIZE
537
+ pitch = (im.width + 3) * 4
538
+ rgba_mask = [0, 0, 0, 0]
539
+ pixel_flags = DDPF.FOURCC
540
+ if pixel_format == "DXT1":
541
+ fourcc = D3DFMT.DXT1
542
+ args = (1,)
543
+ elif pixel_format == "DXT3":
544
+ fourcc = D3DFMT.DXT3
545
+ args = (2,)
546
+ elif pixel_format == "DXT5":
547
+ fourcc = D3DFMT.DXT5
548
+ args = (3,)
549
+ else:
550
+ fourcc = D3DFMT.DX10
551
+ if pixel_format == "BC2":
552
+ args = (2,)
553
+ dxgi_format = DXGI_FORMAT.BC2_TYPELESS
554
+ elif pixel_format == "BC3":
555
+ args = (3,)
556
+ dxgi_format = DXGI_FORMAT.BC3_TYPELESS
557
+ elif pixel_format == "BC5":
558
+ args = (5,)
559
+ dxgi_format = DXGI_FORMAT.BC5_TYPELESS
560
+ if im.mode != "RGB":
561
+ msg = "only RGB mode can be written as BC5"
562
+ raise OSError(msg)
563
+ else:
564
+ msg = f"cannot write pixel format {pixel_format}"
565
+ raise OSError(msg)
566
+ else:
567
+ codec_name = "raw"
568
+ flags |= DDSD.PITCH
569
+ pitch = (im.width * bitcount + 7) // 8
570
+
571
+ alpha = im.mode[-1] == "A"
572
+ if im.mode[0] == "L":
573
+ pixel_flags = DDPF.LUMINANCE
574
+ args = im.mode
575
+ if alpha:
576
+ rgba_mask = [0x000000FF, 0x000000FF, 0x000000FF]
577
+ else:
578
+ rgba_mask = [0xFF000000, 0xFF000000, 0xFF000000]
579
+ else:
580
+ pixel_flags = DDPF.RGB
581
+ args = im.mode[::-1]
582
+ rgba_mask = [0x00FF0000, 0x0000FF00, 0x000000FF]
583
+
584
+ if alpha:
585
+ r, g, b, a = im.split()
586
+ im = Image.merge("RGBA", (a, r, g, b))
587
+ if alpha:
588
+ pixel_flags |= DDPF.ALPHAPIXELS
589
+ rgba_mask.append(0xFF000000 if alpha else 0)
590
+
591
+ fourcc = D3DFMT.UNKNOWN
592
+ fp.write(
593
+ o32(DDS_MAGIC)
594
+ + struct.pack(
595
+ "<7I",
596
+ 124, # header size
597
+ flags, # flags
598
+ im.height,
599
+ im.width,
600
+ pitch,
601
+ 0, # depth
602
+ 0, # mipmaps
603
+ )
604
+ + struct.pack("11I", *((0,) * 11)) # reserved
605
+ # pfsize, pfflags, fourcc, bitcount
606
+ + struct.pack("<4I", 32, pixel_flags, fourcc, bitcount)
607
+ + struct.pack("<4I", *rgba_mask) # dwRGBABitMask
608
+ + struct.pack("<5I", DDSCAPS.TEXTURE, 0, 0, 0, 0)
609
+ )
610
+ if fourcc == D3DFMT.DX10:
611
+ fp.write(
612
+ # dxgi_format, 2D resource, misc, array size, straight alpha
613
+ struct.pack("<5I", dxgi_format, 3, 0, 0, 1)
614
+ )
615
+ ImageFile._save(im, fp, [ImageFile._Tile(codec_name, (0, 0) + im.size, 0, args)])
616
+
617
+
618
+ def _accept(prefix: bytes) -> bool:
619
+ return prefix.startswith(b"DDS ")
620
+
621
+
622
+ Image.register_open(DdsImageFile.format, DdsImageFile, _accept)
623
+ Image.register_decoder("dds_rgb", DdsRgbDecoder)
624
+ Image.register_save(DdsImageFile.format, _save)
625
+ Image.register_extension(DdsImageFile.format, ".dds")
.venv/Lib/site-packages/PIL/EpsImagePlugin.py ADDED
@@ -0,0 +1,481 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from typing import IO
31
+
32
+ from . import Image, ImageFile
33
+ from ._binary import i32le as i32
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() -> bool:
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(
69
+ tile: list[ImageFile._Tile],
70
+ size: tuple[int, int],
71
+ fp: IO[bytes],
72
+ scale: int = 1,
73
+ transparency: bool = False,
74
+ ) -> Image.core.ImagingCore:
75
+ """Render an image using Ghostscript"""
76
+ global gs_binary
77
+ if not has_ghostscript():
78
+ msg = "Unable to locate Ghostscript on paths"
79
+ raise OSError(msg)
80
+ assert isinstance(gs_binary, str)
81
+
82
+ # Unpack decoder tile
83
+ args = tile[0].args
84
+ assert isinstance(args, tuple)
85
+ length, bbox = args
86
+
87
+ # Hack to support hi-res rendering
88
+ scale = int(scale) or 1
89
+ width = size[0] * scale
90
+ height = size[1] * scale
91
+ # resolution is dependent on bbox and size
92
+ res_x = 72.0 * width / (bbox[2] - bbox[0])
93
+ res_y = 72.0 * height / (bbox[3] - bbox[1])
94
+
95
+ out_fd, outfile = tempfile.mkstemp()
96
+ os.close(out_fd)
97
+
98
+ infile_temp = None
99
+ if hasattr(fp, "name") and os.path.exists(fp.name):
100
+ infile = fp.name
101
+ else:
102
+ in_fd, infile_temp = tempfile.mkstemp()
103
+ os.close(in_fd)
104
+ infile = infile_temp
105
+
106
+ # Ignore length and offset!
107
+ # Ghostscript can read it
108
+ # Copy whole file to read in Ghostscript
109
+ with open(infile_temp, "wb") as f:
110
+ # fetch length of fp
111
+ fp.seek(0, io.SEEK_END)
112
+ fsize = fp.tell()
113
+ # ensure start position
114
+ # go back
115
+ fp.seek(0)
116
+ lengthfile = fsize
117
+ while lengthfile > 0:
118
+ s = fp.read(min(lengthfile, 100 * 1024))
119
+ if not s:
120
+ break
121
+ lengthfile -= len(s)
122
+ f.write(s)
123
+
124
+ if transparency:
125
+ # "RGBA"
126
+ device = "pngalpha"
127
+ else:
128
+ # "pnmraw" automatically chooses between
129
+ # PBM ("1"), PGM ("L"), and PPM ("RGB").
130
+ device = "pnmraw"
131
+
132
+ # Build Ghostscript command
133
+ command = [
134
+ gs_binary,
135
+ "-q", # quiet mode
136
+ f"-g{width:d}x{height:d}", # set output geometry (pixels)
137
+ f"-r{res_x:f}x{res_y:f}", # set input DPI (dots per inch)
138
+ "-dBATCH", # exit after processing
139
+ "-dNOPAUSE", # don't pause between pages
140
+ "-dSAFER", # safe mode
141
+ f"-sDEVICE={device}",
142
+ f"-sOutputFile={outfile}", # output file
143
+ # adjust for image origin
144
+ "-c",
145
+ f"{-bbox[0]} {-bbox[1]} translate",
146
+ "-f",
147
+ infile, # input file
148
+ # showpage (see https://bugs.ghostscript.com/show_bug.cgi?id=698272)
149
+ "-c",
150
+ "showpage",
151
+ ]
152
+
153
+ # push data through Ghostscript
154
+ try:
155
+ startupinfo = None
156
+ if sys.platform.startswith("win"):
157
+ startupinfo = subprocess.STARTUPINFO()
158
+ startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
159
+ subprocess.check_call(command, startupinfo=startupinfo)
160
+ with Image.open(outfile) as out_im:
161
+ out_im.load()
162
+ return out_im.im.copy()
163
+ finally:
164
+ try:
165
+ os.unlink(outfile)
166
+ if infile_temp:
167
+ os.unlink(infile_temp)
168
+ except OSError:
169
+ pass
170
+
171
+
172
+ def _accept(prefix: bytes) -> bool:
173
+ return prefix.startswith(b"%!PS") or (
174
+ len(prefix) >= 4 and i32(prefix) == 0xC6D3D0C5
175
+ )
176
+
177
+
178
+ ##
179
+ # Image plugin for Encapsulated PostScript. This plugin supports only
180
+ # a few variants of this format.
181
+
182
+
183
+ class EpsImageFile(ImageFile.ImageFile):
184
+ """EPS File Parser for the Python Imaging Library"""
185
+
186
+ format = "EPS"
187
+ format_description = "Encapsulated Postscript"
188
+
189
+ mode_map = {1: "L", 2: "LAB", 3: "RGB", 4: "CMYK"}
190
+
191
+ def _open(self) -> None:
192
+ assert self.fp is not None
193
+ length, offset = self._find_offset(self.fp)
194
+
195
+ # go to offset - start of "%!PS"
196
+ self.fp.seek(offset)
197
+
198
+ self._mode = "RGB"
199
+
200
+ # When reading header comments, the first comment is used.
201
+ # When reading trailer comments, the last comment is used.
202
+ bounding_box: list[int] | None = None
203
+ imagedata_size: tuple[int, int] | None = None
204
+
205
+ byte_arr = bytearray(255)
206
+ bytes_mv = memoryview(byte_arr)
207
+ bytes_read = 0
208
+ reading_header_comments = True
209
+ reading_trailer_comments = False
210
+ trailer_reached = False
211
+
212
+ def check_required_header_comments() -> None:
213
+ """
214
+ The EPS specification requires that some headers exist.
215
+ This should be checked when the header comments formally end,
216
+ when image data starts, or when the file ends, whichever comes first.
217
+ """
218
+ if "PS-Adobe" not in self.info:
219
+ msg = 'EPS header missing "%!PS-Adobe" comment'
220
+ raise SyntaxError(msg)
221
+ if "BoundingBox" not in self.info:
222
+ msg = 'EPS header missing "%%BoundingBox" comment'
223
+ raise SyntaxError(msg)
224
+
225
+ def read_comment(s: str) -> bool:
226
+ nonlocal bounding_box, reading_trailer_comments
227
+ try:
228
+ m = split.match(s)
229
+ except re.error as e:
230
+ msg = "not an EPS file"
231
+ raise SyntaxError(msg) from e
232
+
233
+ if not m:
234
+ return False
235
+
236
+ k, v = m.group(1, 2)
237
+ self.info[k] = v
238
+ if k == "BoundingBox":
239
+ if v == "(atend)":
240
+ reading_trailer_comments = True
241
+ elif not bounding_box or (trailer_reached and reading_trailer_comments):
242
+ try:
243
+ # Note: The DSC spec says that BoundingBox
244
+ # fields should be integers, but some drivers
245
+ # put floating point values there anyway.
246
+ bounding_box = [int(float(i)) for i in v.split()]
247
+ except Exception:
248
+ pass
249
+ return True
250
+
251
+ while True:
252
+ byte = self.fp.read(1)
253
+ if byte == b"":
254
+ # if we didn't read a byte we must be at the end of the file
255
+ if bytes_read == 0:
256
+ if reading_header_comments:
257
+ check_required_header_comments()
258
+ break
259
+ elif byte in b"\r\n":
260
+ # if we read a line ending character, ignore it and parse what
261
+ # we have already read. if we haven't read any other characters,
262
+ # continue reading
263
+ if bytes_read == 0:
264
+ continue
265
+ else:
266
+ # ASCII/hexadecimal lines in an EPS file must not exceed
267
+ # 255 characters, not including line ending characters
268
+ if bytes_read >= 255:
269
+ # only enforce this for lines starting with a "%",
270
+ # otherwise assume it's binary data
271
+ if byte_arr[0] == ord("%"):
272
+ msg = "not an EPS file"
273
+ raise SyntaxError(msg)
274
+ else:
275
+ if reading_header_comments:
276
+ check_required_header_comments()
277
+ reading_header_comments = False
278
+ # reset bytes_read so we can keep reading
279
+ # data until the end of the line
280
+ bytes_read = 0
281
+ byte_arr[bytes_read] = byte[0]
282
+ bytes_read += 1
283
+ continue
284
+
285
+ if reading_header_comments:
286
+ # Load EPS header
287
+
288
+ # if this line doesn't start with a "%",
289
+ # or does start with "%%EndComments",
290
+ # then we've reached the end of the header/comments
291
+ if byte_arr[0] != ord("%") or bytes_mv[:13] == b"%%EndComments":
292
+ check_required_header_comments()
293
+ reading_header_comments = False
294
+ continue
295
+
296
+ s = str(bytes_mv[:bytes_read], "latin-1")
297
+ if not read_comment(s):
298
+ m = field.match(s)
299
+ if m:
300
+ k = m.group(1)
301
+ if k.startswith("PS-Adobe"):
302
+ self.info["PS-Adobe"] = k[9:]
303
+ else:
304
+ self.info[k] = ""
305
+ elif s[0] == "%":
306
+ # handle non-DSC PostScript comments that some
307
+ # tools mistakenly put in the Comments section
308
+ pass
309
+ else:
310
+ msg = "bad EPS header"
311
+ raise OSError(msg)
312
+ elif bytes_mv[:11] == b"%ImageData:":
313
+ # Check for an "ImageData" descriptor
314
+ # https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#50577413_pgfId-1035096
315
+
316
+ # If we've already read an "ImageData" descriptor,
317
+ # don't read another one.
318
+ if imagedata_size:
319
+ bytes_read = 0
320
+ continue
321
+
322
+ # Values:
323
+ # columns
324
+ # rows
325
+ # bit depth (1 or 8)
326
+ # mode (1: L, 2: LAB, 3: RGB, 4: CMYK)
327
+ # number of padding channels
328
+ # block size (number of bytes per row per channel)
329
+ # binary/ascii (1: binary, 2: ascii)
330
+ # data start identifier (the image data follows after a single line
331
+ # consisting only of this quoted value)
332
+ image_data_values = byte_arr[11:bytes_read].split(None, 7)
333
+ columns, rows, bit_depth, mode_id = (
334
+ int(value) for value in image_data_values[:4]
335
+ )
336
+
337
+ if bit_depth == 1:
338
+ self._mode = "1"
339
+ elif bit_depth == 8:
340
+ try:
341
+ self._mode = self.mode_map[mode_id]
342
+ except ValueError:
343
+ break
344
+ else:
345
+ break
346
+
347
+ # Parse the columns and rows after checking the bit depth and mode
348
+ # in case the bit depth and/or mode are invalid.
349
+ imagedata_size = columns, rows
350
+ elif bytes_mv[:5] == b"%%EOF":
351
+ break
352
+ elif trailer_reached and reading_trailer_comments:
353
+ # Load EPS trailer
354
+ s = str(bytes_mv[:bytes_read], "latin-1")
355
+ read_comment(s)
356
+ elif bytes_mv[:9] == b"%%Trailer":
357
+ trailer_reached = True
358
+ elif bytes_mv[:14] == b"%%BeginBinary:":
359
+ bytecount = int(byte_arr[14:bytes_read])
360
+ self.fp.seek(bytecount, os.SEEK_CUR)
361
+ bytes_read = 0
362
+
363
+ # A "BoundingBox" is always required,
364
+ # even if an "ImageData" descriptor size exists.
365
+ if not bounding_box:
366
+ msg = "cannot determine EPS bounding box"
367
+ raise OSError(msg)
368
+
369
+ # An "ImageData" size takes precedence over the "BoundingBox".
370
+ self._size = imagedata_size or (
371
+ bounding_box[2] - bounding_box[0],
372
+ bounding_box[3] - bounding_box[1],
373
+ )
374
+
375
+ self.tile = [
376
+ ImageFile._Tile("eps", (0, 0) + self.size, offset, (length, bounding_box))
377
+ ]
378
+
379
+ def _find_offset(self, fp: IO[bytes]) -> tuple[int, int]:
380
+ s = fp.read(4)
381
+
382
+ if s == b"%!PS":
383
+ # for HEAD without binary preview
384
+ fp.seek(0, io.SEEK_END)
385
+ length = fp.tell()
386
+ offset = 0
387
+ elif i32(s) == 0xC6D3D0C5:
388
+ # FIX for: Some EPS file not handled correctly / issue #302
389
+ # EPS can contain binary data
390
+ # or start directly with latin coding
391
+ # more info see:
392
+ # https://web.archive.org/web/20160528181353/http://partners.adobe.com/public/developer/en/ps/5002.EPSF_Spec.pdf
393
+ s = fp.read(8)
394
+ offset = i32(s)
395
+ length = i32(s, 4)
396
+ else:
397
+ msg = "not an EPS file"
398
+ raise SyntaxError(msg)
399
+
400
+ return length, offset
401
+
402
+ def load(
403
+ self, scale: int = 1, transparency: bool = False
404
+ ) -> Image.core.PixelAccess | None:
405
+ # Load EPS via Ghostscript
406
+ if self.tile:
407
+ assert self.fp is not None
408
+ self.im = Ghostscript(self.tile, self.size, self.fp, scale, transparency)
409
+ self._mode = self.im.mode
410
+ self._size = self.im.size
411
+ self.tile = []
412
+ return Image.Image.load(self)
413
+
414
+ def load_seek(self, pos: int) -> None:
415
+ # we can't incrementally load, so force ImageFile.parser to
416
+ # use our custom load method by defining this method.
417
+ pass
418
+
419
+
420
+ # --------------------------------------------------------------------
421
+
422
+
423
+ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes, eps: int = 1) -> None:
424
+ """EPS Writer for the Python Imaging Library."""
425
+
426
+ # make sure image data is available
427
+ im.load()
428
+
429
+ # determine PostScript image mode
430
+ if im.mode == "L":
431
+ operator = (8, 1, b"image")
432
+ elif im.mode == "RGB":
433
+ operator = (8, 3, b"false 3 colorimage")
434
+ elif im.mode == "CMYK":
435
+ operator = (8, 4, b"false 4 colorimage")
436
+ else:
437
+ msg = "image mode is not supported"
438
+ raise ValueError(msg)
439
+
440
+ if eps:
441
+ # write EPS header
442
+ fp.write(b"%!PS-Adobe-3.0 EPSF-3.0\n")
443
+ fp.write(b"%%Creator: PIL 0.1 EpsEncode\n")
444
+ # fp.write("%%CreationDate: %s"...)
445
+ fp.write(b"%%%%BoundingBox: 0 0 %d %d\n" % im.size)
446
+ fp.write(b"%%Pages: 1\n")
447
+ fp.write(b"%%EndComments\n")
448
+ fp.write(b"%%Page: 1 1\n")
449
+ fp.write(b"%%ImageData: %d %d " % im.size)
450
+ fp.write(b'%d %d 0 1 1 "%s"\n' % operator)
451
+
452
+ # image header
453
+ fp.write(b"gsave\n")
454
+ fp.write(b"10 dict begin\n")
455
+ fp.write(b"/buf %d string def\n" % (im.size[0] * operator[1]))
456
+ fp.write(b"%d %d scale\n" % im.size)
457
+ fp.write(b"%d %d 8\n" % im.size) # <= bits
458
+ fp.write(b"[%d 0 0 -%d 0 %d]\n" % (im.size[0], im.size[1], im.size[1]))
459
+ fp.write(b"{ currentfile buf readhexstring pop } bind\n")
460
+ fp.write(operator[2] + b"\n")
461
+ if hasattr(fp, "flush"):
462
+ fp.flush()
463
+
464
+ ImageFile._save(im, fp, [ImageFile._Tile("eps", (0, 0) + im.size)])
465
+
466
+ fp.write(b"\n%%%%EndBinary\n")
467
+ fp.write(b"grestore end\n")
468
+ if hasattr(fp, "flush"):
469
+ fp.flush()
470
+
471
+
472
+ # --------------------------------------------------------------------
473
+
474
+
475
+ Image.register_open(EpsImageFile.format, EpsImageFile, _accept)
476
+
477
+ Image.register_save(EpsImageFile.format, _save)
478
+
479
+ Image.register_extensions(EpsImageFile.format, [".ps", ".eps"])
480
+
481
+ Image.register_mime(EpsImageFile.format, "application/postscript")
.venv/Lib/site-packages/PIL/ExifTags.py ADDED
@@ -0,0 +1,384 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
17
+ from __future__ import annotations
18
+
19
+ from enum import IntEnum
20
+
21
+
22
+ class Base(IntEnum):
23
+ # possibly incomplete
24
+ InteropIndex = 0x0001
25
+ ProcessingSoftware = 0x000B
26
+ NewSubfileType = 0x00FE
27
+ SubfileType = 0x00FF
28
+ ImageWidth = 0x0100
29
+ ImageLength = 0x0101
30
+ BitsPerSample = 0x0102
31
+ Compression = 0x0103
32
+ PhotometricInterpretation = 0x0106
33
+ Thresholding = 0x0107
34
+ CellWidth = 0x0108
35
+ CellLength = 0x0109
36
+ FillOrder = 0x010A
37
+ DocumentName = 0x010D
38
+ ImageDescription = 0x010E
39
+ Make = 0x010F
40
+ Model = 0x0110
41
+ StripOffsets = 0x0111
42
+ Orientation = 0x0112
43
+ SamplesPerPixel = 0x0115
44
+ RowsPerStrip = 0x0116
45
+ StripByteCounts = 0x0117
46
+ MinSampleValue = 0x0118
47
+ MaxSampleValue = 0x0119
48
+ XResolution = 0x011A
49
+ YResolution = 0x011B
50
+ PlanarConfiguration = 0x011C
51
+ PageName = 0x011D
52
+ FreeOffsets = 0x0120
53
+ FreeByteCounts = 0x0121
54
+ GrayResponseUnit = 0x0122
55
+ GrayResponseCurve = 0x0123
56
+ T4Options = 0x0124
57
+ T6Options = 0x0125
58
+ ResolutionUnit = 0x0128
59
+ PageNumber = 0x0129
60
+ TransferFunction = 0x012D
61
+ Software = 0x0131
62
+ DateTime = 0x0132
63
+ Artist = 0x013B
64
+ HostComputer = 0x013C
65
+ Predictor = 0x013D
66
+ WhitePoint = 0x013E
67
+ PrimaryChromaticities = 0x013F
68
+ ColorMap = 0x0140
69
+ HalftoneHints = 0x0141
70
+ TileWidth = 0x0142
71
+ TileLength = 0x0143
72
+ TileOffsets = 0x0144
73
+ TileByteCounts = 0x0145
74
+ SubIFDs = 0x014A
75
+ InkSet = 0x014C
76
+ InkNames = 0x014D
77
+ NumberOfInks = 0x014E
78
+ DotRange = 0x0150
79
+ TargetPrinter = 0x0151
80
+ ExtraSamples = 0x0152
81
+ SampleFormat = 0x0153
82
+ SMinSampleValue = 0x0154
83
+ SMaxSampleValue = 0x0155
84
+ TransferRange = 0x0156
85
+ ClipPath = 0x0157
86
+ XClipPathUnits = 0x0158
87
+ YClipPathUnits = 0x0159
88
+ Indexed = 0x015A
89
+ JPEGTables = 0x015B
90
+ OPIProxy = 0x015F
91
+ JPEGProc = 0x0200
92
+ JpegIFOffset = 0x0201
93
+ JpegIFByteCount = 0x0202
94
+ JpegRestartInterval = 0x0203
95
+ JpegLosslessPredictors = 0x0205
96
+ JpegPointTransforms = 0x0206
97
+ JpegQTables = 0x0207
98
+ JpegDCTables = 0x0208
99
+ JpegACTables = 0x0209
100
+ YCbCrCoefficients = 0x0211
101
+ YCbCrSubSampling = 0x0212
102
+ YCbCrPositioning = 0x0213
103
+ ReferenceBlackWhite = 0x0214
104
+ XMLPacket = 0x02BC
105
+ RelatedImageFileFormat = 0x1000
106
+ RelatedImageWidth = 0x1001
107
+ RelatedImageLength = 0x1002
108
+ Rating = 0x4746
109
+ RatingPercent = 0x4749
110
+ ImageID = 0x800D
111
+ CFARepeatPatternDim = 0x828D
112
+ BatteryLevel = 0x828F
113
+ Copyright = 0x8298
114
+ ExposureTime = 0x829A
115
+ FNumber = 0x829D
116
+ IPTCNAA = 0x83BB
117
+ ImageResources = 0x8649
118
+ ExifOffset = 0x8769
119
+ InterColorProfile = 0x8773
120
+ ExposureProgram = 0x8822
121
+ SpectralSensitivity = 0x8824
122
+ GPSInfo = 0x8825
123
+ ISOSpeedRatings = 0x8827
124
+ OECF = 0x8828
125
+ Interlace = 0x8829
126
+ TimeZoneOffset = 0x882A
127
+ SelfTimerMode = 0x882B
128
+ SensitivityType = 0x8830
129
+ StandardOutputSensitivity = 0x8831
130
+ RecommendedExposureIndex = 0x8832
131
+ ISOSpeed = 0x8833
132
+ ISOSpeedLatitudeyyy = 0x8834
133
+ ISOSpeedLatitudezzz = 0x8835
134
+ ExifVersion = 0x9000
135
+ DateTimeOriginal = 0x9003
136
+ DateTimeDigitized = 0x9004
137
+ OffsetTime = 0x9010
138
+ OffsetTimeOriginal = 0x9011
139
+ OffsetTimeDigitized = 0x9012
140
+ ComponentsConfiguration = 0x9101
141
+ CompressedBitsPerPixel = 0x9102
142
+ ShutterSpeedValue = 0x9201
143
+ ApertureValue = 0x9202
144
+ BrightnessValue = 0x9203
145
+ ExposureBiasValue = 0x9204
146
+ MaxApertureValue = 0x9205
147
+ SubjectDistance = 0x9206
148
+ MeteringMode = 0x9207
149
+ LightSource = 0x9208
150
+ Flash = 0x9209
151
+ FocalLength = 0x920A
152
+ Noise = 0x920D
153
+ ImageNumber = 0x9211
154
+ SecurityClassification = 0x9212
155
+ ImageHistory = 0x9213
156
+ TIFFEPStandardID = 0x9216
157
+ MakerNote = 0x927C
158
+ UserComment = 0x9286
159
+ SubsecTime = 0x9290
160
+ SubsecTimeOriginal = 0x9291
161
+ SubsecTimeDigitized = 0x9292
162
+ AmbientTemperature = 0x9400
163
+ Humidity = 0x9401
164
+ Pressure = 0x9402
165
+ WaterDepth = 0x9403
166
+ Acceleration = 0x9404
167
+ CameraElevationAngle = 0x9405
168
+ XPTitle = 0x9C9B
169
+ XPComment = 0x9C9C
170
+ XPAuthor = 0x9C9D
171
+ XPKeywords = 0x9C9E
172
+ XPSubject = 0x9C9F
173
+ FlashPixVersion = 0xA000
174
+ ColorSpace = 0xA001
175
+ ExifImageWidth = 0xA002
176
+ ExifImageHeight = 0xA003
177
+ RelatedSoundFile = 0xA004
178
+ ExifInteroperabilityOffset = 0xA005
179
+ FlashEnergy = 0xA20B
180
+ SpatialFrequencyResponse = 0xA20C
181
+ FocalPlaneXResolution = 0xA20E
182
+ FocalPlaneYResolution = 0xA20F
183
+ FocalPlaneResolutionUnit = 0xA210
184
+ SubjectLocation = 0xA214
185
+ ExposureIndex = 0xA215
186
+ SensingMethod = 0xA217
187
+ FileSource = 0xA300
188
+ SceneType = 0xA301
189
+ CFAPattern = 0xA302
190
+ CustomRendered = 0xA401
191
+ ExposureMode = 0xA402
192
+ WhiteBalance = 0xA403
193
+ DigitalZoomRatio = 0xA404
194
+ FocalLengthIn35mmFilm = 0xA405
195
+ SceneCaptureType = 0xA406
196
+ GainControl = 0xA407
197
+ Contrast = 0xA408
198
+ Saturation = 0xA409
199
+ Sharpness = 0xA40A
200
+ DeviceSettingDescription = 0xA40B
201
+ SubjectDistanceRange = 0xA40C
202
+ ImageUniqueID = 0xA420
203
+ CameraOwnerName = 0xA430
204
+ BodySerialNumber = 0xA431
205
+ LensSpecification = 0xA432
206
+ LensMake = 0xA433
207
+ LensModel = 0xA434
208
+ LensSerialNumber = 0xA435
209
+ CompositeImage = 0xA460
210
+ CompositeImageCount = 0xA461
211
+ CompositeImageExposureTimes = 0xA462
212
+ Gamma = 0xA500
213
+ PrintImageMatching = 0xC4A5
214
+ DNGVersion = 0xC612
215
+ DNGBackwardVersion = 0xC613
216
+ UniqueCameraModel = 0xC614
217
+ LocalizedCameraModel = 0xC615
218
+ CFAPlaneColor = 0xC616
219
+ CFALayout = 0xC617
220
+ LinearizationTable = 0xC618
221
+ BlackLevelRepeatDim = 0xC619
222
+ BlackLevel = 0xC61A
223
+ BlackLevelDeltaH = 0xC61B
224
+ BlackLevelDeltaV = 0xC61C
225
+ WhiteLevel = 0xC61D
226
+ DefaultScale = 0xC61E
227
+ DefaultCropOrigin = 0xC61F
228
+ DefaultCropSize = 0xC620
229
+ ColorMatrix1 = 0xC621
230
+ ColorMatrix2 = 0xC622
231
+ CameraCalibration1 = 0xC623
232
+ CameraCalibration2 = 0xC624
233
+ ReductionMatrix1 = 0xC625
234
+ ReductionMatrix2 = 0xC626
235
+ AnalogBalance = 0xC627
236
+ AsShotNeutral = 0xC628
237
+ AsShotWhiteXY = 0xC629
238
+ BaselineExposure = 0xC62A
239
+ BaselineNoise = 0xC62B
240
+ BaselineSharpness = 0xC62C
241
+ BayerGreenSplit = 0xC62D
242
+ LinearResponseLimit = 0xC62E
243
+ CameraSerialNumber = 0xC62F
244
+ LensInfo = 0xC630
245
+ ChromaBlurRadius = 0xC631
246
+ AntiAliasStrength = 0xC632
247
+ ShadowScale = 0xC633
248
+ DNGPrivateData = 0xC634
249
+ MakerNoteSafety = 0xC635
250
+ CalibrationIlluminant1 = 0xC65A
251
+ CalibrationIlluminant2 = 0xC65B
252
+ BestQualityScale = 0xC65C
253
+ RawDataUniqueID = 0xC65D
254
+ OriginalRawFileName = 0xC68B
255
+ OriginalRawFileData = 0xC68C
256
+ ActiveArea = 0xC68D
257
+ MaskedAreas = 0xC68E
258
+ AsShotICCProfile = 0xC68F
259
+ AsShotPreProfileMatrix = 0xC690
260
+ CurrentICCProfile = 0xC691
261
+ CurrentPreProfileMatrix = 0xC692
262
+ ColorimetricReference = 0xC6BF
263
+ CameraCalibrationSignature = 0xC6F3
264
+ ProfileCalibrationSignature = 0xC6F4
265
+ AsShotProfileName = 0xC6F6
266
+ NoiseReductionApplied = 0xC6F7
267
+ ProfileName = 0xC6F8
268
+ ProfileHueSatMapDims = 0xC6F9
269
+ ProfileHueSatMapData1 = 0xC6FA
270
+ ProfileHueSatMapData2 = 0xC6FB
271
+ ProfileToneCurve = 0xC6FC
272
+ ProfileEmbedPolicy = 0xC6FD
273
+ ProfileCopyright = 0xC6FE
274
+ ForwardMatrix1 = 0xC714
275
+ ForwardMatrix2 = 0xC715
276
+ PreviewApplicationName = 0xC716
277
+ PreviewApplicationVersion = 0xC717
278
+ PreviewSettingsName = 0xC718
279
+ PreviewSettingsDigest = 0xC719
280
+ PreviewColorSpace = 0xC71A
281
+ PreviewDateTime = 0xC71B
282
+ RawImageDigest = 0xC71C
283
+ OriginalRawFileDigest = 0xC71D
284
+ SubTileBlockSize = 0xC71E
285
+ RowInterleaveFactor = 0xC71F
286
+ ProfileLookTableDims = 0xC725
287
+ ProfileLookTableData = 0xC726
288
+ OpcodeList1 = 0xC740
289
+ OpcodeList2 = 0xC741
290
+ OpcodeList3 = 0xC74E
291
+ NoiseProfile = 0xC761
292
+ FrameRate = 0xC764
293
+
294
+
295
+ """Maps EXIF tags to tag names."""
296
+ TAGS = {
297
+ **{i.value: i.name for i in Base},
298
+ 0x920C: "SpatialFrequencyResponse",
299
+ 0x9214: "SubjectLocation",
300
+ 0x9215: "ExposureIndex",
301
+ 0x828E: "CFAPattern",
302
+ 0x920B: "FlashEnergy",
303
+ 0x9216: "TIFF/EPStandardID",
304
+ }
305
+
306
+
307
+ class GPS(IntEnum):
308
+ GPSVersionID = 0x00
309
+ GPSLatitudeRef = 0x01
310
+ GPSLatitude = 0x02
311
+ GPSLongitudeRef = 0x03
312
+ GPSLongitude = 0x04
313
+ GPSAltitudeRef = 0x05
314
+ GPSAltitude = 0x06
315
+ GPSTimeStamp = 0x07
316
+ GPSSatellites = 0x08
317
+ GPSStatus = 0x09
318
+ GPSMeasureMode = 0x0A
319
+ GPSDOP = 0x0B
320
+ GPSSpeedRef = 0x0C
321
+ GPSSpeed = 0x0D
322
+ GPSTrackRef = 0x0E
323
+ GPSTrack = 0x0F
324
+ GPSImgDirectionRef = 0x10
325
+ GPSImgDirection = 0x11
326
+ GPSMapDatum = 0x12
327
+ GPSDestLatitudeRef = 0x13
328
+ GPSDestLatitude = 0x14
329
+ GPSDestLongitudeRef = 0x15
330
+ GPSDestLongitude = 0x16
331
+ GPSDestBearingRef = 0x17
332
+ GPSDestBearing = 0x18
333
+ GPSDestDistanceRef = 0x19
334
+ GPSDestDistance = 0x1A
335
+ GPSProcessingMethod = 0x1B
336
+ GPSAreaInformation = 0x1C
337
+ GPSDateStamp = 0x1D
338
+ GPSDifferential = 0x1E
339
+ GPSHPositioningError = 0x1F
340
+
341
+
342
+ """Maps EXIF GPS tags to tag names."""
343
+ GPSTAGS = {i.value: i.name for i in GPS}
344
+
345
+
346
+ class Interop(IntEnum):
347
+ InteropIndex = 0x0001
348
+ InteropVersion = 0x0002
349
+ RelatedImageFileFormat = 0x1000
350
+ RelatedImageWidth = 0x1001
351
+ RelatedImageHeight = 0x1002
352
+
353
+
354
+ class IFD(IntEnum):
355
+ Exif = 0x8769
356
+ GPSInfo = 0x8825
357
+ MakerNote = 0x927C
358
+ Makernote = 0x927C # Deprecated
359
+ Interop = 0xA005
360
+ IFD1 = -1
361
+
362
+
363
+ class LightSource(IntEnum):
364
+ Unknown = 0x00
365
+ Daylight = 0x01
366
+ Fluorescent = 0x02
367
+ Tungsten = 0x03
368
+ Flash = 0x04
369
+ Fine = 0x09
370
+ Cloudy = 0x0A
371
+ Shade = 0x0B
372
+ DaylightFluorescent = 0x0C
373
+ DayWhiteFluorescent = 0x0D
374
+ CoolWhiteFluorescent = 0x0E
375
+ WhiteFluorescent = 0x0F
376
+ StandardLightA = 0x11
377
+ StandardLightB = 0x12
378
+ StandardLightC = 0x13
379
+ D55 = 0x14
380
+ D65 = 0x15
381
+ D75 = 0x16
382
+ D50 = 0x17
383
+ ISO = 0x18
384
+ Other = 0xFF
.venv/Lib/site-packages/PIL/FitsImagePlugin.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.startswith(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 = [ImageFile._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: tuple[str | int, ...]
119
+ if decoder_name == "raw":
120
+ args = (self.mode, 0, -1)
121
+ else:
122
+ args = (number_of_bits,)
123
+ return decoder_name, offset, args
124
+
125
+
126
+ class FitsGzipDecoder(ImageFile.PyDecoder):
127
+ _pulls_fd = True
128
+
129
+ def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:
130
+ assert self.fd is not None
131
+ with gzip.open(self.fd) as fp:
132
+ value = fp.read(self.state.xsize * self.state.ysize * 4)
133
+
134
+ rows = []
135
+ offset = 0
136
+ number_of_bits = min(self.args[0] // 8, 4)
137
+ for y in range(self.state.ysize):
138
+ row = bytearray()
139
+ for x in range(self.state.xsize):
140
+ row += value[offset + (4 - number_of_bits) : offset + 4]
141
+ offset += 4
142
+ rows.append(row)
143
+ self.set_as_raw(bytes([pixel for row in rows[::-1] for pixel in row]))
144
+ return -1, 0
145
+
146
+
147
+ # --------------------------------------------------------------------
148
+ # Registry
149
+
150
+ Image.register_open(FitsImageFile.format, FitsImageFile, _accept)
151
+ Image.register_decoder("fits_gzip", FitsGzipDecoder)
152
+
153
+ Image.register_extensions(FitsImageFile.format, [".fit", ".fits"])
.venv/Lib/site-packages/PIL/FliImagePlugin.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from ._util import DeferredError
26
+
27
+ #
28
+ # decoder
29
+
30
+
31
+ def _accept(prefix: bytes) -> bool:
32
+ return (
33
+ len(prefix) >= 16
34
+ and i16(prefix, 4) in [0xAF11, 0xAF12]
35
+ and i16(prefix, 14) in [0, 3] # flags
36
+ )
37
+
38
+
39
+ ##
40
+ # Image plugin for the FLI/FLC animation format. Use the <b>seek</b>
41
+ # method to load individual frames.
42
+
43
+
44
+ class FliImageFile(ImageFile.ImageFile):
45
+ format = "FLI"
46
+ format_description = "Autodesk FLI/FLC Animation"
47
+ _close_exclusive_fp_after_loading = False
48
+
49
+ def _open(self) -> None:
50
+ # HEAD
51
+ assert self.fp is not None
52
+ s = self.fp.read(128)
53
+ if not (
54
+ _accept(s)
55
+ and s[20:22] == b"\x00" * 2
56
+ and s[42:80] == b"\x00" * 38
57
+ and s[88:] == b"\x00" * 40
58
+ ):
59
+ msg = "not an FLI/FLC file"
60
+ raise SyntaxError(msg)
61
+
62
+ # frames
63
+ self.n_frames = i16(s, 6)
64
+ self.is_animated = self.n_frames > 1
65
+
66
+ # image characteristics
67
+ self._mode = "P"
68
+ self._size = i16(s, 8), i16(s, 10)
69
+
70
+ # animation speed
71
+ duration = i32(s, 16)
72
+ magic = i16(s, 4)
73
+ if magic == 0xAF11:
74
+ duration = (duration * 1000) // 70
75
+ self.info["duration"] = duration
76
+
77
+ # look for palette
78
+ palette = [(a, a, a) for a in range(256)]
79
+
80
+ s = self.fp.read(16)
81
+
82
+ self.__offset = 128
83
+
84
+ if i16(s, 4) == 0xF100:
85
+ # prefix chunk; ignore it
86
+ self.fp.seek(self.__offset + i32(s))
87
+ s = self.fp.read(16)
88
+
89
+ if i16(s, 4) == 0xF1FA:
90
+ # look for palette chunk
91
+ number_of_subchunks = i16(s, 6)
92
+ chunk_size: int | None = None
93
+ for _ in range(number_of_subchunks):
94
+ if chunk_size is not None:
95
+ self.fp.seek(chunk_size - 6, os.SEEK_CUR)
96
+ s = self.fp.read(6)
97
+ chunk_type = i16(s, 4)
98
+ if chunk_type in (4, 11):
99
+ self._palette(palette, 2 if chunk_type == 11 else 0)
100
+ break
101
+ chunk_size = i32(s)
102
+ if not chunk_size:
103
+ break
104
+
105
+ self.palette = ImagePalette.raw(
106
+ "RGB", b"".join(o8(r) + o8(g) + o8(b) for (r, g, b) in palette)
107
+ )
108
+
109
+ # set things up to decode first frame
110
+ self.__frame = -1
111
+ self._fp = self.fp
112
+ self.__rewind = self.fp.tell()
113
+ self.seek(0)
114
+
115
+ def _palette(self, palette: list[tuple[int, int, int]], shift: int) -> None:
116
+ # load palette
117
+
118
+ i = 0
119
+ assert self.fp is not None
120
+ for e in range(i16(self.fp.read(2))):
121
+ s = self.fp.read(2)
122
+ i = i + s[0]
123
+ n = s[1]
124
+ if n == 0:
125
+ n = 256
126
+ s = self.fp.read(n * 3)
127
+ for n in range(0, len(s), 3):
128
+ r = s[n] << shift
129
+ g = s[n + 1] << shift
130
+ b = s[n + 2] << shift
131
+ palette[i] = (r, g, b)
132
+ i += 1
133
+
134
+ def seek(self, frame: int) -> None:
135
+ if not self._seek_check(frame):
136
+ return
137
+ if frame < self.__frame:
138
+ self._seek(0)
139
+
140
+ for f in range(self.__frame + 1, frame + 1):
141
+ self._seek(f)
142
+
143
+ def _seek(self, frame: int) -> None:
144
+ if isinstance(self._fp, DeferredError):
145
+ raise self._fp.ex
146
+ if frame == 0:
147
+ self.__frame = -1
148
+ self._fp.seek(self.__rewind)
149
+ self.__offset = 128
150
+ else:
151
+ # ensure that the previous frame was loaded
152
+ self.load()
153
+
154
+ if frame != self.__frame + 1:
155
+ msg = f"cannot seek to frame {frame}"
156
+ raise ValueError(msg)
157
+ self.__frame = frame
158
+
159
+ # move to next frame
160
+ self.fp = self._fp
161
+ self.fp.seek(self.__offset)
162
+
163
+ s = self.fp.read(4)
164
+ if not s:
165
+ msg = "missing frame size"
166
+ raise EOFError(msg)
167
+
168
+ framesize = i32(s)
169
+
170
+ self.decodermaxblock = framesize
171
+ self.tile = [ImageFile._Tile("fli", (0, 0) + self.size, self.__offset)]
172
+
173
+ self.__offset += framesize
174
+
175
+ def tell(self) -> int:
176
+ return self.__frame
177
+
178
+
179
+ #
180
+ # registry
181
+
182
+ Image.register_open(FliImageFile.format, FliImageFile, _accept)
183
+
184
+ Image.register_extensions(FliImageFile.format, [".fli", ".flc"])
.venv/Lib/site-packages/PIL/FontFile.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, ImageFont, _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 _encode_metrics(self) -> bytes:
114
+ values: list[int] = []
115
+ for i in range(256):
116
+ m = self.metrics[i]
117
+ if m:
118
+ values.extend(m[0] + m[1] + m[2])
119
+ else:
120
+ values.extend((0,) * 10)
121
+
122
+ data = bytearray()
123
+ for v in values:
124
+ if v < 0:
125
+ v += 65536
126
+ data += _binary.o16be(v)
127
+ return bytes(data)
128
+
129
+ def save(self, filename: str) -> None:
130
+ """Save font"""
131
+
132
+ self.compile()
133
+
134
+ # font data
135
+ if not self.bitmap:
136
+ msg = "No bitmap created"
137
+ raise ValueError(msg)
138
+ self.bitmap.save(os.path.splitext(filename)[0] + ".pbm", "PNG")
139
+
140
+ # font metrics
141
+ with open(os.path.splitext(filename)[0] + ".pil", "wb") as fp:
142
+ fp.write(b"PILfont\n")
143
+ fp.write(f";;;;;;{self.ysize};\n".encode("ascii")) # HACK!!!
144
+ fp.write(b"DATA\n")
145
+ fp.write(self._encode_metrics())
146
+
147
+ def to_imagefont(self) -> ImageFont.ImageFont:
148
+ """Convert to ImageFont"""
149
+
150
+ self.compile()
151
+
152
+ # font data
153
+ if not self.bitmap:
154
+ msg = "No bitmap created"
155
+ raise ValueError(msg)
156
+
157
+ imagefont = ImageFont.ImageFont()
158
+ imagefont._load(self.bitmap, self._encode_metrics())
159
+ return imagefont
.venv/Lib/site-packages/PIL/FpxImagePlugin.py ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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: bytes) -> bool:
45
+ return prefix.startswith(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) -> None:
57
+ #
58
+ # read the OLE directory and see if this is a likely
59
+ # to be a FlashPix file
60
+
61
+ assert self.fp is not None
62
+ try:
63
+ self.ole = olefile.OleFileIO(self.fp)
64
+ except OSError as e:
65
+ msg = "not an FPX file; invalid OLE file"
66
+ raise SyntaxError(msg) from e
67
+
68
+ root = self.ole.root
69
+ if not root or root.clsid != "56616700-C154-11CE-8553-00AA00A1F95B":
70
+ msg = "not an FPX file; bad root CLSID"
71
+ raise SyntaxError(msg)
72
+
73
+ self._open_index(1)
74
+
75
+ def _open_index(self, index: int = 1) -> None:
76
+ #
77
+ # get the Image Contents Property Set
78
+
79
+ prop = self.ole.getproperties(
80
+ [f"Data Object Store {index:06d}", "\005Image Contents"]
81
+ )
82
+
83
+ # size (highest resolution)
84
+
85
+ assert isinstance(prop[0x1000002], int)
86
+ assert isinstance(prop[0x1000003], int)
87
+ self._size = prop[0x1000002], prop[0x1000003]
88
+
89
+ size = max(self.size)
90
+ i = 1
91
+ while size > 64:
92
+ size = size // 2
93
+ i += 1
94
+ self.maxid = i - 1
95
+
96
+ # mode. instead of using a single field for this, flashpix
97
+ # requires you to specify the mode for each channel in each
98
+ # resolution subimage, and leaves it to the decoder to make
99
+ # sure that they all match. for now, we'll cheat and assume
100
+ # that this is always the case.
101
+
102
+ id = self.maxid << 16
103
+
104
+ s = prop[0x2000002 | id]
105
+
106
+ if not isinstance(s, bytes) or (bands := i32(s, 4)) > 4:
107
+ msg = "Invalid number of bands"
108
+ raise OSError(msg)
109
+
110
+ # note: for now, we ignore the "uncalibrated" flag
111
+ colors = tuple(i32(s, 8 + i * 4) & 0x7FFFFFFF for i in range(bands))
112
+
113
+ self._mode, self.rawmode = MODES[colors]
114
+
115
+ # load JPEG tables, if any
116
+ self.jpeg = {}
117
+ for i in range(256):
118
+ id = 0x3000001 | (i << 16)
119
+ if id in prop:
120
+ self.jpeg[i] = prop[id]
121
+
122
+ self._open_subimage(1, self.maxid)
123
+
124
+ def _open_subimage(self, index: int = 1, subimage: int = 0) -> None:
125
+ #
126
+ # setup tile descriptors for a given subimage
127
+
128
+ stream = [
129
+ f"Data Object Store {index:06d}",
130
+ f"Resolution {subimage:04d}",
131
+ "Subimage 0000 Header",
132
+ ]
133
+
134
+ fp = self.ole.openstream(stream)
135
+
136
+ # skip prefix
137
+ fp.read(28)
138
+
139
+ # header stream
140
+ s = fp.read(36)
141
+
142
+ size = i32(s, 4), i32(s, 8)
143
+ # tilecount = i32(s, 12)
144
+ xtile, ytile = i32(s, 16), i32(s, 20)
145
+ # channels = i32(s, 24)
146
+ offset = i32(s, 28)
147
+ length = i32(s, 32)
148
+
149
+ if size != self.size:
150
+ msg = "subimage mismatch"
151
+ raise OSError(msg)
152
+
153
+ # get tile descriptors
154
+ fp.seek(28 + offset)
155
+ s = fp.read(i32(s, 12) * length)
156
+
157
+ x = y = 0
158
+ xsize, ysize = size
159
+ self.tile = []
160
+
161
+ for i in range(0, len(s), length):
162
+ x1 = min(xsize, x + xtile)
163
+ y1 = min(ysize, y + ytile)
164
+
165
+ compression = i32(s, i + 8)
166
+
167
+ if compression == 0:
168
+ self.tile.append(
169
+ ImageFile._Tile(
170
+ "raw",
171
+ (x, y, x1, y1),
172
+ i32(s, i) + 28,
173
+ self.rawmode,
174
+ )
175
+ )
176
+
177
+ elif compression == 1:
178
+ # FIXME: the fill decoder is not implemented
179
+ self.tile.append(
180
+ ImageFile._Tile(
181
+ "fill",
182
+ (x, y, x1, y1),
183
+ i32(s, i) + 28,
184
+ (self.rawmode, s[12:16]),
185
+ )
186
+ )
187
+
188
+ elif compression == 2:
189
+ internal_color_conversion = s[14]
190
+ jpeg_tables = s[15]
191
+ rawmode = self.rawmode
192
+
193
+ if internal_color_conversion:
194
+ # The image is stored as usual (usually YCbCr).
195
+ if rawmode == "RGBA":
196
+ # For "RGBA", data is stored as YCbCrA based on
197
+ # negative RGB. The following trick works around
198
+ # this problem :
199
+ jpegmode, rawmode = "YCbCrK", "CMYK"
200
+ else:
201
+ jpegmode = None # let the decoder decide
202
+
203
+ else:
204
+ # The image is stored as defined by rawmode
205
+ jpegmode = rawmode
206
+
207
+ self.tile.append(
208
+ ImageFile._Tile(
209
+ "jpeg",
210
+ (x, y, x1, y1),
211
+ i32(s, i) + 28,
212
+ (rawmode, jpegmode),
213
+ )
214
+ )
215
+
216
+ # FIXME: jpeg tables are tile dependent; the prefix
217
+ # data must be placed in the tile descriptor itself!
218
+
219
+ if jpeg_tables:
220
+ self.tile_prefix = self.jpeg[jpeg_tables]
221
+
222
+ else:
223
+ msg = "unknown/invalid compression"
224
+ raise OSError(msg)
225
+
226
+ x += xtile
227
+ if x >= xsize:
228
+ x, y = 0, y + ytile
229
+ if y >= ysize:
230
+ break # isn't really required
231
+
232
+ assert self.fp is not None
233
+ self.stream = stream
234
+ self._fp = self.fp
235
+ self.fp = None
236
+
237
+ def load(self) -> Image.core.PixelAccess | None:
238
+ if not self.fp:
239
+ self.fp = self.ole.openstream(self.stream[:2] + ["Subimage 0000 Data"])
240
+
241
+ return ImageFile.ImageFile.load(self)
242
+
243
+ def close(self) -> None:
244
+ self.ole.close()
245
+ super().close()
246
+
247
+ def __exit__(self, *args: object) -> None:
248
+ self.ole.close()
249
+ super().__exit__()
250
+
251
+
252
+ #
253
+ # --------------------------------------------------------------------
254
+
255
+
256
+ Image.register_open(FpxImageFile.format, FpxImageFile, _accept)
257
+
258
+ 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) -> None:
75
+ assert self.fp is not None
76
+ if not _accept(self.fp.read(4)):
77
+ msg = "not an FTEX file"
78
+ raise SyntaxError(msg)
79
+ struct.unpack("<i", self.fp.read(4)) # version
80
+ self._size = struct.unpack("<2i", self.fp.read(8))
81
+ mipmap_count, format_count = struct.unpack("<2i", self.fp.read(8))
82
+
83
+ # Only support single-format files.
84
+ # I don't know of any multi-format file.
85
+ assert format_count == 1
86
+
87
+ format, where = struct.unpack("<2i", self.fp.read(8))
88
+ self.fp.seek(where)
89
+ (mipmap_size,) = struct.unpack("<i", self.fp.read(4))
90
+
91
+ data = self.fp.read(mipmap_size)
92
+
93
+ if format == Format.DXT1:
94
+ self._mode = "RGBA"
95
+ self.tile = [ImageFile._Tile("bcn", (0, 0) + self.size, 0, (1,))]
96
+ elif format == Format.UNCOMPRESSED:
97
+ self._mode = "RGB"
98
+ self.tile = [ImageFile._Tile("raw", (0, 0) + self.size, 0, "RGB")]
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: int) -> None:
107
+ pass
108
+
109
+
110
+ def _accept(prefix: bytes) -> bool:
111
+ return prefix.startswith(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: bytes) -> bool:
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) -> None:
45
+ assert self.fp is not None
46
+ header_size = i32(self.fp.read(4))
47
+ if header_size < 20:
48
+ msg = "not a GIMP brush"
49
+ raise SyntaxError(msg)
50
+ version = i32(self.fp.read(4))
51
+ if version not in (1, 2):
52
+ msg = f"Unsupported GIMP brush version: {version}"
53
+ raise SyntaxError(msg)
54
+
55
+ width = i32(self.fp.read(4))
56
+ height = i32(self.fp.read(4))
57
+ color_depth = i32(self.fp.read(4))
58
+ if width == 0 or height == 0:
59
+ msg = "not a GIMP brush"
60
+ raise SyntaxError(msg)
61
+ if color_depth not in (1, 4):
62
+ msg = f"Unsupported GIMP brush color depth: {color_depth}"
63
+ raise SyntaxError(msg)
64
+
65
+ if version == 1:
66
+ comment_length = header_size - 20
67
+ else:
68
+ comment_length = header_size - 28
69
+ magic_number = self.fp.read(4)
70
+ if magic_number != b"GIMP":
71
+ msg = "not a GIMP brush, bad magic number"
72
+ raise SyntaxError(msg)
73
+ self.info["spacing"] = i32(self.fp.read(4))
74
+
75
+ self.info["comment"] = self.fp.read(comment_length)[:-1]
76
+
77
+ if color_depth == 1:
78
+ self._mode = "L"
79
+ else:
80
+ self._mode = "RGBA"
81
+
82
+ self._size = width, height
83
+
84
+ # Image might not be small
85
+ Image._decompression_bomb_check(self.size)
86
+
87
+ # Data is an uncompressed block of w * h * bytes/pixel
88
+ self._data_size = width * height * color_depth
89
+
90
+ def load(self) -> Image.core.PixelAccess | None:
91
+ if self._im is None:
92
+ assert self.fp is not None
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,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
29
+ from __future__ import annotations
30
+
31
+ from typing import IO
32
+
33
+ from . import ImageFile, ImagePalette, UnidentifiedImageError
34
+ from ._binary import i16be as i16
35
+ from ._binary import i32be as i32
36
+ from ._typing import StrOrBytesPath
37
+
38
+
39
+ class GdImageFile(ImageFile.ImageFile):
40
+ """
41
+ Image plugin for the GD uncompressed format. Note that this format
42
+ is not supported by the standard :py:func:`PIL.Image.open()` function. To use
43
+ this plugin, you have to import the :py:mod:`PIL.GdImageFile` module and
44
+ use the :py:func:`PIL.GdImageFile.open()` function.
45
+ """
46
+
47
+ format = "GD"
48
+ format_description = "GD uncompressed images"
49
+
50
+ def _open(self) -> None:
51
+ # Header
52
+ assert self.fp is not None
53
+
54
+ s = self.fp.read(1037)
55
+
56
+ if i16(s) not in [65534, 65535]:
57
+ msg = "Not a valid GD 2.x .gd file"
58
+ raise SyntaxError(msg)
59
+
60
+ self._mode = "P"
61
+ self._size = i16(s, 2), i16(s, 4)
62
+
63
+ true_color = s[6]
64
+ true_color_offset = 2 if true_color else 0
65
+
66
+ # transparency index
67
+ tindex = i32(s, 7 + true_color_offset)
68
+ if tindex < 256:
69
+ self.info["transparency"] = tindex
70
+
71
+ self.palette = ImagePalette.raw(
72
+ "RGBX", s[7 + true_color_offset + 6 : 7 + true_color_offset + 6 + 256 * 4]
73
+ )
74
+
75
+ self.tile = [
76
+ ImageFile._Tile(
77
+ "raw",
78
+ (0, 0) + self.size,
79
+ 7 + true_color_offset + 6 + 256 * 4,
80
+ "L",
81
+ )
82
+ ]
83
+
84
+
85
+ def open(fp: StrOrBytesPath | IO[bytes], mode: str = "r") -> GdImageFile:
86
+ """
87
+ Load texture from a GD image file.
88
+
89
+ :param fp: GD file name, or an opened file handle.
90
+ :param mode: Optional mode. In this version, if the mode argument
91
+ is given, it must be "r".
92
+ :returns: An image instance.
93
+ :raises OSError: If the image could not be read.
94
+ """
95
+ if mode != "r":
96
+ msg = "bad mode"
97
+ raise ValueError(msg)
98
+
99
+ try:
100
+ return GdImageFile(fp)
101
+ except SyntaxError as e:
102
+ msg = "cannot identify this image file"
103
+ raise UnidentifiedImageError(msg) from e
.venv/Lib/site-packages/PIL/GifImagePlugin.py ADDED
@@ -0,0 +1,1223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from functools import cached_property
34
+ from typing import Any, NamedTuple, cast
35
+
36
+ from . import (
37
+ Image,
38
+ ImageChops,
39
+ ImageFile,
40
+ ImageMath,
41
+ ImageOps,
42
+ ImagePalette,
43
+ ImageSequence,
44
+ )
45
+ from ._binary import i16le as i16
46
+ from ._binary import o8
47
+ from ._binary import o16le as o16
48
+ from ._util import DeferredError
49
+
50
+ TYPE_CHECKING = False
51
+ if TYPE_CHECKING:
52
+ from typing import IO, Literal
53
+
54
+ from . import _imaging
55
+ from ._typing import Buffer
56
+
57
+
58
+ class LoadingStrategy(IntEnum):
59
+ """.. versionadded:: 9.1.0"""
60
+
61
+ RGB_AFTER_FIRST = 0
62
+ RGB_AFTER_DIFFERENT_PALETTE_ONLY = 1
63
+ RGB_ALWAYS = 2
64
+
65
+
66
+ #: .. versionadded:: 9.1.0
67
+ LOADING_STRATEGY = LoadingStrategy.RGB_AFTER_FIRST
68
+
69
+ # --------------------------------------------------------------------
70
+ # Identify/read GIF files
71
+
72
+
73
+ def _accept(prefix: bytes) -> bool:
74
+ return prefix.startswith((b"GIF87a", b"GIF89a"))
75
+
76
+
77
+ ##
78
+ # Image plugin for GIF images. This plugin supports both GIF87 and
79
+ # GIF89 images.
80
+
81
+
82
+ class GifImageFile(ImageFile.ImageFile):
83
+ format = "GIF"
84
+ format_description = "Compuserve GIF"
85
+ _close_exclusive_fp_after_loading = False
86
+
87
+ global_palette = None
88
+
89
+ def data(self) -> bytes | None:
90
+ assert self.fp is not None
91
+ s = self.fp.read(1)
92
+ if s and s[0]:
93
+ return self.fp.read(s[0])
94
+ return None
95
+
96
+ def _is_palette_needed(self, p: bytes) -> bool:
97
+ for i in range(0, len(p), 3):
98
+ if not (i // 3 == p[i] == p[i + 1] == p[i + 2]):
99
+ return True
100
+ return False
101
+
102
+ def _open(self) -> None:
103
+ # Screen
104
+ assert self.fp is not None
105
+ s = self.fp.read(13)
106
+ if not _accept(s):
107
+ msg = "not a GIF file"
108
+ raise SyntaxError(msg)
109
+
110
+ self.info["version"] = s[:6]
111
+ self._size = i16(s, 6), i16(s, 8)
112
+ flags = s[10]
113
+ bits = (flags & 7) + 1
114
+
115
+ if flags & 128:
116
+ # get global palette
117
+ self.info["background"] = s[11]
118
+ # check if palette contains colour indices
119
+ p = self.fp.read(3 << bits)
120
+ if self._is_palette_needed(p):
121
+ palette = ImagePalette.raw("RGB", p)
122
+ self.global_palette = self.palette = palette
123
+
124
+ self._fp = self.fp # FIXME: hack
125
+ self.__rewind = self.fp.tell()
126
+ self._n_frames: int | None = None
127
+ self._seek(0) # get ready to read first frame
128
+
129
+ @property
130
+ def n_frames(self) -> int:
131
+ if self._n_frames is None:
132
+ current = self.tell()
133
+ try:
134
+ while True:
135
+ self._seek(self.tell() + 1, False)
136
+ except EOFError:
137
+ self._n_frames = self.tell() + 1
138
+ self.seek(current)
139
+ return self._n_frames
140
+
141
+ @cached_property
142
+ def is_animated(self) -> bool:
143
+ if self._n_frames is not None:
144
+ return self._n_frames != 1
145
+
146
+ current = self.tell()
147
+ if current:
148
+ return True
149
+
150
+ try:
151
+ self._seek(1, False)
152
+ is_animated = True
153
+ except EOFError:
154
+ is_animated = False
155
+
156
+ self.seek(current)
157
+ return is_animated
158
+
159
+ def seek(self, frame: int) -> None:
160
+ if not self._seek_check(frame):
161
+ return
162
+ if frame < self.__frame:
163
+ self._im = None
164
+ self._seek(0)
165
+
166
+ last_frame = self.__frame
167
+ try:
168
+ for f in range(self.__frame + 1, frame + 1):
169
+ self._seek(f)
170
+ except EOFError as e:
171
+ self.seek(last_frame)
172
+ msg = "no more images in GIF file"
173
+ raise EOFError(msg) from e
174
+
175
+ def _seek(self, frame: int, update_image: bool = True) -> None:
176
+ if isinstance(self._fp, DeferredError):
177
+ raise self._fp.ex
178
+ if frame == 0:
179
+ # rewind
180
+ self.__offset = 0
181
+ self.dispose: _imaging.ImagingCore | None = None
182
+ self.__frame = -1
183
+ self._fp.seek(self.__rewind)
184
+ self.disposal_method = 0
185
+ if "comment" in self.info:
186
+ del self.info["comment"]
187
+ else:
188
+ # ensure that the previous frame was loaded
189
+ if self.tile and update_image:
190
+ self.load()
191
+
192
+ if frame != self.__frame + 1:
193
+ msg = f"cannot seek to frame {frame}"
194
+ raise ValueError(msg)
195
+
196
+ self.fp = self._fp
197
+ if self.__offset:
198
+ # backup to last frame
199
+ self.fp.seek(self.__offset)
200
+ while self.data():
201
+ pass
202
+ self.__offset = 0
203
+
204
+ s = self.fp.read(1)
205
+ if not s or s == b";":
206
+ msg = "no more images in GIF file"
207
+ raise EOFError(msg)
208
+
209
+ palette: ImagePalette.ImagePalette | Literal[False] | None = None
210
+
211
+ info: dict[str, Any] = {}
212
+ frame_transparency = None
213
+ interlace = None
214
+ frame_dispose_extent = None
215
+ while True:
216
+ if not s:
217
+ s = self.fp.read(1)
218
+ if not s or s == b";":
219
+ break
220
+
221
+ elif s == b"!":
222
+ #
223
+ # extensions
224
+ #
225
+ s = self.fp.read(1)
226
+ block = self.data()
227
+ if s[0] == 249 and block is not None:
228
+ #
229
+ # graphic control extension
230
+ #
231
+ flags = block[0]
232
+ if flags & 1:
233
+ frame_transparency = block[3]
234
+ info["duration"] = i16(block, 1) * 10
235
+
236
+ # disposal method - find the value of bits 4 - 6
237
+ dispose_bits = 0b00011100 & flags
238
+ dispose_bits = dispose_bits >> 2
239
+ if dispose_bits:
240
+ # only set the dispose if it is not
241
+ # unspecified. I'm not sure if this is
242
+ # correct, but it seems to prevent the last
243
+ # frame from looking odd for some animations
244
+ self.disposal_method = dispose_bits
245
+ elif s[0] == 254:
246
+ #
247
+ # comment extension
248
+ #
249
+ comment = b""
250
+
251
+ # Read this comment block
252
+ while block:
253
+ comment += block
254
+ block = self.data()
255
+
256
+ if "comment" in info:
257
+ # If multiple comment blocks in frame, separate with \n
258
+ info["comment"] += b"\n" + comment
259
+ else:
260
+ info["comment"] = comment
261
+ s = b""
262
+ continue
263
+ elif s[0] == 255 and frame == 0 and block is not None:
264
+ #
265
+ # application extension
266
+ #
267
+ info["extension"] = block, self.fp.tell()
268
+ if block.startswith(b"NETSCAPE2.0"):
269
+ block = self.data()
270
+ if block and len(block) >= 3 and block[0] == 1:
271
+ self.info["loop"] = i16(block, 1)
272
+ while self.data():
273
+ pass
274
+
275
+ elif s == b",":
276
+ #
277
+ # local image
278
+ #
279
+ s = self.fp.read(9)
280
+
281
+ # extent
282
+ x0, y0 = i16(s, 0), i16(s, 2)
283
+ x1, y1 = x0 + i16(s, 4), y0 + i16(s, 6)
284
+ if (x1 > self.size[0] or y1 > self.size[1]) and update_image:
285
+ self._size = max(x1, self.size[0]), max(y1, self.size[1])
286
+ Image._decompression_bomb_check(self._size)
287
+ frame_dispose_extent = x0, y0, x1, y1
288
+ flags = s[8]
289
+
290
+ interlace = (flags & 64) != 0
291
+
292
+ if flags & 128:
293
+ bits = (flags & 7) + 1
294
+ p = self.fp.read(3 << bits)
295
+ if self._is_palette_needed(p):
296
+ palette = ImagePalette.raw("RGB", p)
297
+ else:
298
+ palette = False
299
+
300
+ # image data
301
+ bits = self.fp.read(1)[0]
302
+ self.__offset = self.fp.tell()
303
+ break
304
+ s = b""
305
+
306
+ if interlace is None:
307
+ msg = "image not found in GIF frame"
308
+ raise EOFError(msg)
309
+
310
+ self.__frame = frame
311
+ if not update_image:
312
+ return
313
+
314
+ self.tile = []
315
+
316
+ if self.dispose:
317
+ self.im.paste(self.dispose, self.dispose_extent)
318
+
319
+ self._frame_palette = palette if palette is not None else self.global_palette
320
+ self._frame_transparency = frame_transparency
321
+ if frame == 0:
322
+ if self._frame_palette:
323
+ if LOADING_STRATEGY == LoadingStrategy.RGB_ALWAYS:
324
+ self._mode = "RGBA" if frame_transparency is not None else "RGB"
325
+ else:
326
+ self._mode = "P"
327
+ else:
328
+ self._mode = "L"
329
+
330
+ if palette:
331
+ self.palette = palette
332
+ elif self.global_palette:
333
+ from copy import copy
334
+
335
+ self.palette = copy(self.global_palette)
336
+ else:
337
+ self.palette = None
338
+ else:
339
+ if self.mode == "P":
340
+ if (
341
+ LOADING_STRATEGY != LoadingStrategy.RGB_AFTER_DIFFERENT_PALETTE_ONLY
342
+ or palette
343
+ ):
344
+ if "transparency" in self.info:
345
+ self.im.putpalettealpha(self.info["transparency"], 0)
346
+ self.im = self.im.convert("RGBA", Image.Dither.FLOYDSTEINBERG)
347
+ self._mode = "RGBA"
348
+ del self.info["transparency"]
349
+ else:
350
+ self._mode = "RGB"
351
+ self.im = self.im.convert("RGB", Image.Dither.FLOYDSTEINBERG)
352
+
353
+ def _rgb(color: int) -> tuple[int, int, int]:
354
+ if self._frame_palette:
355
+ if color * 3 + 3 > len(self._frame_palette.palette):
356
+ color = 0
357
+ return cast(
358
+ tuple[int, int, int],
359
+ tuple(self._frame_palette.palette[color * 3 : color * 3 + 3]),
360
+ )
361
+ else:
362
+ return (color, color, color)
363
+
364
+ self.dispose = None
365
+ self.dispose_extent: tuple[int, int, int, int] | None = frame_dispose_extent
366
+ if self.dispose_extent and self.disposal_method >= 2:
367
+ try:
368
+ if self.disposal_method == 2:
369
+ # replace with background colour
370
+
371
+ # only dispose the extent in this frame
372
+ x0, y0, x1, y1 = self.dispose_extent
373
+ dispose_size = (x1 - x0, y1 - y0)
374
+
375
+ Image._decompression_bomb_check(dispose_size)
376
+
377
+ # by convention, attempt to use transparency first
378
+ dispose_mode = "P"
379
+ color = self.info.get("transparency", frame_transparency)
380
+ if color is not None:
381
+ if self.mode in ("RGB", "RGBA"):
382
+ dispose_mode = "RGBA"
383
+ color = _rgb(color) + (0,)
384
+ else:
385
+ color = self.info.get("background", 0)
386
+ if self.mode in ("RGB", "RGBA"):
387
+ dispose_mode = "RGB"
388
+ color = _rgb(color)
389
+ self.dispose = Image.core.fill(dispose_mode, dispose_size, color)
390
+ else:
391
+ # replace with previous contents
392
+ if self._im is not None:
393
+ # only dispose the extent in this frame
394
+ self.dispose = self._crop(self.im, self.dispose_extent)
395
+ elif frame_transparency is not None:
396
+ x0, y0, x1, y1 = self.dispose_extent
397
+ dispose_size = (x1 - x0, y1 - y0)
398
+
399
+ Image._decompression_bomb_check(dispose_size)
400
+ dispose_mode = "P"
401
+ color = frame_transparency
402
+ if self.mode in ("RGB", "RGBA"):
403
+ dispose_mode = "RGBA"
404
+ color = _rgb(frame_transparency) + (0,)
405
+ self.dispose = Image.core.fill(
406
+ dispose_mode, dispose_size, color
407
+ )
408
+ except AttributeError:
409
+ pass
410
+
411
+ if interlace is not None:
412
+ transparency = -1
413
+ if frame_transparency is not None:
414
+ if frame == 0:
415
+ if LOADING_STRATEGY != LoadingStrategy.RGB_ALWAYS:
416
+ self.info["transparency"] = frame_transparency
417
+ elif self.mode not in ("RGB", "RGBA"):
418
+ transparency = frame_transparency
419
+ self.tile = [
420
+ ImageFile._Tile(
421
+ "gif",
422
+ (x0, y0, x1, y1),
423
+ self.__offset,
424
+ (bits, interlace, transparency),
425
+ )
426
+ ]
427
+
428
+ if info.get("comment"):
429
+ self.info["comment"] = info["comment"]
430
+ for k in ["duration", "extension"]:
431
+ if k in info:
432
+ self.info[k] = info[k]
433
+ elif k in self.info:
434
+ del self.info[k]
435
+
436
+ def load_prepare(self) -> None:
437
+ temp_mode = "P" if self._frame_palette else "L"
438
+ self._prev_im = None
439
+ if self.__frame == 0:
440
+ if self._frame_transparency is not None:
441
+ self.im = Image.core.fill(
442
+ temp_mode, self.size, self._frame_transparency
443
+ )
444
+ elif self.mode in ("RGB", "RGBA"):
445
+ self._prev_im = self.im
446
+ if self._frame_palette:
447
+ self.im = Image.core.fill("P", self.size, self._frame_transparency or 0)
448
+ self.im.putpalette("RGB", *self._frame_palette.getdata())
449
+ else:
450
+ self._im = None
451
+ if not self._prev_im and self._im is not None and self.size != self.im.size:
452
+ expanded_im = Image.core.fill(self.im.mode, self.size)
453
+ if self._frame_palette:
454
+ expanded_im.putpalette("RGB", *self._frame_palette.getdata())
455
+ expanded_im.paste(self.im, (0, 0) + self.im.size)
456
+
457
+ self.im = expanded_im
458
+ self._mode = temp_mode
459
+ self._frame_palette = None
460
+
461
+ super().load_prepare()
462
+
463
+ def load_end(self) -> None:
464
+ if self.__frame == 0:
465
+ if self.mode == "P" and LOADING_STRATEGY == LoadingStrategy.RGB_ALWAYS:
466
+ if self._frame_transparency is not None:
467
+ self.im.putpalettealpha(self._frame_transparency, 0)
468
+ self._mode = "RGBA"
469
+ else:
470
+ self._mode = "RGB"
471
+ self.im = self.im.convert(self.mode, Image.Dither.FLOYDSTEINBERG)
472
+ return
473
+ if not self._prev_im:
474
+ return
475
+ if self.size != self._prev_im.size:
476
+ if self._frame_transparency is not None:
477
+ expanded_im = Image.core.fill("RGBA", self.size)
478
+ else:
479
+ expanded_im = Image.core.fill("P", self.size)
480
+ expanded_im.putpalette("RGB", "RGB", self.im.getpalette())
481
+ expanded_im = expanded_im.convert("RGB")
482
+ expanded_im.paste(self._prev_im, (0, 0) + self._prev_im.size)
483
+
484
+ self._prev_im = expanded_im
485
+ assert self._prev_im is not None
486
+ if self._frame_transparency is not None:
487
+ if self.mode == "L":
488
+ frame_im = self.im.convert_transparent("LA", self._frame_transparency)
489
+ else:
490
+ self.im.putpalettealpha(self._frame_transparency, 0)
491
+ frame_im = self.im.convert("RGBA")
492
+ else:
493
+ frame_im = self.im.convert("RGB")
494
+
495
+ assert self.dispose_extent is not None
496
+ frame_im = self._crop(frame_im, self.dispose_extent)
497
+
498
+ self.im = self._prev_im
499
+ self._mode = self.im.mode
500
+ if frame_im.mode in ("LA", "RGBA"):
501
+ self.im.paste(frame_im, self.dispose_extent, frame_im)
502
+ else:
503
+ self.im.paste(frame_im, self.dispose_extent)
504
+
505
+ def tell(self) -> int:
506
+ return self.__frame
507
+
508
+
509
+ # --------------------------------------------------------------------
510
+ # Write GIF files
511
+
512
+
513
+ RAWMODE = {"1": "L", "L": "L", "P": "P"}
514
+
515
+
516
+ def _normalize_mode(im: Image.Image) -> Image.Image:
517
+ """
518
+ Takes an image (or frame), returns an image in a mode that is appropriate
519
+ for saving in a Gif.
520
+
521
+ It may return the original image, or it may return an image converted to
522
+ palette or 'L' mode.
523
+
524
+ :param im: Image object
525
+ :returns: Image object
526
+ """
527
+ if im.mode in RAWMODE:
528
+ im.load()
529
+ return im
530
+ if Image.getmodebase(im.mode) == "RGB":
531
+ im = im.convert("P", palette=Image.Palette.ADAPTIVE)
532
+ assert im.palette is not None
533
+ if im.palette.mode == "RGBA":
534
+ for rgba in im.palette.colors:
535
+ if rgba[3] == 0:
536
+ im.info["transparency"] = im.palette.colors[rgba]
537
+ break
538
+ return im
539
+ return im.convert("L")
540
+
541
+
542
+ _Palette = bytes | bytearray | list[int] | ImagePalette.ImagePalette
543
+
544
+
545
+ def _normalize_palette(
546
+ im: Image.Image, palette: _Palette | None, info: dict[str, Any]
547
+ ) -> Image.Image:
548
+ """
549
+ Normalizes the palette for image.
550
+ - Sets the palette to the incoming palette, if provided.
551
+ - Ensures that there's a palette for L mode images
552
+ - Optimizes the palette if necessary/desired.
553
+
554
+ :param im: Image object
555
+ :param palette: bytes object containing the source palette, or ....
556
+ :param info: encoderinfo
557
+ :returns: Image object
558
+ """
559
+ source_palette = None
560
+ if palette:
561
+ # a bytes palette
562
+ if isinstance(palette, (bytes, bytearray, list)):
563
+ source_palette = bytearray(palette[:768])
564
+ if isinstance(palette, ImagePalette.ImagePalette):
565
+ source_palette = bytearray(palette.palette)
566
+
567
+ if im.mode == "P":
568
+ if not source_palette:
569
+ im_palette = im.getpalette(None)
570
+ assert im_palette is not None
571
+ source_palette = bytearray(im_palette)
572
+ else: # L-mode
573
+ if not source_palette:
574
+ source_palette = bytearray(i // 3 for i in range(768))
575
+ im.palette = ImagePalette.ImagePalette("RGB", palette=source_palette)
576
+ assert source_palette is not None
577
+
578
+ if palette:
579
+ used_palette_colors: list[int | None] = []
580
+ assert im.palette is not None
581
+ for i in range(0, len(source_palette), 3):
582
+ source_color = tuple(source_palette[i : i + 3])
583
+ index = im.palette.colors.get(source_color)
584
+ if index in used_palette_colors:
585
+ index = None
586
+ used_palette_colors.append(index)
587
+ for i, index in enumerate(used_palette_colors):
588
+ if index is None:
589
+ for j in range(len(used_palette_colors)):
590
+ if j not in used_palette_colors:
591
+ used_palette_colors[i] = j
592
+ break
593
+ dest_map: list[int] = []
594
+ for index in used_palette_colors:
595
+ assert index is not None
596
+ dest_map.append(index)
597
+ im = im.remap_palette(dest_map)
598
+ else:
599
+ optimized_palette_colors = _get_optimize(im, info)
600
+ if optimized_palette_colors is not None:
601
+ im = im.remap_palette(optimized_palette_colors, source_palette)
602
+ if "transparency" in info:
603
+ try:
604
+ info["transparency"] = optimized_palette_colors.index(
605
+ info["transparency"]
606
+ )
607
+ except ValueError:
608
+ del info["transparency"]
609
+ return im
610
+
611
+ assert im.palette is not None
612
+ im.palette.palette = source_palette
613
+ return im
614
+
615
+
616
+ def _write_single_frame(
617
+ im: Image.Image,
618
+ fp: IO[bytes],
619
+ palette: _Palette | None,
620
+ ) -> None:
621
+ im_out = _normalize_mode(im)
622
+ for k, v in im_out.info.items():
623
+ if isinstance(k, str):
624
+ im.encoderinfo.setdefault(k, v)
625
+ im_out = _normalize_palette(im_out, palette, im.encoderinfo)
626
+
627
+ for s in _get_global_header(im_out, im.encoderinfo):
628
+ fp.write(s)
629
+
630
+ # local image header
631
+ flags = 0
632
+ if get_interlace(im):
633
+ flags = flags | 64
634
+ _write_local_header(fp, im, (0, 0), flags)
635
+
636
+ im_out.encoderconfig = (8, get_interlace(im))
637
+ ImageFile._save(
638
+ im_out, fp, [ImageFile._Tile("gif", (0, 0) + im.size, 0, RAWMODE[im_out.mode])]
639
+ )
640
+
641
+ fp.write(b"\0") # end of image data
642
+
643
+
644
+ def _getbbox(
645
+ base_im: Image.Image, im_frame: Image.Image
646
+ ) -> tuple[Image.Image, tuple[int, int, int, int] | None]:
647
+ palette_bytes = [
648
+ bytes(im.palette.palette) if im.palette else b"" for im in (base_im, im_frame)
649
+ ]
650
+ if palette_bytes[0] != palette_bytes[1]:
651
+ im_frame = im_frame.convert("RGBA")
652
+ base_im = base_im.convert("RGBA")
653
+ delta = ImageChops.subtract_modulo(im_frame, base_im)
654
+ return delta, delta.getbbox(alpha_only=False)
655
+
656
+
657
+ class _Frame(NamedTuple):
658
+ im: Image.Image
659
+ bbox: tuple[int, int, int, int] | None
660
+ encoderinfo: dict[str, Any]
661
+
662
+
663
+ def _write_multiple_frames(
664
+ im: Image.Image, fp: IO[bytes], palette: _Palette | None
665
+ ) -> bool:
666
+ duration = im.encoderinfo.get("duration")
667
+ disposal = im.encoderinfo.get("disposal", im.info.get("disposal"))
668
+
669
+ im_frames: list[_Frame] = []
670
+ previous_im: Image.Image | None = None
671
+ frame_count = 0
672
+ background_im = None
673
+ for imSequence in itertools.chain([im], im.encoderinfo.get("append_images", [])):
674
+ for im_frame in ImageSequence.Iterator(imSequence):
675
+ # a copy is required here since seek can still mutate the image
676
+ im_frame = _normalize_mode(im_frame.copy())
677
+ if frame_count == 0:
678
+ for k, v in im_frame.info.items():
679
+ if k == "transparency":
680
+ continue
681
+ if isinstance(k, str):
682
+ im.encoderinfo.setdefault(k, v)
683
+
684
+ encoderinfo = im.encoderinfo.copy()
685
+ if "transparency" in im_frame.info:
686
+ encoderinfo.setdefault("transparency", im_frame.info["transparency"])
687
+ im_frame = _normalize_palette(im_frame, palette, encoderinfo)
688
+ if isinstance(duration, (list, tuple)):
689
+ encoderinfo["duration"] = duration[frame_count]
690
+ elif duration is None and "duration" in im_frame.info:
691
+ encoderinfo["duration"] = im_frame.info["duration"]
692
+ if isinstance(disposal, (list, tuple)):
693
+ encoderinfo["disposal"] = disposal[frame_count]
694
+ frame_count += 1
695
+
696
+ diff_frame = None
697
+ if im_frames and previous_im:
698
+ # delta frame
699
+ delta, bbox = _getbbox(previous_im, im_frame)
700
+ if not bbox:
701
+ # This frame is identical to the previous frame
702
+ if encoderinfo.get("duration"):
703
+ im_frames[-1].encoderinfo["duration"] += encoderinfo["duration"]
704
+ continue
705
+ if im_frames[-1].encoderinfo.get("disposal") == 2:
706
+ # To appear correctly in viewers using a convention,
707
+ # only consider transparency, and not background color
708
+ color = im.encoderinfo.get(
709
+ "transparency", im.info.get("transparency")
710
+ )
711
+ if color is not None:
712
+ if background_im is None:
713
+ background = _get_background(im_frame, color)
714
+ background_im = Image.new("P", im_frame.size, background)
715
+ first_palette = im_frames[0].im.palette
716
+ assert first_palette is not None
717
+ background_im.putpalette(first_palette, first_palette.mode)
718
+ bbox = _getbbox(background_im, im_frame)[1]
719
+ else:
720
+ bbox = (0, 0) + im_frame.size
721
+ elif encoderinfo.get("optimize") and im_frame.mode != "1":
722
+ if "transparency" not in encoderinfo:
723
+ assert im_frame.palette is not None
724
+ try:
725
+ encoderinfo["transparency"] = (
726
+ im_frame.palette._new_color_index(im_frame)
727
+ )
728
+ except ValueError:
729
+ pass
730
+ if "transparency" in encoderinfo:
731
+ # When the delta is zero, fill the image with transparency
732
+ diff_frame = im_frame.copy()
733
+ fill = Image.new("P", delta.size, encoderinfo["transparency"])
734
+ if delta.mode == "RGBA":
735
+ r, g, b, a = delta.split()
736
+ mask = ImageMath.lambda_eval(
737
+ lambda args: args["convert"](
738
+ args["max"](
739
+ args["max"](
740
+ args["max"](args["r"], args["g"]), args["b"]
741
+ ),
742
+ args["a"],
743
+ )
744
+ * 255,
745
+ "1",
746
+ ),
747
+ r=r,
748
+ g=g,
749
+ b=b,
750
+ a=a,
751
+ )
752
+ else:
753
+ if delta.mode == "P":
754
+ # Convert to L without considering palette
755
+ delta_l = Image.new("L", delta.size)
756
+ delta_l.putdata(delta.get_flattened_data())
757
+ delta = delta_l
758
+ mask = ImageMath.lambda_eval(
759
+ lambda args: args["convert"](args["im"] * 255, "1"),
760
+ im=delta,
761
+ )
762
+ diff_frame.paste(fill, mask=ImageOps.invert(mask))
763
+ else:
764
+ bbox = None
765
+ previous_im = im_frame
766
+ im_frames.append(_Frame(diff_frame or im_frame, bbox, encoderinfo))
767
+
768
+ if len(im_frames) == 1:
769
+ if "duration" in im.encoderinfo:
770
+ # Since multiple frames will not be written, use the combined duration
771
+ im.encoderinfo["duration"] = im_frames[0].encoderinfo["duration"]
772
+ return False
773
+
774
+ for frame_data in im_frames:
775
+ im_frame = frame_data.im
776
+ if not frame_data.bbox:
777
+ # global header
778
+ for s in _get_global_header(im_frame, frame_data.encoderinfo):
779
+ fp.write(s)
780
+ offset = (0, 0)
781
+ else:
782
+ # compress difference
783
+ if not palette:
784
+ frame_data.encoderinfo["include_color_table"] = True
785
+
786
+ if frame_data.bbox != (0, 0) + im_frame.size:
787
+ im_frame = im_frame.crop(frame_data.bbox)
788
+ offset = frame_data.bbox[:2]
789
+ _write_frame_data(fp, im_frame, offset, frame_data.encoderinfo)
790
+ return True
791
+
792
+
793
+ def _save_all(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
794
+ _save(im, fp, filename, save_all=True)
795
+
796
+
797
+ def _save(
798
+ im: Image.Image, fp: IO[bytes], filename: str | bytes, save_all: bool = False
799
+ ) -> None:
800
+ # header
801
+ if "palette" in im.encoderinfo or "palette" in im.info:
802
+ palette = im.encoderinfo.get("palette", im.info.get("palette"))
803
+ else:
804
+ palette = None
805
+ im.encoderinfo.setdefault("optimize", True)
806
+
807
+ if not save_all or not _write_multiple_frames(im, fp, palette):
808
+ _write_single_frame(im, fp, palette)
809
+
810
+ fp.write(b";") # end of file
811
+
812
+ if hasattr(fp, "flush"):
813
+ fp.flush()
814
+
815
+
816
+ def get_interlace(im: Image.Image) -> int:
817
+ interlace = im.encoderinfo.get("interlace", 1)
818
+
819
+ # workaround for @PIL153
820
+ if min(im.size) < 16:
821
+ interlace = 0
822
+
823
+ return interlace
824
+
825
+
826
+ def _write_local_header(
827
+ fp: IO[bytes], im: Image.Image, offset: tuple[int, int], flags: int
828
+ ) -> None:
829
+ try:
830
+ transparency = im.encoderinfo["transparency"]
831
+ except KeyError:
832
+ transparency = None
833
+
834
+ if "duration" in im.encoderinfo:
835
+ duration = int(im.encoderinfo["duration"] / 10)
836
+ else:
837
+ duration = 0
838
+
839
+ disposal = int(im.encoderinfo.get("disposal", 0))
840
+
841
+ if transparency is not None or duration != 0 or disposal:
842
+ packed_flag = 1 if transparency is not None else 0
843
+ packed_flag |= disposal << 2
844
+
845
+ fp.write(
846
+ b"!"
847
+ + o8(249) # extension intro
848
+ + o8(4) # length
849
+ + o8(packed_flag) # packed fields
850
+ + o16(duration) # duration
851
+ + o8(transparency or 0) # transparency index
852
+ + o8(0)
853
+ )
854
+
855
+ include_color_table = im.encoderinfo.get("include_color_table")
856
+ if include_color_table:
857
+ palette_bytes = _get_palette_bytes(im)
858
+ color_table_size = _get_color_table_size(palette_bytes)
859
+ if color_table_size:
860
+ flags = flags | 128 # local color table flag
861
+ flags = flags | color_table_size
862
+
863
+ fp.write(
864
+ b","
865
+ + o16(offset[0]) # offset
866
+ + o16(offset[1])
867
+ + o16(im.size[0]) # size
868
+ + o16(im.size[1])
869
+ + o8(flags) # flags
870
+ )
871
+ if include_color_table and color_table_size:
872
+ fp.write(_get_header_palette(palette_bytes))
873
+ fp.write(o8(8)) # bits
874
+
875
+
876
+ def _save_netpbm(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
877
+ # Unused by default.
878
+ # To use, uncomment the register_save call at the end of the file.
879
+ #
880
+ # If you need real GIF compression and/or RGB quantization, you
881
+ # can use the external NETPBM/PBMPLUS utilities. See comments
882
+ # below for information on how to enable this.
883
+ tempfile = im._dump()
884
+
885
+ try:
886
+ with open(filename, "wb") as f:
887
+ if im.mode != "RGB":
888
+ subprocess.check_call(
889
+ ["ppmtogif", tempfile], stdout=f, stderr=subprocess.DEVNULL
890
+ )
891
+ else:
892
+ # Pipe ppmquant output into ppmtogif
893
+ # "ppmquant 256 %s | ppmtogif > %s" % (tempfile, filename)
894
+ quant_cmd = ["ppmquant", "256", tempfile]
895
+ togif_cmd = ["ppmtogif"]
896
+ quant_proc = subprocess.Popen(
897
+ quant_cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL
898
+ )
899
+ togif_proc = subprocess.Popen(
900
+ togif_cmd,
901
+ stdin=quant_proc.stdout,
902
+ stdout=f,
903
+ stderr=subprocess.DEVNULL,
904
+ )
905
+
906
+ # Allow ppmquant to receive SIGPIPE if ppmtogif exits
907
+ assert quant_proc.stdout is not None
908
+ quant_proc.stdout.close()
909
+
910
+ retcode = quant_proc.wait()
911
+ if retcode:
912
+ raise subprocess.CalledProcessError(retcode, quant_cmd)
913
+
914
+ retcode = togif_proc.wait()
915
+ if retcode:
916
+ raise subprocess.CalledProcessError(retcode, togif_cmd)
917
+ finally:
918
+ try:
919
+ os.unlink(tempfile)
920
+ except OSError:
921
+ pass
922
+
923
+
924
+ # Force optimization so that we can test performance against
925
+ # cases where it took lots of memory and time previously.
926
+ _FORCE_OPTIMIZE = False
927
+
928
+
929
+ def _get_optimize(im: Image.Image, info: dict[str, Any]) -> list[int] | None:
930
+ """
931
+ Palette optimization is a potentially expensive operation.
932
+
933
+ This function determines if the palette should be optimized using
934
+ some heuristics, then returns the list of palette entries in use.
935
+
936
+ :param im: Image object
937
+ :param info: encoderinfo
938
+ :returns: list of indexes of palette entries in use, or None
939
+ """
940
+ if (
941
+ im.mode in ("P", "L")
942
+ and info
943
+ and info.get("optimize")
944
+ and im.width != 0
945
+ and im.height != 0
946
+ ):
947
+ # Potentially expensive operation.
948
+
949
+ # The palette saves 3 bytes per color not used, but palette
950
+ # lengths are restricted to 3*(2**N) bytes. Max saving would
951
+ # be 768 -> 6 bytes if we went all the way down to 2 colors.
952
+ # * If we're over 128 colors, we can't save any space.
953
+ # * If there aren't any holes, it's not worth collapsing.
954
+ # * If we have a 'large' image, the palette is in the noise.
955
+
956
+ # create the new palette if not every color is used
957
+ optimise = _FORCE_OPTIMIZE or im.mode == "L"
958
+ if optimise or im.width * im.height < 512 * 512:
959
+ # check which colors are used
960
+ used_palette_colors = []
961
+ for i, count in enumerate(im.histogram()):
962
+ if count:
963
+ used_palette_colors.append(i)
964
+
965
+ if optimise or max(used_palette_colors) >= len(used_palette_colors):
966
+ return used_palette_colors
967
+
968
+ assert im.palette is not None
969
+ num_palette_colors = len(im.palette.palette) // Image.getmodebands(
970
+ im.palette.mode
971
+ )
972
+ current_palette_size = 1 << (num_palette_colors - 1).bit_length()
973
+ if (
974
+ # check that the palette would become smaller when saved
975
+ len(used_palette_colors) <= current_palette_size // 2
976
+ # check that the palette is not already the smallest possible size
977
+ and current_palette_size > 2
978
+ ):
979
+ return used_palette_colors
980
+ return None
981
+
982
+
983
+ def _get_color_table_size(palette_bytes: bytes) -> int:
984
+ # calculate the palette size for the header
985
+ if not palette_bytes:
986
+ return 0
987
+ elif len(palette_bytes) < 9:
988
+ return 1
989
+ else:
990
+ return math.ceil(math.log(len(palette_bytes) // 3, 2)) - 1
991
+
992
+
993
+ def _get_header_palette(palette_bytes: bytes) -> bytes:
994
+ """
995
+ Returns the palette, null padded to the next power of 2 (*3) bytes
996
+ suitable for direct inclusion in the GIF header
997
+
998
+ :param palette_bytes: Unpadded palette bytes, in RGBRGB form
999
+ :returns: Null padded palette
1000
+ """
1001
+ color_table_size = _get_color_table_size(palette_bytes)
1002
+
1003
+ # add the missing amount of bytes
1004
+ # the palette has to be 2<<n in size
1005
+ actual_target_size_diff = (2 << color_table_size) - len(palette_bytes) // 3
1006
+ if actual_target_size_diff > 0:
1007
+ palette_bytes += o8(0) * 3 * actual_target_size_diff
1008
+ return palette_bytes
1009
+
1010
+
1011
+ def _get_palette_bytes(im: Image.Image) -> bytes:
1012
+ """
1013
+ Gets the palette for inclusion in the gif header
1014
+
1015
+ :param im: Image object
1016
+ :returns: Bytes, len<=768 suitable for inclusion in gif header
1017
+ """
1018
+ if not im.palette:
1019
+ return b""
1020
+
1021
+ palette = bytes(im.palette.palette)
1022
+ if im.palette.mode == "RGBA":
1023
+ palette = b"".join(palette[i * 4 : i * 4 + 3] for i in range(len(palette) // 3))
1024
+ return palette
1025
+
1026
+
1027
+ def _get_background(
1028
+ im: Image.Image,
1029
+ info_background: int | tuple[int, int, int] | tuple[int, int, int, int] | None,
1030
+ ) -> int:
1031
+ background = 0
1032
+ if info_background:
1033
+ if isinstance(info_background, tuple):
1034
+ # WebPImagePlugin stores an RGBA value in info["background"]
1035
+ # So it must be converted to the same format as GifImagePlugin's
1036
+ # info["background"] - a global color table index
1037
+ assert im.palette is not None
1038
+ try:
1039
+ background = im.palette.getcolor(info_background, im)
1040
+ except ValueError as e:
1041
+ if str(e) not in (
1042
+ # If all 256 colors are in use,
1043
+ # then there is no need for the background color
1044
+ "cannot allocate more than 256 colors",
1045
+ # Ignore non-opaque WebP background
1046
+ "cannot add non-opaque RGBA color to RGB palette",
1047
+ ):
1048
+ raise
1049
+ else:
1050
+ background = info_background
1051
+ return background
1052
+
1053
+
1054
+ def _get_global_header(im: Image.Image, info: dict[str, Any]) -> list[bytes]:
1055
+ """Return a list of strings representing a GIF header"""
1056
+
1057
+ # Header Block
1058
+ # https://www.matthewflickinger.com/lab/whatsinagif/bits_and_bytes.asp
1059
+
1060
+ version = b"87a"
1061
+ if im.info.get("version") == b"89a" or (
1062
+ info
1063
+ and (
1064
+ "transparency" in info
1065
+ or info.get("loop") is not None
1066
+ or info.get("duration")
1067
+ or info.get("comment")
1068
+ )
1069
+ ):
1070
+ version = b"89a"
1071
+
1072
+ background = _get_background(im, info.get("background"))
1073
+
1074
+ palette_bytes = _get_palette_bytes(im)
1075
+ color_table_size = _get_color_table_size(palette_bytes)
1076
+
1077
+ header = [
1078
+ b"GIF" # signature
1079
+ + version # version
1080
+ + o16(im.size[0]) # canvas width
1081
+ + o16(im.size[1]), # canvas height
1082
+ # Logical Screen Descriptor
1083
+ # size of global color table + global color table flag
1084
+ o8(color_table_size + 128), # packed fields
1085
+ # background + reserved/aspect
1086
+ o8(background) + o8(0),
1087
+ # Global Color Table
1088
+ _get_header_palette(palette_bytes),
1089
+ ]
1090
+ if info.get("loop") is not None:
1091
+ header.append(
1092
+ b"!"
1093
+ + o8(255) # extension intro
1094
+ + o8(11)
1095
+ + b"NETSCAPE2.0"
1096
+ + o8(3)
1097
+ + o8(1)
1098
+ + o16(info["loop"]) # number of loops
1099
+ + o8(0)
1100
+ )
1101
+ if info.get("comment"):
1102
+ comment_block = b"!" + o8(254) # extension intro
1103
+
1104
+ comment = info["comment"]
1105
+ if isinstance(comment, str):
1106
+ comment = comment.encode()
1107
+ for i in range(0, len(comment), 255):
1108
+ subblock = comment[i : i + 255]
1109
+ comment_block += o8(len(subblock)) + subblock
1110
+
1111
+ comment_block += o8(0)
1112
+ header.append(comment_block)
1113
+ return header
1114
+
1115
+
1116
+ def _write_frame_data(
1117
+ fp: IO[bytes],
1118
+ im_frame: Image.Image,
1119
+ offset: tuple[int, int],
1120
+ params: dict[str, Any],
1121
+ ) -> None:
1122
+ try:
1123
+ im_frame.encoderinfo = params
1124
+
1125
+ # local image header
1126
+ _write_local_header(fp, im_frame, offset, 0)
1127
+
1128
+ ImageFile._save(
1129
+ im_frame,
1130
+ fp,
1131
+ [ImageFile._Tile("gif", (0, 0) + im_frame.size, 0, RAWMODE[im_frame.mode])],
1132
+ )
1133
+
1134
+ fp.write(b"\0") # end of image data
1135
+ finally:
1136
+ del im_frame.encoderinfo
1137
+
1138
+
1139
+ # --------------------------------------------------------------------
1140
+ # Legacy GIF utilities
1141
+
1142
+
1143
+ def getheader(
1144
+ im: Image.Image, palette: _Palette | None = None, info: dict[str, Any] | None = None
1145
+ ) -> tuple[list[bytes], list[int] | None]:
1146
+ """
1147
+ Legacy Method to get Gif data from image.
1148
+
1149
+ Warning:: May modify image data.
1150
+
1151
+ :param im: Image object
1152
+ :param palette: bytes object containing the source palette, or ....
1153
+ :param info: encoderinfo
1154
+ :returns: tuple of(list of header items, optimized palette)
1155
+
1156
+ """
1157
+ if info is None:
1158
+ info = {}
1159
+
1160
+ used_palette_colors = _get_optimize(im, info)
1161
+
1162
+ if "background" not in info and "background" in im.info:
1163
+ info["background"] = im.info["background"]
1164
+
1165
+ im_mod = _normalize_palette(im, palette, info)
1166
+ im.palette = im_mod.palette
1167
+ im.im = im_mod.im
1168
+ header = _get_global_header(im, info)
1169
+
1170
+ return header, used_palette_colors
1171
+
1172
+
1173
+ def getdata(
1174
+ im: Image.Image, offset: tuple[int, int] = (0, 0), **params: Any
1175
+ ) -> list[bytes]:
1176
+ """
1177
+ Legacy Method
1178
+
1179
+ Return a list of strings representing this image.
1180
+ The first string is a local image header, the rest contains
1181
+ encoded image data.
1182
+
1183
+ To specify duration, add the time in milliseconds,
1184
+ e.g. ``getdata(im_frame, duration=1000)``
1185
+
1186
+ :param im: Image object
1187
+ :param offset: Tuple of (x, y) pixels. Defaults to (0, 0)
1188
+ :param \\**params: e.g. duration or other encoder info parameters
1189
+ :returns: List of bytes containing GIF encoded frame data
1190
+
1191
+ """
1192
+ from io import BytesIO
1193
+
1194
+ class Collector(BytesIO):
1195
+ data = []
1196
+
1197
+ def write(self, data: Buffer) -> int:
1198
+ self.data.append(data)
1199
+ return len(data)
1200
+
1201
+ im.load() # make sure raster data is available
1202
+
1203
+ fp = Collector()
1204
+
1205
+ _write_frame_data(fp, im, offset, params)
1206
+
1207
+ return fp.data
1208
+
1209
+
1210
+ # --------------------------------------------------------------------
1211
+ # Registry
1212
+
1213
+ Image.register_open(GifImageFile.format, GifImageFile, _accept)
1214
+ Image.register_save(GifImageFile.format, _save)
1215
+ Image.register_save_all(GifImageFile.format, _save_all)
1216
+ Image.register_extension(GifImageFile.format, ".gif")
1217
+ Image.register_mime(GifImageFile.format, "image/gif")
1218
+
1219
+ #
1220
+ # Uncomment the following line if you wish to use NETPBM/PBMPLUS
1221
+ # instead of the built-in "uncompressed" GIF encoder
1222
+
1223
+ # Image.register_save(GifImageFile.format, _save_netpbm)
.venv/Lib/site-packages/PIL/GimpGradientFile.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
22
+ from __future__ import annotations
23
+
24
+ from math import log, pi, sin, sqrt
25
+
26
+ from ._binary import o8
27
+
28
+ TYPE_CHECKING = False
29
+ if TYPE_CHECKING:
30
+ from collections.abc import Callable
31
+ from typing import IO
32
+
33
+ EPSILON = 1e-10
34
+ """""" # Enable auto-doc for data member
35
+
36
+
37
+ def linear(middle: float, pos: float) -> float:
38
+ if pos <= middle:
39
+ if middle < EPSILON:
40
+ return 0.0
41
+ else:
42
+ return 0.5 * pos / middle
43
+ else:
44
+ pos = pos - middle
45
+ middle = 1.0 - middle
46
+ if middle < EPSILON:
47
+ return 1.0
48
+ else:
49
+ return 0.5 + 0.5 * pos / middle
50
+
51
+
52
+ def curved(middle: float, pos: float) -> float:
53
+ return pos ** (log(0.5) / log(max(middle, EPSILON)))
54
+
55
+
56
+ def sine(middle: float, pos: float) -> float:
57
+ return (sin((-pi / 2.0) + pi * linear(middle, pos)) + 1.0) / 2.0
58
+
59
+
60
+ def sphere_increasing(middle: float, pos: float) -> float:
61
+ return sqrt(1.0 - (linear(middle, pos) - 1.0) ** 2)
62
+
63
+
64
+ def sphere_decreasing(middle: float, pos: float) -> float:
65
+ return 1.0 - sqrt(1.0 - linear(middle, pos) ** 2)
66
+
67
+
68
+ SEGMENTS = [linear, curved, sine, sphere_increasing, sphere_decreasing]
69
+ """""" # Enable auto-doc for data member
70
+
71
+
72
+ class GradientFile:
73
+ gradient: (
74
+ list[
75
+ tuple[
76
+ float,
77
+ float,
78
+ float,
79
+ list[float],
80
+ list[float],
81
+ Callable[[float, float], float],
82
+ ]
83
+ ]
84
+ | None
85
+ ) = None
86
+
87
+ def getpalette(self, entries: int = 256) -> tuple[bytes, str]:
88
+ assert self.gradient is not None
89
+ palette = []
90
+
91
+ ix = 0
92
+ x0, x1, xm, rgb0, rgb1, segment = self.gradient[ix]
93
+
94
+ for i in range(entries):
95
+ x = i / (entries - 1)
96
+
97
+ while x1 < x:
98
+ ix += 1
99
+ x0, x1, xm, rgb0, rgb1, segment = self.gradient[ix]
100
+
101
+ w = x1 - x0
102
+
103
+ if w < EPSILON:
104
+ scale = segment(0.5, 0.5)
105
+ else:
106
+ scale = segment((xm - x0) / w, (x - x0) / w)
107
+
108
+ # expand to RGBA
109
+ r = o8(int(255 * ((rgb1[0] - rgb0[0]) * scale + rgb0[0]) + 0.5))
110
+ g = o8(int(255 * ((rgb1[1] - rgb0[1]) * scale + rgb0[1]) + 0.5))
111
+ b = o8(int(255 * ((rgb1[2] - rgb0[2]) * scale + rgb0[2]) + 0.5))
112
+ a = o8(int(255 * ((rgb1[3] - rgb0[3]) * scale + rgb0[3]) + 0.5))
113
+
114
+ # add to palette
115
+ palette.append(r + g + b + a)
116
+
117
+ return b"".join(palette), "RGBA"
118
+
119
+
120
+ class GimpGradientFile(GradientFile):
121
+ """File handler for GIMP's gradient format."""
122
+
123
+ def __init__(self, fp: IO[bytes]) -> None:
124
+ if not fp.readline().startswith(b"GIMP Gradient"):
125
+ msg = "not a GIMP gradient file"
126
+ raise SyntaxError(msg)
127
+
128
+ line = fp.readline()
129
+
130
+ # GIMP 1.2 gradient files don't contain a name, but GIMP 1.3 files do
131
+ if line.startswith(b"Name: "):
132
+ line = fp.readline().strip()
133
+
134
+ count = int(line)
135
+
136
+ self.gradient = []
137
+
138
+ for i in range(count):
139
+ s = fp.readline().split()
140
+ w = [float(x) for x in s[:11]]
141
+
142
+ x0, x1 = w[0], w[2]
143
+ xm = w[1]
144
+ rgb0 = w[3:7]
145
+ rgb1 = w[7:11]
146
+
147
+ segment = SEGMENTS[int(s[11])]
148
+ cspace = int(s[12])
149
+
150
+ if cspace != 0:
151
+ msg = "cannot handle HSV colour space"
152
+ raise OSError(msg)
153
+
154
+ self.gradient.append((x0, x1, xm, rgb0, rgb1, segment))
.venv/Lib/site-packages/PIL/GimpPaletteFile.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from io import BytesIO
20
+
21
+ TYPE_CHECKING = False
22
+ if TYPE_CHECKING:
23
+ from typing import IO
24
+
25
+
26
+ class GimpPaletteFile:
27
+ """File handler for GIMP's palette format."""
28
+
29
+ rawmode = "RGB"
30
+
31
+ def _read(self, fp: IO[bytes], limit: bool = True) -> None:
32
+ if not fp.readline().startswith(b"GIMP Palette"):
33
+ msg = "not a GIMP palette file"
34
+ raise SyntaxError(msg)
35
+
36
+ palette: list[int] = []
37
+ i = 0
38
+ while True:
39
+ if limit and i == 256 + 3:
40
+ break
41
+
42
+ i += 1
43
+ s = fp.readline()
44
+ if not s:
45
+ break
46
+
47
+ # skip fields and comment lines
48
+ if re.match(rb"\w+:|#", s):
49
+ continue
50
+ if limit and len(s) > 100:
51
+ msg = "bad palette file"
52
+ raise SyntaxError(msg)
53
+
54
+ v = s.split(maxsplit=3)
55
+ if len(v) < 3:
56
+ msg = "bad palette entry"
57
+ raise ValueError(msg)
58
+
59
+ palette += (int(v[i]) for i in range(3))
60
+ if limit and len(palette) == 768:
61
+ break
62
+
63
+ self.palette = bytes(palette)
64
+
65
+ def __init__(self, fp: IO[bytes]) -> None:
66
+ self._read(fp)
67
+
68
+ @classmethod
69
+ def frombytes(cls, data: bytes) -> GimpPaletteFile:
70
+ self = cls.__new__(cls)
71
+ self._read(BytesIO(data), False)
72
+ return self
73
+
74
+ def getpalette(self) -> tuple[bytes, str]:
75
+ return self.palette, self.rawmode
.venv/Lib/site-packages/PIL/GribStubImagePlugin.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import os
14
+ from typing import IO
15
+
16
+ from . import Image, ImageFile
17
+
18
+ _handler = None
19
+
20
+
21
+ def register_handler(handler: ImageFile.StubHandler | None) -> None:
22
+ """
23
+ Install application-specific GRIB image handler.
24
+
25
+ :param handler: Handler object.
26
+ """
27
+ global _handler
28
+ _handler = handler
29
+
30
+
31
+ # --------------------------------------------------------------------
32
+ # Image adapter
33
+
34
+
35
+ def _accept(prefix: bytes) -> bool:
36
+ return len(prefix) >= 8 and prefix.startswith(b"GRIB") and prefix[7] == 1
37
+
38
+
39
+ class GribStubImageFile(ImageFile.StubImageFile):
40
+ format = "GRIB"
41
+ format_description = "GRIB"
42
+
43
+ def _open(self) -> None:
44
+ assert self.fp is not None
45
+ if not _accept(self.fp.read(8)):
46
+ msg = "Not a GRIB file"
47
+ raise SyntaxError(msg)
48
+
49
+ self.fp.seek(-8, os.SEEK_CUR)
50
+
51
+ # make something up
52
+ self._mode = "F"
53
+ self._size = 1, 1
54
+
55
+ def _load(self) -> ImageFile.StubHandler | None:
56
+ return _handler
57
+
58
+
59
+ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
60
+ if _handler is None or not hasattr(_handler, "save"):
61
+ msg = "GRIB save handler not installed"
62
+ raise OSError(msg)
63
+ _handler.save(im, fp, filename)
64
+
65
+
66
+ # --------------------------------------------------------------------
67
+ # Registry
68
+
69
+ Image.register_open(GribStubImageFile.format, GribStubImageFile, _accept)
70
+ Image.register_save(GribStubImageFile.format, _save)
71
+
72
+ Image.register_extension(GribStubImageFile.format, ".grib")
.venv/Lib/site-packages/PIL/Hdf5StubImagePlugin.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import os
14
+ from typing import IO
15
+
16
+ from . import Image, ImageFile
17
+
18
+ _handler = None
19
+
20
+
21
+ def register_handler(handler: ImageFile.StubHandler | None) -> None:
22
+ """
23
+ Install application-specific HDF5 image handler.
24
+
25
+ :param handler: Handler object.
26
+ """
27
+ global _handler
28
+ _handler = handler
29
+
30
+
31
+ # --------------------------------------------------------------------
32
+ # Image adapter
33
+
34
+
35
+ def _accept(prefix: bytes) -> bool:
36
+ return prefix.startswith(b"\x89HDF\r\n\x1a\n")
37
+
38
+
39
+ class HDF5StubImageFile(ImageFile.StubImageFile):
40
+ format = "HDF5"
41
+ format_description = "HDF5"
42
+
43
+ def _open(self) -> None:
44
+ assert self.fp is not None
45
+ if not _accept(self.fp.read(8)):
46
+ msg = "Not an HDF file"
47
+ raise SyntaxError(msg)
48
+
49
+ self.fp.seek(-8, os.SEEK_CUR)
50
+
51
+ # make something up
52
+ self._mode = "F"
53
+ self._size = 1, 1
54
+
55
+ def _load(self) -> ImageFile.StubHandler | None:
56
+ return _handler
57
+
58
+
59
+ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
60
+ if _handler is None or not hasattr(_handler, "save"):
61
+ msg = "HDF5 save handler not installed"
62
+ raise OSError(msg)
63
+ _handler.save(im, fp, filename)
64
+
65
+
66
+ # --------------------------------------------------------------------
67
+ # Registry
68
+
69
+ Image.register_open(HDF5StubImageFile.format, HDF5StubImageFile, _accept)
70
+ Image.register_save(HDF5StubImageFile.format, _save)
71
+
72
+ Image.register_extensions(HDF5StubImageFile.format, [".h5", ".hdf"])
.venv/Lib/site-packages/PIL/IcnsImagePlugin.py ADDED
@@ -0,0 +1,401 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from typing import IO
26
+
27
+ from . import Image, ImageFile, PngImagePlugin, features
28
+
29
+ enable_jpeg2k = features.check_codec("jpg_2000")
30
+ if enable_jpeg2k:
31
+ from . import Jpeg2KImagePlugin
32
+
33
+ MAGIC = b"icns"
34
+ HEADERSIZE = 8
35
+
36
+
37
+ def nextheader(fobj: IO[bytes]) -> tuple[bytes, int]:
38
+ return struct.unpack(">4sI", fobj.read(HEADERSIZE))
39
+
40
+
41
+ def read_32t(
42
+ fobj: IO[bytes], start_length: tuple[int, int], size: tuple[int, int, int]
43
+ ) -> dict[str, Image.Image]:
44
+ # The 128x128 icon seems to have an extra header for some reason.
45
+ start, length = start_length
46
+ fobj.seek(start)
47
+ sig = fobj.read(4)
48
+ if sig != b"\x00\x00\x00\x00":
49
+ msg = "Unknown signature, expecting 0x00000000"
50
+ raise SyntaxError(msg)
51
+ return read_32(fobj, (start + 4, length - 4), size)
52
+
53
+
54
+ def read_32(
55
+ fobj: IO[bytes], start_length: tuple[int, int], size: tuple[int, int, int]
56
+ ) -> dict[str, Image.Image]:
57
+ """
58
+ Read a 32bit RGB icon resource. Seems to be either uncompressed or
59
+ an RLE packbits-like scheme.
60
+ """
61
+ start, length = start_length
62
+ fobj.seek(start)
63
+ pixel_size = (size[0] * size[2], size[1] * size[2])
64
+ sizesq = pixel_size[0] * pixel_size[1]
65
+ if length == sizesq * 3:
66
+ # uncompressed ("RGBRGBGB")
67
+ indata = fobj.read(length)
68
+ im = Image.frombuffer("RGB", pixel_size, indata, "raw", "RGB", 0, 1)
69
+ else:
70
+ # decode image
71
+ im = Image.new("RGB", pixel_size, None)
72
+ for band_ix in range(3):
73
+ data = []
74
+ bytesleft = sizesq
75
+ while bytesleft > 0:
76
+ byte = fobj.read(1)
77
+ if not byte:
78
+ break
79
+ byte_int = byte[0]
80
+ if byte_int & 0x80:
81
+ blocksize = byte_int - 125
82
+ byte = fobj.read(1)
83
+ data.extend([byte] * blocksize)
84
+ else:
85
+ blocksize = byte_int + 1
86
+ data.append(fobj.read(blocksize))
87
+ bytesleft -= blocksize
88
+ if bytesleft <= 0:
89
+ break
90
+ if bytesleft != 0:
91
+ msg = f"Error reading channel [{repr(bytesleft)} left]"
92
+ raise SyntaxError(msg)
93
+ band = Image.frombuffer("L", pixel_size, b"".join(data), "raw", "L", 0, 1)
94
+ im.im.putband(band.im, band_ix)
95
+ return {"RGB": im}
96
+
97
+
98
+ def read_mk(
99
+ fobj: IO[bytes], start_length: tuple[int, int], size: tuple[int, int, int]
100
+ ) -> dict[str, Image.Image]:
101
+ # Alpha masks seem to be uncompressed
102
+ start = start_length[0]
103
+ fobj.seek(start)
104
+ pixel_size = (size[0] * size[2], size[1] * size[2])
105
+ sizesq = pixel_size[0] * pixel_size[1]
106
+ band = Image.frombuffer("L", pixel_size, fobj.read(sizesq), "raw", "L", 0, 1)
107
+ return {"A": band}
108
+
109
+
110
+ def read_png_or_jpeg2000(
111
+ fobj: IO[bytes], start_length: tuple[int, int], size: tuple[int, int, int]
112
+ ) -> dict[str, Image.Image]:
113
+ start, length = start_length
114
+ fobj.seek(start)
115
+ sig = fobj.read(12)
116
+
117
+ im: Image.Image
118
+ if sig.startswith(b"\x89PNG\x0d\x0a\x1a\x0a"):
119
+ fobj.seek(start)
120
+ im = PngImagePlugin.PngImageFile(fobj)
121
+ Image._decompression_bomb_check(im.size)
122
+ return {"RGBA": im}
123
+ elif (
124
+ sig.startswith((b"\xff\x4f\xff\x51", b"\x0d\x0a\x87\x0a"))
125
+ or sig == b"\x00\x00\x00\x0cjP \x0d\x0a\x87\x0a"
126
+ ):
127
+ if not enable_jpeg2k:
128
+ msg = (
129
+ "Unsupported icon subimage format (rebuild PIL "
130
+ "with JPEG 2000 support to fix this)"
131
+ )
132
+ raise ValueError(msg)
133
+ # j2k, jpc or j2c
134
+ fobj.seek(start)
135
+ jp2kstream = fobj.read(length)
136
+ f = io.BytesIO(jp2kstream)
137
+ im = Jpeg2KImagePlugin.Jpeg2KImageFile(f)
138
+ Image._decompression_bomb_check(im.size)
139
+ if im.mode != "RGBA":
140
+ im = im.convert("RGBA")
141
+ return {"RGBA": im}
142
+ else:
143
+ msg = "Unsupported icon subimage format"
144
+ raise ValueError(msg)
145
+
146
+
147
+ class IcnsFile:
148
+ SIZES = {
149
+ (512, 512, 2): [(b"ic10", read_png_or_jpeg2000)],
150
+ (512, 512, 1): [(b"ic09", read_png_or_jpeg2000)],
151
+ (256, 256, 2): [(b"ic14", read_png_or_jpeg2000)],
152
+ (256, 256, 1): [(b"ic08", read_png_or_jpeg2000)],
153
+ (128, 128, 2): [(b"ic13", read_png_or_jpeg2000)],
154
+ (128, 128, 1): [
155
+ (b"ic07", read_png_or_jpeg2000),
156
+ (b"it32", read_32t),
157
+ (b"t8mk", read_mk),
158
+ ],
159
+ (64, 64, 1): [(b"icp6", read_png_or_jpeg2000)],
160
+ (32, 32, 2): [(b"ic12", read_png_or_jpeg2000)],
161
+ (48, 48, 1): [(b"ih32", read_32), (b"h8mk", read_mk)],
162
+ (32, 32, 1): [
163
+ (b"icp5", read_png_or_jpeg2000),
164
+ (b"il32", read_32),
165
+ (b"l8mk", read_mk),
166
+ ],
167
+ (16, 16, 2): [(b"ic11", read_png_or_jpeg2000)],
168
+ (16, 16, 1): [
169
+ (b"icp4", read_png_or_jpeg2000),
170
+ (b"is32", read_32),
171
+ (b"s8mk", read_mk),
172
+ ],
173
+ }
174
+
175
+ def __init__(self, fobj: IO[bytes]) -> None:
176
+ """
177
+ fobj is a file-like object as an icns resource
178
+ """
179
+ # signature : (start, length)
180
+ self.dct = {}
181
+ self.fobj = fobj
182
+ sig, filesize = nextheader(fobj)
183
+ if not _accept(sig):
184
+ msg = "not an icns file"
185
+ raise SyntaxError(msg)
186
+ i = HEADERSIZE
187
+ while i < filesize:
188
+ sig, blocksize = nextheader(fobj)
189
+ if blocksize <= 0:
190
+ msg = "invalid block header"
191
+ raise SyntaxError(msg)
192
+ i += HEADERSIZE
193
+ blocksize -= HEADERSIZE
194
+ self.dct[sig] = (i, blocksize)
195
+ fobj.seek(blocksize, io.SEEK_CUR)
196
+ i += blocksize
197
+
198
+ def itersizes(self) -> list[tuple[int, int, int]]:
199
+ sizes = []
200
+ for size, fmts in self.SIZES.items():
201
+ for fmt, reader in fmts:
202
+ if fmt in self.dct:
203
+ sizes.append(size)
204
+ break
205
+ return sizes
206
+
207
+ def bestsize(self) -> tuple[int, int, int]:
208
+ sizes = self.itersizes()
209
+ if not sizes:
210
+ msg = "No 32bit icon resources found"
211
+ raise SyntaxError(msg)
212
+ return max(sizes)
213
+
214
+ def dataforsize(self, size: tuple[int, int, int]) -> dict[str, Image.Image]:
215
+ """
216
+ Get an icon resource as {channel: array}. Note that
217
+ the arrays are bottom-up like windows bitmaps and will likely
218
+ need to be flipped or transposed in some way.
219
+ """
220
+ dct = {}
221
+ for code, reader in self.SIZES[size]:
222
+ desc = self.dct.get(code)
223
+ if desc is not None:
224
+ dct.update(reader(self.fobj, desc, size))
225
+ return dct
226
+
227
+ def getimage(
228
+ self, size: tuple[int, int] | tuple[int, int, int] | None = None
229
+ ) -> Image.Image:
230
+ if size is None:
231
+ size = self.bestsize()
232
+ elif len(size) == 2:
233
+ size = (size[0], size[1], 1)
234
+ channels = self.dataforsize(size)
235
+
236
+ im = channels.get("RGBA")
237
+ if im:
238
+ return im
239
+
240
+ im = channels["RGB"].copy()
241
+ try:
242
+ im.putalpha(channels["A"])
243
+ except KeyError:
244
+ pass
245
+ return im
246
+
247
+
248
+ ##
249
+ # Image plugin for Mac OS icons.
250
+
251
+
252
+ class IcnsImageFile(ImageFile.ImageFile):
253
+ """
254
+ PIL image support for Mac OS .icns files.
255
+ Chooses the best resolution, but will possibly load
256
+ a different size image if you mutate the size attribute
257
+ before calling 'load'.
258
+
259
+ The info dictionary has a key 'sizes' that is a list
260
+ of sizes that the icns file has.
261
+ """
262
+
263
+ format = "ICNS"
264
+ format_description = "Mac OS icns resource"
265
+
266
+ def _open(self) -> None:
267
+ assert self.fp is not None
268
+ self.icns = IcnsFile(self.fp)
269
+ self._mode = "RGBA"
270
+ self.info["sizes"] = self.icns.itersizes()
271
+ self.best_size = self.icns.bestsize()
272
+ self.size = (
273
+ self.best_size[0] * self.best_size[2],
274
+ self.best_size[1] * self.best_size[2],
275
+ )
276
+
277
+ @property
278
+ def size(self) -> tuple[int, int]:
279
+ return self._size
280
+
281
+ @size.setter
282
+ def size(self, value: tuple[int, int]) -> None:
283
+ # Check that a matching size exists,
284
+ # or that there is a scale that would create a size that matches
285
+ for size in self.info["sizes"]:
286
+ simple_size = size[0] * size[2], size[1] * size[2]
287
+ scale = simple_size[0] // value[0]
288
+ if simple_size[1] / value[1] == scale:
289
+ self._size = value
290
+ return
291
+ msg = "This is not one of the allowed sizes of this image"
292
+ raise ValueError(msg)
293
+
294
+ def load(self, scale: int | None = None) -> Image.core.PixelAccess | None:
295
+ if scale is not None:
296
+ width, height = self.size[:2]
297
+ self.size = width * scale, height * scale
298
+ self.best_size = width, height, scale
299
+
300
+ px = Image.Image.load(self)
301
+ if self._im is not None and self.im.size == self.size:
302
+ # Already loaded
303
+ return px
304
+ self.load_prepare()
305
+ # This is likely NOT the best way to do it, but whatever.
306
+ im = self.icns.getimage(self.best_size)
307
+
308
+ # If this is a PNG or JPEG 2000, it won't be loaded yet
309
+ px = im.load()
310
+
311
+ self.im = im.im
312
+ self._mode = im.mode
313
+ self.size = im.size
314
+
315
+ return px
316
+
317
+
318
+ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
319
+ """
320
+ Saves the image as a series of PNG files,
321
+ that are then combined into a .icns file.
322
+ """
323
+ if hasattr(fp, "flush"):
324
+ fp.flush()
325
+
326
+ sizes = {
327
+ b"ic07": 128,
328
+ b"ic08": 256,
329
+ b"ic09": 512,
330
+ b"ic10": 1024,
331
+ b"ic11": 32,
332
+ b"ic12": 64,
333
+ b"ic13": 256,
334
+ b"ic14": 512,
335
+ }
336
+ provided_images = {im.width: im for im in im.encoderinfo.get("append_images", [])}
337
+ size_streams = {}
338
+ for size in set(sizes.values()):
339
+ image = (
340
+ provided_images[size]
341
+ if size in provided_images
342
+ else im.resize((size, size))
343
+ )
344
+
345
+ temp = io.BytesIO()
346
+ image.save(temp, "png")
347
+ size_streams[size] = temp.getvalue()
348
+
349
+ entries = []
350
+ for type, size in sizes.items():
351
+ stream = size_streams[size]
352
+ entries.append((type, HEADERSIZE + len(stream), stream))
353
+
354
+ # Header
355
+ fp.write(MAGIC)
356
+ file_length = HEADERSIZE # Header
357
+ file_length += HEADERSIZE + 8 * len(entries) # TOC
358
+ file_length += sum(entry[1] for entry in entries)
359
+ fp.write(struct.pack(">i", file_length))
360
+
361
+ # TOC
362
+ fp.write(b"TOC ")
363
+ fp.write(struct.pack(">i", HEADERSIZE + len(entries) * HEADERSIZE))
364
+ for entry in entries:
365
+ fp.write(entry[0])
366
+ fp.write(struct.pack(">i", entry[1]))
367
+
368
+ # Data
369
+ for entry in entries:
370
+ fp.write(entry[0])
371
+ fp.write(struct.pack(">i", entry[1]))
372
+ fp.write(entry[2])
373
+
374
+ if hasattr(fp, "flush"):
375
+ fp.flush()
376
+
377
+
378
+ def _accept(prefix: bytes) -> bool:
379
+ return prefix.startswith(MAGIC)
380
+
381
+
382
+ Image.register_open(IcnsImageFile.format, IcnsImageFile, _accept)
383
+ Image.register_extension(IcnsImageFile.format, ".icns")
384
+
385
+ Image.register_save(IcnsImageFile.format, _save)
386
+ Image.register_mime(IcnsImageFile.format, "image/icns")
387
+
388
+ if __name__ == "__main__":
389
+ if len(sys.argv) < 2:
390
+ print("Syntax: python3 IcnsImagePlugin.py [file]")
391
+ sys.exit()
392
+
393
+ with open(sys.argv[1], "rb") as fp:
394
+ imf = IcnsImageFile(fp)
395
+ for size in imf.info["sizes"]:
396
+ width, height, scale = imf.size = size
397
+ imf.save(f"out-{width}-{height}-{scale}.png")
398
+ with Image.open(sys.argv[1]) as im:
399
+ im.save("out.png")
400
+ if sys.platform == "windows":
401
+ os.startfile("out.png")
.venv/Lib/site-packages/PIL/IcoImagePlugin.py ADDED
@@ -0,0 +1,396 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Copyright 2008 Bryan Davis
21
+ #
22
+ # Licensed under the Apache License, Version 2.0 (the "License"); you may
23
+ # not use this file except in compliance with the License. You may obtain
24
+ # a copy of the License at
25
+ #
26
+ # https://www.apache.org/licenses/LICENSE-2.0
27
+ #
28
+ # Unless required by applicable law or agreed to in writing, software
29
+ # distributed under the License is distributed on an "AS IS" BASIS,
30
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31
+ # See the License for the specific language governing permissions and
32
+ # limitations under the License.
33
+
34
+ # Icon format references:
35
+ # * https://en.wikipedia.org/wiki/ICO_(file_format)
36
+ # * https://msdn.microsoft.com/en-us/library/ms997538.aspx
37
+ from __future__ import annotations
38
+
39
+ import warnings
40
+ from io import BytesIO
41
+ from math import ceil, log
42
+ from typing import IO, NamedTuple
43
+
44
+ from . import BmpImagePlugin, Image, ImageFile, PngImagePlugin
45
+ from ._binary import i16le as i16
46
+ from ._binary import i32le as i32
47
+ from ._binary import o8
48
+ from ._binary import o16le as o16
49
+ from ._binary import o32le as o32
50
+
51
+ #
52
+ # --------------------------------------------------------------------
53
+
54
+ _MAGIC = b"\0\0\1\0"
55
+
56
+
57
+ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
58
+ fp.write(_MAGIC) # (2+2)
59
+ bmp = im.encoderinfo.get("bitmap_format") == "bmp"
60
+ sizes = im.encoderinfo.get(
61
+ "sizes",
62
+ [(16, 16), (24, 24), (32, 32), (48, 48), (64, 64), (128, 128), (256, 256)],
63
+ )
64
+ frames = []
65
+ provided_ims = [im] + im.encoderinfo.get("append_images", [])
66
+ width, height = im.size
67
+ for size in sorted(set(sizes)):
68
+ if size[0] > width or size[1] > height or size[0] > 256 or size[1] > 256:
69
+ continue
70
+
71
+ for provided_im in provided_ims:
72
+ if provided_im.size != size:
73
+ continue
74
+ frames.append(provided_im)
75
+ if bmp:
76
+ bits = BmpImagePlugin.SAVE[provided_im.mode][1]
77
+ bits_used = [bits]
78
+ for other_im in provided_ims:
79
+ if other_im.size != size:
80
+ continue
81
+ bits = BmpImagePlugin.SAVE[other_im.mode][1]
82
+ if bits not in bits_used:
83
+ # Another image has been supplied for this size
84
+ # with a different bit depth
85
+ frames.append(other_im)
86
+ bits_used.append(bits)
87
+ break
88
+ else:
89
+ # TODO: invent a more convenient method for proportional scalings
90
+ frame = provided_im.copy()
91
+ frame.thumbnail(size, Image.Resampling.LANCZOS, reducing_gap=None)
92
+ frames.append(frame)
93
+ fp.write(o16(len(frames))) # idCount(2)
94
+ offset = fp.tell() + len(frames) * 16
95
+ for frame in frames:
96
+ width, height = frame.size
97
+ # 0 means 256
98
+ fp.write(o8(width if width < 256 else 0)) # bWidth(1)
99
+ fp.write(o8(height if height < 256 else 0)) # bHeight(1)
100
+
101
+ bits, colors = BmpImagePlugin.SAVE[frame.mode][1:] if bmp else (32, 0)
102
+ fp.write(o8(colors)) # bColorCount(1)
103
+ fp.write(b"\0") # bReserved(1)
104
+ fp.write(b"\0\0") # wPlanes(2)
105
+ fp.write(o16(bits)) # wBitCount(2)
106
+
107
+ image_io = BytesIO()
108
+ if bmp:
109
+ frame.save(image_io, "dib")
110
+
111
+ if bits != 32:
112
+ and_mask = Image.new("1", size)
113
+ ImageFile._save(
114
+ and_mask,
115
+ image_io,
116
+ [ImageFile._Tile("raw", (0, 0) + size, 0, ("1", 0, -1))],
117
+ )
118
+ else:
119
+ frame.save(image_io, "png")
120
+ image_io.seek(0)
121
+ image_bytes = image_io.read()
122
+ if bmp:
123
+ image_bytes = image_bytes[:8] + o32(height * 2) + image_bytes[12:]
124
+ bytes_len = len(image_bytes)
125
+ fp.write(o32(bytes_len)) # dwBytesInRes(4)
126
+ fp.write(o32(offset)) # dwImageOffset(4)
127
+ current = fp.tell()
128
+ fp.seek(offset)
129
+ fp.write(image_bytes)
130
+ offset = offset + bytes_len
131
+ fp.seek(current)
132
+
133
+
134
+ def _accept(prefix: bytes) -> bool:
135
+ return prefix.startswith(_MAGIC)
136
+
137
+
138
+ class IconHeader(NamedTuple):
139
+ width: int
140
+ height: int
141
+ nb_color: int
142
+ reserved: int
143
+ planes: int
144
+ bpp: int
145
+ size: int
146
+ offset: int
147
+ dim: tuple[int, int]
148
+ square: int
149
+ color_depth: int
150
+
151
+
152
+ class IcoFile:
153
+ def __init__(self, buf: IO[bytes]) -> None:
154
+ """
155
+ Parse image from file-like object containing ico file data
156
+ """
157
+
158
+ # check magic
159
+ s = buf.read(6)
160
+ if not _accept(s):
161
+ msg = "not an ICO file"
162
+ raise SyntaxError(msg)
163
+
164
+ self.buf = buf
165
+ self.entry = []
166
+
167
+ # Number of items in file
168
+ self.nb_items = i16(s, 4)
169
+
170
+ # Get headers for each item
171
+ for i in range(self.nb_items):
172
+ s = buf.read(16)
173
+
174
+ # See Wikipedia
175
+ width = s[0] or 256
176
+ height = s[1] or 256
177
+
178
+ # No. of colors in image (0 if >=8bpp)
179
+ nb_color = s[2]
180
+ bpp = i16(s, 6)
181
+ icon_header = IconHeader(
182
+ width=width,
183
+ height=height,
184
+ nb_color=nb_color,
185
+ reserved=s[3],
186
+ planes=i16(s, 4),
187
+ bpp=i16(s, 6),
188
+ size=i32(s, 8),
189
+ offset=i32(s, 12),
190
+ dim=(width, height),
191
+ square=width * height,
192
+ # See Wikipedia notes about color depth.
193
+ # We need this just to differ images with equal sizes
194
+ color_depth=bpp or (nb_color != 0 and ceil(log(nb_color, 2))) or 256,
195
+ )
196
+
197
+ self.entry.append(icon_header)
198
+
199
+ self.entry = sorted(self.entry, key=lambda x: x.color_depth)
200
+ # ICO images are usually squares
201
+ self.entry = sorted(self.entry, key=lambda x: x.square, reverse=True)
202
+
203
+ def sizes(self) -> set[tuple[int, int]]:
204
+ """
205
+ Get a set of all available icon sizes and color depths.
206
+ """
207
+ return {(h.width, h.height) for h in self.entry}
208
+
209
+ def getentryindex(self, size: tuple[int, int], bpp: int | bool = False) -> int:
210
+ for i, h in enumerate(self.entry):
211
+ if size == h.dim and (bpp is False or bpp == h.color_depth):
212
+ return i
213
+ return 0
214
+
215
+ def getimage(self, size: tuple[int, int], bpp: int | bool = False) -> Image.Image:
216
+ """
217
+ Get an image from the icon
218
+ """
219
+ return self.frame(self.getentryindex(size, bpp))
220
+
221
+ def frame(self, idx: int) -> Image.Image:
222
+ """
223
+ Get an image from frame idx
224
+ """
225
+
226
+ header = self.entry[idx]
227
+
228
+ self.buf.seek(header.offset)
229
+ data = self.buf.read(8)
230
+ self.buf.seek(header.offset)
231
+
232
+ im: Image.Image
233
+ if data[:8] == PngImagePlugin._MAGIC:
234
+ # png frame
235
+ im = PngImagePlugin.PngImageFile(self.buf)
236
+ Image._decompression_bomb_check(im.size)
237
+ else:
238
+ # XOR + AND mask bmp frame
239
+ im = BmpImagePlugin.DibImageFile(self.buf)
240
+ Image._decompression_bomb_check(im.size)
241
+
242
+ # change tile dimension to only encompass XOR image
243
+ im._size = (im.size[0], int(im.size[1] / 2))
244
+ d, e, o, a = im.tile[0]
245
+ im.tile[0] = ImageFile._Tile(d, (0, 0) + im.size, o, a)
246
+
247
+ # figure out where AND mask image starts
248
+ if header.bpp == 32:
249
+ # 32-bit color depth icon image allows semitransparent areas
250
+ # PIL's DIB format ignores transparency bits, recover them.
251
+ # The DIB is packed in BGRX byte order where X is the alpha
252
+ # channel.
253
+
254
+ # Back up to start of bmp data
255
+ self.buf.seek(o)
256
+ # extract every 4th byte (eg. 3,7,11,15,...)
257
+ alpha_bytes = self.buf.read(im.size[0] * im.size[1] * 4)[3::4]
258
+
259
+ # convert to an 8bpp grayscale image
260
+ try:
261
+ mask = Image.frombuffer(
262
+ "L", # 8bpp
263
+ im.size, # (w, h)
264
+ alpha_bytes, # source chars
265
+ "raw", # raw decoder
266
+ ("L", 0, -1), # 8bpp inverted, unpadded, reversed
267
+ )
268
+ except ValueError:
269
+ if ImageFile.LOAD_TRUNCATED_IMAGES:
270
+ mask = None
271
+ else:
272
+ raise
273
+ else:
274
+ # get AND image from end of bitmap
275
+ w = im.size[0]
276
+ if (w % 32) > 0:
277
+ # bitmap row data is aligned to word boundaries
278
+ w += 32 - (im.size[0] % 32)
279
+
280
+ # the total mask data is
281
+ # padded row size * height / bits per char
282
+
283
+ total_bytes = int((w * im.size[1]) / 8)
284
+ and_mask_offset = header.offset + header.size - total_bytes
285
+
286
+ self.buf.seek(and_mask_offset)
287
+ mask_data = self.buf.read(total_bytes)
288
+
289
+ # convert raw data to image
290
+ try:
291
+ mask = Image.frombuffer(
292
+ "1", # 1 bpp
293
+ im.size, # (w, h)
294
+ mask_data, # source chars
295
+ "raw", # raw decoder
296
+ ("1;I", int(w / 8), -1), # 1bpp inverted, padded, reversed
297
+ )
298
+ except ValueError:
299
+ if ImageFile.LOAD_TRUNCATED_IMAGES:
300
+ mask = None
301
+ else:
302
+ raise
303
+
304
+ # now we have two images, im is XOR image and mask is AND image
305
+
306
+ # apply mask image as alpha channel
307
+ if mask:
308
+ im = im.convert("RGBA")
309
+ im.putalpha(mask)
310
+
311
+ return im
312
+
313
+
314
+ ##
315
+ # Image plugin for Windows Icon files.
316
+
317
+
318
+ class IcoImageFile(ImageFile.ImageFile):
319
+ """
320
+ PIL read-only image support for Microsoft Windows .ico files.
321
+
322
+ By default the largest resolution image in the file will be loaded. This
323
+ can be changed by altering the 'size' attribute before calling 'load'.
324
+
325
+ The info dictionary has a key 'sizes' that is a list of the sizes available
326
+ in the icon file.
327
+
328
+ Handles classic, XP and Vista icon formats.
329
+
330
+ When saving, PNG compression is used. Support for this was only added in
331
+ Windows Vista. If you are unable to view the icon in Windows, convert the
332
+ image to "RGBA" mode before saving.
333
+
334
+ This plugin is a refactored version of Win32IconImagePlugin by Bryan Davis
335
+ <casadebender@gmail.com>.
336
+ https://code.google.com/archive/p/casadebender/wikis/Win32IconImagePlugin.wiki
337
+ """
338
+
339
+ format = "ICO"
340
+ format_description = "Windows Icon"
341
+
342
+ def _open(self) -> None:
343
+ assert self.fp is not None
344
+ self.ico = IcoFile(self.fp)
345
+ self.info["sizes"] = self.ico.sizes()
346
+ self.size = self.ico.entry[0].dim
347
+ self.load()
348
+
349
+ @property
350
+ def size(self) -> tuple[int, int]:
351
+ return self._size
352
+
353
+ @size.setter
354
+ def size(self, value: tuple[int, int]) -> None:
355
+ if value not in self.info["sizes"]:
356
+ msg = "This is not one of the allowed sizes of this image"
357
+ raise ValueError(msg)
358
+ self._size = value
359
+
360
+ def load(self) -> Image.core.PixelAccess | None:
361
+ if self._im is not None and self.im.size == self.size:
362
+ # Already loaded
363
+ return Image.Image.load(self)
364
+ im = self.ico.getimage(self.size)
365
+ # if tile is PNG, it won't really be loaded yet
366
+ im.load()
367
+ self.im = im.im
368
+ self._mode = im.mode
369
+ if im.palette:
370
+ self.palette = im.palette
371
+ if im.size != self.size:
372
+ warnings.warn("Image was not the expected size")
373
+
374
+ index = self.ico.getentryindex(self.size)
375
+ sizes = list(self.info["sizes"])
376
+ sizes[index] = im.size
377
+ self.info["sizes"] = set(sizes)
378
+
379
+ self.size = im.size
380
+ return Image.Image.load(self)
381
+
382
+ def load_seek(self, pos: int) -> None:
383
+ # Flag the ImageFile.Parser so that it
384
+ # just does all the decode at the end.
385
+ pass
386
+
387
+
388
+ #
389
+ # --------------------------------------------------------------------
390
+
391
+
392
+ Image.register_open(IcoImageFile.format, IcoImageFile, _accept)
393
+ Image.register_save(IcoImageFile.format, _save)
394
+ Image.register_extension(IcoImageFile.format, ".ico")
395
+
396
+ Image.register_mime(IcoImageFile.format, "image/x-icon")
.venv/Lib/site-packages/PIL/ImImagePlugin.py ADDED
@@ -0,0 +1,390 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from typing import IO, Any
32
+
33
+ from . import Image, ImageFile, ImagePalette
34
+ from ._util import DeferredError
35
+
36
+ # --------------------------------------------------------------------
37
+ # Standard tags
38
+
39
+ COMMENT = "Comment"
40
+ DATE = "Date"
41
+ EQUIPMENT = "Digitalization equipment"
42
+ FRAMES = "File size (no of images)"
43
+ LUT = "Lut"
44
+ NAME = "Name"
45
+ SCALE = "Scale (x,y)"
46
+ SIZE = "Image size (x*y)"
47
+ MODE = "Image type"
48
+
49
+ TAGS = {
50
+ COMMENT: 0,
51
+ DATE: 0,
52
+ EQUIPMENT: 0,
53
+ FRAMES: 0,
54
+ LUT: 0,
55
+ NAME: 0,
56
+ SCALE: 0,
57
+ SIZE: 0,
58
+ MODE: 0,
59
+ }
60
+
61
+ OPEN = {
62
+ # ifunc93/p3cfunc formats
63
+ "0 1 image": ("1", "1"),
64
+ "L 1 image": ("1", "1"),
65
+ "Greyscale image": ("L", "L"),
66
+ "Grayscale image": ("L", "L"),
67
+ "RGB image": ("RGB", "RGB;L"),
68
+ "RLB image": ("RGB", "RLB"),
69
+ "RYB image": ("RGB", "RLB"),
70
+ "B1 image": ("1", "1"),
71
+ "B2 image": ("P", "P;2"),
72
+ "B4 image": ("P", "P;4"),
73
+ "X 24 image": ("RGB", "RGB"),
74
+ "L 32 S image": ("I", "I;32"),
75
+ "L 32 F image": ("F", "F;32"),
76
+ # old p3cfunc formats
77
+ "RGB3 image": ("RGB", "RGB;T"),
78
+ "RYB3 image": ("RGB", "RYB;T"),
79
+ # extensions
80
+ "LA image": ("LA", "LA;L"),
81
+ "PA image": ("LA", "PA;L"),
82
+ "RGBA image": ("RGBA", "RGBA;L"),
83
+ "RGBX image": ("RGB", "RGBX;L"),
84
+ "CMYK image": ("CMYK", "CMYK;L"),
85
+ "YCC image": ("YCbCr", "YCbCr;L"),
86
+ }
87
+
88
+ # ifunc95 extensions
89
+ for i in ["8", "8S", "16", "16S", "32", "32F"]:
90
+ OPEN[f"L {i} image"] = ("F", f"F;{i}")
91
+ OPEN[f"L*{i} image"] = ("F", f"F;{i}")
92
+ for i in ["16", "16L", "16B"]:
93
+ OPEN[f"L {i} image"] = (f"I;{i}", f"I;{i}")
94
+ OPEN[f"L*{i} image"] = (f"I;{i}", f"I;{i}")
95
+ for i in ["32S"]:
96
+ OPEN[f"L {i} image"] = ("I", f"I;{i}")
97
+ OPEN[f"L*{i} image"] = ("I", f"I;{i}")
98
+ for j in range(2, 33):
99
+ OPEN[f"L*{j} image"] = ("F", f"F;{j}")
100
+
101
+
102
+ # --------------------------------------------------------------------
103
+ # Read IM directory
104
+
105
+ split = re.compile(rb"^([A-Za-z][^:]*):[ \t]*(.*)[ \t]*$")
106
+
107
+
108
+ def number(s: Any) -> float:
109
+ try:
110
+ return int(s)
111
+ except ValueError:
112
+ return float(s)
113
+
114
+
115
+ ##
116
+ # Image plugin for the IFUNC IM file format.
117
+
118
+
119
+ class ImImageFile(ImageFile.ImageFile):
120
+ format = "IM"
121
+ format_description = "IFUNC Image Memory"
122
+ _close_exclusive_fp_after_loading = False
123
+
124
+ def _open(self) -> None:
125
+ # Quick rejection: if there's not an LF among the first
126
+ # 100 bytes, this is (probably) not a text header.
127
+
128
+ assert self.fp is not None
129
+ if b"\n" not in self.fp.read(100):
130
+ msg = "not an IM file"
131
+ raise SyntaxError(msg)
132
+ self.fp.seek(0)
133
+
134
+ n = 0
135
+
136
+ # Default values
137
+ self.info[MODE] = "L"
138
+ self.info[SIZE] = (512, 512)
139
+ self.info[FRAMES] = 1
140
+
141
+ self.rawmode = "L"
142
+
143
+ while True:
144
+ s = self.fp.read(1)
145
+
146
+ # Some versions of IFUNC uses \n\r instead of \r\n...
147
+ if s == b"\r":
148
+ continue
149
+
150
+ if not s or s == b"\0" or s == b"\x1a":
151
+ break
152
+
153
+ # FIXME: this may read whole file if not a text file
154
+ s = s + self.fp.readline()
155
+
156
+ if len(s) > 100:
157
+ msg = "not an IM file"
158
+ raise SyntaxError(msg)
159
+
160
+ if s.endswith(b"\r\n"):
161
+ s = s[:-2]
162
+ elif s.endswith(b"\n"):
163
+ s = s[:-1]
164
+
165
+ try:
166
+ m = split.match(s)
167
+ except re.error as e:
168
+ msg = "not an IM file"
169
+ raise SyntaxError(msg) from e
170
+
171
+ if m:
172
+ k, v = m.group(1, 2)
173
+
174
+ # Don't know if this is the correct encoding,
175
+ # but a decent guess (I guess)
176
+ k = k.decode("latin-1", "replace")
177
+ v = v.decode("latin-1", "replace")
178
+
179
+ # Convert value as appropriate
180
+ if k in [FRAMES, SCALE, SIZE]:
181
+ v = v.replace("*", ",")
182
+ v = tuple(map(number, v.split(",")))
183
+ if len(v) == 1:
184
+ v = v[0]
185
+ elif k == MODE and v in OPEN:
186
+ v, self.rawmode = OPEN[v]
187
+
188
+ # Add to dictionary. Note that COMMENT tags are
189
+ # combined into a list of strings.
190
+ if k == COMMENT:
191
+ if k in self.info:
192
+ self.info[k].append(v)
193
+ else:
194
+ self.info[k] = [v]
195
+ else:
196
+ self.info[k] = v
197
+
198
+ if k in TAGS:
199
+ n += 1
200
+
201
+ else:
202
+ msg = f"Syntax error in IM header: {s.decode('ascii', 'replace')}"
203
+ raise SyntaxError(msg)
204
+
205
+ if not n:
206
+ msg = "Not an IM file"
207
+ raise SyntaxError(msg)
208
+
209
+ # Basic attributes
210
+ self._size = self.info[SIZE]
211
+ self._mode = self.info[MODE]
212
+
213
+ # Skip forward to start of image data
214
+ while s and not s.startswith(b"\x1a"):
215
+ s = self.fp.read(1)
216
+ if not s:
217
+ msg = "File truncated"
218
+ raise SyntaxError(msg)
219
+
220
+ if LUT in self.info:
221
+ # convert lookup table to palette or lut attribute
222
+ palette = self.fp.read(768)
223
+ greyscale = 1 # greyscale palette
224
+ linear = 1 # linear greyscale palette
225
+ for i in range(256):
226
+ if palette[i] == palette[i + 256] == palette[i + 512]:
227
+ if palette[i] != i:
228
+ linear = 0
229
+ else:
230
+ greyscale = 0
231
+ if self.mode in ["L", "LA", "P", "PA"]:
232
+ if greyscale:
233
+ if not linear:
234
+ self.lut = list(palette[:256])
235
+ else:
236
+ if self.mode in ["L", "P"]:
237
+ self._mode = self.rawmode = "P"
238
+ elif self.mode in ["LA", "PA"]:
239
+ self._mode = "PA"
240
+ self.rawmode = "PA;L"
241
+ self.palette = ImagePalette.raw("RGB;L", palette)
242
+ elif self.mode == "RGB":
243
+ if not greyscale or not linear:
244
+ self.lut = list(palette)
245
+
246
+ self.frame = 0
247
+
248
+ self.__offset = offs = self.fp.tell()
249
+
250
+ self._fp = self.fp # FIXME: hack
251
+
252
+ if self.rawmode.startswith("F;"):
253
+ # ifunc95 formats
254
+ try:
255
+ # use bit decoder (if necessary)
256
+ bits = int(self.rawmode[2:])
257
+ if bits not in [8, 16, 32]:
258
+ self.tile = [
259
+ ImageFile._Tile(
260
+ "bit", (0, 0) + self.size, offs, (bits, 8, 3, 0, -1)
261
+ )
262
+ ]
263
+ return
264
+ except ValueError:
265
+ pass
266
+
267
+ if self.rawmode in ["RGB;T", "RYB;T"]:
268
+ # Old LabEye/3PC files. Would be very surprised if anyone
269
+ # ever stumbled upon such a file ;-)
270
+ size = self.size[0] * self.size[1]
271
+ self.tile = [
272
+ ImageFile._Tile("raw", (0, 0) + self.size, offs, ("G", 0, -1)),
273
+ ImageFile._Tile("raw", (0, 0) + self.size, offs + size, ("R", 0, -1)),
274
+ ImageFile._Tile(
275
+ "raw", (0, 0) + self.size, offs + 2 * size, ("B", 0, -1)
276
+ ),
277
+ ]
278
+ else:
279
+ # LabEye/IFUNC files
280
+ self.tile = [
281
+ ImageFile._Tile("raw", (0, 0) + self.size, offs, (self.rawmode, 0, -1))
282
+ ]
283
+
284
+ @property
285
+ def n_frames(self) -> int:
286
+ return self.info[FRAMES]
287
+
288
+ @property
289
+ def is_animated(self) -> bool:
290
+ return self.info[FRAMES] > 1
291
+
292
+ def seek(self, frame: int) -> None:
293
+ if not self._seek_check(frame):
294
+ return
295
+ if isinstance(self._fp, DeferredError):
296
+ raise self._fp.ex
297
+
298
+ self.frame = frame
299
+
300
+ if self.mode == "1":
301
+ bits = 1
302
+ else:
303
+ bits = 8 * len(self.mode)
304
+
305
+ size = ((self.size[0] * bits + 7) // 8) * self.size[1]
306
+ offs = self.__offset + frame * size
307
+
308
+ self.fp = self._fp
309
+
310
+ self.tile = [
311
+ ImageFile._Tile("raw", (0, 0) + self.size, offs, (self.rawmode, 0, -1))
312
+ ]
313
+
314
+ def tell(self) -> int:
315
+ return self.frame
316
+
317
+
318
+ #
319
+ # --------------------------------------------------------------------
320
+ # Save IM files
321
+
322
+
323
+ SAVE = {
324
+ # mode: (im type, raw mode)
325
+ "1": ("0 1", "1"),
326
+ "L": ("Greyscale", "L"),
327
+ "LA": ("LA", "LA;L"),
328
+ "P": ("Greyscale", "P"),
329
+ "PA": ("LA", "PA;L"),
330
+ "I": ("L 32S", "I;32S"),
331
+ "I;16": ("L 16", "I;16"),
332
+ "I;16L": ("L 16L", "I;16L"),
333
+ "I;16B": ("L 16B", "I;16B"),
334
+ "F": ("L 32F", "F;32F"),
335
+ "RGB": ("RGB", "RGB;L"),
336
+ "RGBA": ("RGBA", "RGBA;L"),
337
+ "RGBX": ("RGBX", "RGBX;L"),
338
+ "CMYK": ("CMYK", "CMYK;L"),
339
+ "YCbCr": ("YCC", "YCbCr;L"),
340
+ }
341
+
342
+
343
+ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
344
+ try:
345
+ image_type, rawmode = SAVE[im.mode]
346
+ except KeyError as e:
347
+ msg = f"Cannot save {im.mode} images as IM"
348
+ raise ValueError(msg) from e
349
+
350
+ frames = im.encoderinfo.get("frames", 1)
351
+
352
+ fp.write(f"Image type: {image_type} image\r\n".encode("ascii"))
353
+ if filename:
354
+ # Each line must be 100 characters or less,
355
+ # or: SyntaxError("not an IM file")
356
+ # 8 characters are used for "Name: " and "\r\n"
357
+ # Keep just the filename, ditch the potentially overlong path
358
+ if isinstance(filename, bytes):
359
+ filename = filename.decode("ascii")
360
+ name, ext = os.path.splitext(os.path.basename(filename))
361
+ name = "".join([name[: 92 - len(ext)], ext])
362
+
363
+ fp.write(f"Name: {name}\r\n".encode("ascii"))
364
+ fp.write(f"Image size (x*y): {im.size[0]}*{im.size[1]}\r\n".encode("ascii"))
365
+ fp.write(f"File size (no of images): {frames}\r\n".encode("ascii"))
366
+ if im.mode in ["P", "PA"]:
367
+ fp.write(b"Lut: 1\r\n")
368
+ fp.write(b"\000" * (511 - fp.tell()) + b"\032")
369
+ if im.mode in ["P", "PA"]:
370
+ im_palette = im.im.getpalette("RGB", "RGB;L")
371
+ colors = len(im_palette) // 3
372
+ palette = b""
373
+ for i in range(3):
374
+ palette += im_palette[colors * i : colors * (i + 1)]
375
+ palette += b"\x00" * (256 - colors)
376
+ fp.write(palette) # 768 bytes
377
+ ImageFile._save(
378
+ im, fp, [ImageFile._Tile("raw", (0, 0) + im.size, 0, (rawmode, 0, -1))]
379
+ )
380
+
381
+
382
+ #
383
+ # --------------------------------------------------------------------
384
+ # Registry
385
+
386
+
387
+ Image.register_open(ImImageFile.format, ImImageFile)
388
+ Image.register_save(ImImageFile.format, _save)
389
+
390
+ 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,1076 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
29
+ from ._deprecate import deprecate
30
+ from ._typing import SupportsRead
31
+
32
+ try:
33
+ from . import _imagingcms as core
34
+
35
+ _CmsProfileCompatible = Union[
36
+ str, SupportsRead[bytes], core.CmsProfile, "ImageCmsProfile"
37
+ ]
38
+ except ImportError as ex:
39
+ # Allow error import for doc purposes, but error out when accessing
40
+ # anything in core.
41
+ from ._util import DeferredError
42
+
43
+ core = DeferredError.new(ex)
44
+
45
+ _DESCRIPTION = """
46
+ pyCMS
47
+
48
+ a Python / PIL interface to the littleCMS ICC Color Management System
49
+ Copyright (C) 2002-2003 Kevin Cazabon
50
+ kevin@cazabon.com
51
+ https://www.cazabon.com
52
+
53
+ pyCMS home page: https://www.cazabon.com/pyCMS
54
+ littleCMS home page: https://www.littlecms.com
55
+ (littleCMS is Copyright (C) 1998-2001 Marti Maria)
56
+
57
+ Originally released under LGPL. Graciously donated to PIL in
58
+ March 2009, for distribution under the standard PIL license
59
+
60
+ The pyCMS.py module provides a "clean" interface between Python/PIL and
61
+ pyCMSdll, taking care of some of the more complex handling of the direct
62
+ pyCMSdll functions, as well as error-checking and making sure that all
63
+ relevant data is kept together.
64
+
65
+ While it is possible to call pyCMSdll functions directly, it's not highly
66
+ recommended.
67
+
68
+ Version History:
69
+
70
+ 1.0.0 pil Oct 2013 Port to LCMS 2.
71
+
72
+ 0.1.0 pil mod March 10, 2009
73
+
74
+ Renamed display profile to proof profile. The proof
75
+ profile is the profile of the device that is being
76
+ simulated, not the profile of the device which is
77
+ actually used to display/print the final simulation
78
+ (that'd be the output profile) - also see LCMSAPI.txt
79
+ input colorspace -> using 'renderingIntent' -> proof
80
+ colorspace -> using 'proofRenderingIntent' -> output
81
+ colorspace
82
+
83
+ Added LCMS FLAGS support.
84
+ Added FLAGS["SOFTPROOFING"] as default flag for
85
+ buildProofTransform (otherwise the proof profile/intent
86
+ would be ignored).
87
+
88
+ 0.1.0 pil March 2009 - added to PIL, as PIL.ImageCms
89
+
90
+ 0.0.2 alpha Jan 6, 2002
91
+
92
+ Added try/except statements around type() checks of
93
+ potential CObjects... Python won't let you use type()
94
+ on them, and raises a TypeError (stupid, if you ask
95
+ me!)
96
+
97
+ Added buildProofTransformFromOpenProfiles() function.
98
+ Additional fixes in DLL, see DLL code for details.
99
+
100
+ 0.0.1 alpha first public release, Dec. 26, 2002
101
+
102
+ Known to-do list with current version (of Python interface, not pyCMSdll):
103
+
104
+ none
105
+
106
+ """
107
+
108
+ _VERSION = "1.0.0 pil"
109
+
110
+
111
+ # --------------------------------------------------------------------.
112
+
113
+
114
+ #
115
+ # intent/direction values
116
+
117
+
118
+ class Intent(IntEnum):
119
+ PERCEPTUAL = 0
120
+ RELATIVE_COLORIMETRIC = 1
121
+ SATURATION = 2
122
+ ABSOLUTE_COLORIMETRIC = 3
123
+
124
+
125
+ class Direction(IntEnum):
126
+ INPUT = 0
127
+ OUTPUT = 1
128
+ PROOF = 2
129
+
130
+
131
+ #
132
+ # flags
133
+
134
+
135
+ class Flags(IntFlag):
136
+ """Flags and documentation are taken from ``lcms2.h``."""
137
+
138
+ NONE = 0
139
+ NOCACHE = 0x0040
140
+ """Inhibit 1-pixel cache"""
141
+ NOOPTIMIZE = 0x0100
142
+ """Inhibit optimizations"""
143
+ NULLTRANSFORM = 0x0200
144
+ """Don't transform anyway"""
145
+ GAMUTCHECK = 0x1000
146
+ """Out of Gamut alarm"""
147
+ SOFTPROOFING = 0x4000
148
+ """Do softproofing"""
149
+ BLACKPOINTCOMPENSATION = 0x2000
150
+ NOWHITEONWHITEFIXUP = 0x0004
151
+ """Don't fix scum dot"""
152
+ HIGHRESPRECALC = 0x0400
153
+ """Use more memory to give better accuracy"""
154
+ LOWRESPRECALC = 0x0800
155
+ """Use less memory to minimize resources"""
156
+ # this should be 8BITS_DEVICELINK, but that is not a valid name in Python:
157
+ USE_8BITS_DEVICELINK = 0x0008
158
+ """Create 8 bits devicelinks"""
159
+ GUESSDEVICECLASS = 0x0020
160
+ """Guess device class (for ``transform2devicelink``)"""
161
+ KEEP_SEQUENCE = 0x0080
162
+ """Keep profile sequence for devicelink creation"""
163
+ FORCE_CLUT = 0x0002
164
+ """Force CLUT optimization"""
165
+ CLUT_POST_LINEARIZATION = 0x0001
166
+ """create postlinearization tables if possible"""
167
+ CLUT_PRE_LINEARIZATION = 0x0010
168
+ """create prelinearization tables if possible"""
169
+ NONEGATIVES = 0x8000
170
+ """Prevent negative numbers in floating point transforms"""
171
+ COPY_ALPHA = 0x04000000
172
+ """Alpha channels are copied on ``cmsDoTransform()``"""
173
+ NODEFAULTRESOURCEDEF = 0x01000000
174
+
175
+ _GRIDPOINTS_1 = 1 << 16
176
+ _GRIDPOINTS_2 = 2 << 16
177
+ _GRIDPOINTS_4 = 4 << 16
178
+ _GRIDPOINTS_8 = 8 << 16
179
+ _GRIDPOINTS_16 = 16 << 16
180
+ _GRIDPOINTS_32 = 32 << 16
181
+ _GRIDPOINTS_64 = 64 << 16
182
+ _GRIDPOINTS_128 = 128 << 16
183
+
184
+ @staticmethod
185
+ def GRIDPOINTS(n: int) -> Flags:
186
+ """
187
+ Fine-tune control over number of gridpoints
188
+
189
+ :param n: :py:class:`int` in range ``0 <= n <= 255``
190
+ """
191
+ return Flags.NONE | ((n & 0xFF) << 16)
192
+
193
+
194
+ _MAX_FLAG = reduce(operator.or_, Flags)
195
+
196
+
197
+ _FLAGS = {
198
+ "MATRIXINPUT": 1,
199
+ "MATRIXOUTPUT": 2,
200
+ "MATRIXONLY": (1 | 2),
201
+ "NOWHITEONWHITEFIXUP": 4, # Don't hot fix scum dot
202
+ # Don't create prelinearization tables on precalculated transforms
203
+ # (internal use):
204
+ "NOPRELINEARIZATION": 16,
205
+ "GUESSDEVICECLASS": 32, # Guess device class (for transform2devicelink)
206
+ "NOTCACHE": 64, # Inhibit 1-pixel cache
207
+ "NOTPRECALC": 256,
208
+ "NULLTRANSFORM": 512, # Don't transform anyway
209
+ "HIGHRESPRECALC": 1024, # Use more memory to give better accuracy
210
+ "LOWRESPRECALC": 2048, # Use less memory to minimize resources
211
+ "WHITEBLACKCOMPENSATION": 8192,
212
+ "BLACKPOINTCOMPENSATION": 8192,
213
+ "GAMUTCHECK": 4096, # Out of Gamut alarm
214
+ "SOFTPROOFING": 16384, # Do softproofing
215
+ "PRESERVEBLACK": 32768, # Black preservation
216
+ "NODEFAULTRESOURCEDEF": 16777216, # CRD special
217
+ "GRIDPOINTS": lambda n: (n & 0xFF) << 16, # Gridpoints
218
+ }
219
+
220
+
221
+ # --------------------------------------------------------------------.
222
+ # Experimental PIL-level API
223
+ # --------------------------------------------------------------------.
224
+
225
+ ##
226
+ # Profile.
227
+
228
+
229
+ class ImageCmsProfile:
230
+ def __init__(self, profile: str | SupportsRead[bytes] | core.CmsProfile) -> None:
231
+ """
232
+ :param profile: Either a string representing a filename,
233
+ a file like object containing a profile or a
234
+ low-level profile object
235
+
236
+ """
237
+ self.filename: str | None = None
238
+
239
+ if isinstance(profile, str):
240
+ if sys.platform == "win32":
241
+ profile_bytes_path = profile.encode()
242
+ try:
243
+ profile_bytes_path.decode("ascii")
244
+ except UnicodeDecodeError:
245
+ with open(profile, "rb") as f:
246
+ self.profile = core.profile_frombytes(f.read())
247
+ return
248
+ self.filename = profile
249
+ self.profile = core.profile_open(profile)
250
+ elif hasattr(profile, "read"):
251
+ self.profile = core.profile_frombytes(profile.read())
252
+ elif isinstance(profile, core.CmsProfile):
253
+ self.profile = profile
254
+ else:
255
+ msg = "Invalid type for Profile" # type: ignore[unreachable]
256
+ raise TypeError(msg)
257
+
258
+ def __getattr__(self, name: str) -> Any:
259
+ if name in ("product_name", "product_info"):
260
+ deprecate(f"ImageCms.ImageCmsProfile.{name}", 13)
261
+ return None
262
+ msg = f"'{self.__class__.__name__}' object has no attribute '{name}'"
263
+ raise AttributeError(msg)
264
+
265
+ def tobytes(self) -> bytes:
266
+ """
267
+ Returns the profile in a format suitable for embedding in
268
+ saved images.
269
+
270
+ :returns: a bytes object containing the ICC profile.
271
+ """
272
+
273
+ return core.profile_tobytes(self.profile)
274
+
275
+
276
+ class ImageCmsTransform(Image.ImagePointHandler):
277
+ """
278
+ Transform. This can be used with the procedural API, or with the standard
279
+ :py:func:`~PIL.Image.Image.point` method.
280
+
281
+ Will return the output profile in the ``output.info['icc_profile']``.
282
+ """
283
+
284
+ def __init__(
285
+ self,
286
+ input: ImageCmsProfile,
287
+ output: ImageCmsProfile,
288
+ input_mode: str,
289
+ output_mode: str,
290
+ intent: Intent = Intent.PERCEPTUAL,
291
+ proof: ImageCmsProfile | None = None,
292
+ proof_intent: Intent = Intent.ABSOLUTE_COLORIMETRIC,
293
+ flags: Flags = Flags.NONE,
294
+ ):
295
+ if proof is None:
296
+ self.transform = core.buildTransform(
297
+ input.profile, output.profile, input_mode, output_mode, intent, flags
298
+ )
299
+ else:
300
+ self.transform = core.buildProofTransform(
301
+ input.profile,
302
+ output.profile,
303
+ proof.profile,
304
+ input_mode,
305
+ output_mode,
306
+ intent,
307
+ proof_intent,
308
+ flags,
309
+ )
310
+ # Note: inputMode and outputMode are for pyCMS compatibility only
311
+ self.input_mode = self.inputMode = input_mode
312
+ self.output_mode = self.outputMode = output_mode
313
+
314
+ self.output_profile = output
315
+
316
+ def point(self, im: Image.Image) -> Image.Image:
317
+ return self.apply(im)
318
+
319
+ def apply(self, im: Image.Image, imOut: Image.Image | None = None) -> Image.Image:
320
+ if imOut is None:
321
+ imOut = Image.new(self.output_mode, im.size, None)
322
+ self.transform.apply(im.getim(), imOut.getim())
323
+ imOut.info["icc_profile"] = self.output_profile.tobytes()
324
+ return imOut
325
+
326
+ def apply_in_place(self, im: Image.Image) -> Image.Image:
327
+ if im.mode != self.output_mode:
328
+ msg = "mode mismatch"
329
+ raise ValueError(msg) # wrong output mode
330
+ self.transform.apply(im.getim(), im.getim())
331
+ im.info["icc_profile"] = self.output_profile.tobytes()
332
+ return im
333
+
334
+
335
+ def get_display_profile(handle: SupportsInt | None = None) -> ImageCmsProfile | None:
336
+ """
337
+ (experimental) Fetches the profile for the current display device.
338
+
339
+ :returns: ``None`` if the profile is not known.
340
+ """
341
+
342
+ if sys.platform != "win32":
343
+ return None
344
+
345
+ from . import ImageWin # type: ignore[unused-ignore, unreachable]
346
+
347
+ if isinstance(handle, ImageWin.HDC):
348
+ profile = core.get_display_profile_win32(int(handle), 1)
349
+ else:
350
+ profile = core.get_display_profile_win32(int(handle or 0))
351
+ if profile is None:
352
+ return None
353
+ return ImageCmsProfile(profile)
354
+
355
+
356
+ # --------------------------------------------------------------------.
357
+ # pyCMS compatible layer
358
+ # --------------------------------------------------------------------.
359
+
360
+
361
+ class PyCMSError(Exception):
362
+ """(pyCMS) Exception class.
363
+ This is used for all errors in the pyCMS API."""
364
+
365
+ pass
366
+
367
+
368
+ def profileToProfile(
369
+ im: Image.Image,
370
+ inputProfile: _CmsProfileCompatible,
371
+ outputProfile: _CmsProfileCompatible,
372
+ renderingIntent: Intent = Intent.PERCEPTUAL,
373
+ outputMode: str | None = None,
374
+ inPlace: bool = False,
375
+ flags: Flags = Flags.NONE,
376
+ ) -> Image.Image | None:
377
+ """
378
+ (pyCMS) Applies an ICC transformation to a given image, mapping from
379
+ ``inputProfile`` to ``outputProfile``.
380
+
381
+ If the input or output profiles specified are not valid filenames, a
382
+ :exc:`PyCMSError` will be raised. If ``inPlace`` is ``True`` and
383
+ ``outputMode != im.mode``, a :exc:`PyCMSError` will be raised.
384
+ If an error occurs during application of the profiles,
385
+ a :exc:`PyCMSError` will be raised.
386
+ If ``outputMode`` is not a mode supported by the ``outputProfile`` (or by pyCMS),
387
+ a :exc:`PyCMSError` will be raised.
388
+
389
+ This function applies an ICC transformation to im from ``inputProfile``'s
390
+ color space to ``outputProfile``'s color space using the specified rendering
391
+ intent to decide how to handle out-of-gamut colors.
392
+
393
+ ``outputMode`` can be used to specify that a color mode conversion is to
394
+ be done using these profiles, but the specified profiles must be able
395
+ to handle that mode. I.e., if converting im from RGB to CMYK using
396
+ profiles, the input profile must handle RGB data, and the output
397
+ profile must handle CMYK data.
398
+
399
+ :param im: An open :py:class:`~PIL.Image.Image` object (i.e. Image.new(...)
400
+ or Image.open(...), etc.)
401
+ :param inputProfile: String, as a valid filename path to the ICC input
402
+ profile you wish to use for this image, or a profile object
403
+ :param outputProfile: String, as a valid filename path to the ICC output
404
+ profile you wish to use for this image, or a profile object
405
+ :param renderingIntent: Integer (0-3) specifying the rendering intent you
406
+ wish to use for the transform
407
+
408
+ ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
409
+ ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
410
+ ImageCms.Intent.SATURATION = 2
411
+ ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
412
+
413
+ see the pyCMS documentation for details on rendering intents and what
414
+ they do.
415
+ :param outputMode: A valid PIL mode for the output image (i.e. "RGB",
416
+ "CMYK", etc.). Note: if rendering the image "inPlace", outputMode
417
+ MUST be the same mode as the input, or omitted completely. If
418
+ omitted, the outputMode will be the same as the mode of the input
419
+ image (im.mode)
420
+ :param inPlace: Boolean. If ``True``, the original image is modified in-place,
421
+ and ``None`` is returned. If ``False`` (default), a new
422
+ :py:class:`~PIL.Image.Image` object is returned with the transform applied.
423
+ :param flags: Integer (0-...) specifying additional flags
424
+ :returns: Either None or a new :py:class:`~PIL.Image.Image` object, depending on
425
+ the value of ``inPlace``
426
+ :exception PyCMSError:
427
+ """
428
+
429
+ if outputMode is None:
430
+ outputMode = im.mode
431
+
432
+ if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3):
433
+ msg = "renderingIntent must be an integer between 0 and 3"
434
+ raise PyCMSError(msg)
435
+
436
+ if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
437
+ msg = f"flags must be an integer between 0 and {_MAX_FLAG}"
438
+ raise PyCMSError(msg)
439
+
440
+ try:
441
+ if not isinstance(inputProfile, ImageCmsProfile):
442
+ inputProfile = ImageCmsProfile(inputProfile)
443
+ if not isinstance(outputProfile, ImageCmsProfile):
444
+ outputProfile = ImageCmsProfile(outputProfile)
445
+ transform = ImageCmsTransform(
446
+ inputProfile,
447
+ outputProfile,
448
+ im.mode,
449
+ outputMode,
450
+ renderingIntent,
451
+ flags=flags,
452
+ )
453
+ if inPlace:
454
+ transform.apply_in_place(im)
455
+ imOut = None
456
+ else:
457
+ imOut = transform.apply(im)
458
+ except (OSError, TypeError, ValueError) as v:
459
+ raise PyCMSError(v) from v
460
+
461
+ return imOut
462
+
463
+
464
+ def getOpenProfile(
465
+ profileFilename: str | SupportsRead[bytes] | core.CmsProfile,
466
+ ) -> ImageCmsProfile:
467
+ """
468
+ (pyCMS) Opens an ICC profile file.
469
+
470
+ The PyCMSProfile object can be passed back into pyCMS for use in creating
471
+ transforms and such (as in ImageCms.buildTransformFromOpenProfiles()).
472
+
473
+ If ``profileFilename`` is not a valid filename for an ICC profile,
474
+ a :exc:`PyCMSError` will be raised.
475
+
476
+ :param profileFilename: String, as a valid filename path to the ICC profile
477
+ you wish to open, or a file-like object.
478
+ :returns: A CmsProfile class object.
479
+ :exception PyCMSError:
480
+ """
481
+
482
+ try:
483
+ return ImageCmsProfile(profileFilename)
484
+ except (OSError, TypeError, ValueError) as v:
485
+ raise PyCMSError(v) from v
486
+
487
+
488
+ def buildTransform(
489
+ inputProfile: _CmsProfileCompatible,
490
+ outputProfile: _CmsProfileCompatible,
491
+ inMode: str,
492
+ outMode: str,
493
+ renderingIntent: Intent = Intent.PERCEPTUAL,
494
+ flags: Flags = Flags.NONE,
495
+ ) -> ImageCmsTransform:
496
+ """
497
+ (pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the
498
+ ``outputProfile``. Use applyTransform to apply the transform to a given
499
+ image.
500
+
501
+ If the input or output profiles specified are not valid filenames, a
502
+ :exc:`PyCMSError` will be raised. If an error occurs during creation
503
+ of the transform, a :exc:`PyCMSError` will be raised.
504
+
505
+ If ``inMode`` or ``outMode`` are not a mode supported by the ``outputProfile``
506
+ (or by pyCMS), a :exc:`PyCMSError` will be raised.
507
+
508
+ This function builds and returns an ICC transform from the ``inputProfile``
509
+ to the ``outputProfile`` using the ``renderingIntent`` to determine what to do
510
+ with out-of-gamut colors. It will ONLY work for converting images that
511
+ are in ``inMode`` to images that are in ``outMode`` color format (PIL mode,
512
+ i.e. "RGB", "RGBA", "CMYK", etc.).
513
+
514
+ Building the transform is a fair part of the overhead in
515
+ ImageCms.profileToProfile(), so if you're planning on converting multiple
516
+ images using the same input/output settings, this can save you time.
517
+ Once you have a transform object, it can be used with
518
+ ImageCms.applyProfile() to convert images without the need to re-compute
519
+ the lookup table for the transform.
520
+
521
+ The reason pyCMS returns a class object rather than a handle directly
522
+ to the transform is that it needs to keep track of the PIL input/output
523
+ modes that the transform is meant for. These attributes are stored in
524
+ the ``inMode`` and ``outMode`` attributes of the object (which can be
525
+ manually overridden if you really want to, but I don't know of any
526
+ time that would be of use, or would even work).
527
+
528
+ :param inputProfile: String, as a valid filename path to the ICC input
529
+ profile you wish to use for this transform, or a profile object
530
+ :param outputProfile: String, as a valid filename path to the ICC output
531
+ profile you wish to use for this transform, or a profile object
532
+ :param inMode: String, as a valid PIL mode that the appropriate profile
533
+ also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
534
+ :param outMode: String, as a valid PIL mode that the appropriate profile
535
+ also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
536
+ :param renderingIntent: Integer (0-3) specifying the rendering intent you
537
+ wish to use for the transform
538
+
539
+ ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
540
+ ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
541
+ ImageCms.Intent.SATURATION = 2
542
+ ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
543
+
544
+ see the pyCMS documentation for details on rendering intents and what
545
+ they do.
546
+ :param flags: Integer (0-...) specifying additional flags
547
+ :returns: A CmsTransform class object.
548
+ :exception PyCMSError:
549
+ """
550
+
551
+ if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3):
552
+ msg = "renderingIntent must be an integer between 0 and 3"
553
+ raise PyCMSError(msg)
554
+
555
+ if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
556
+ msg = f"flags must be an integer between 0 and {_MAX_FLAG}"
557
+ raise PyCMSError(msg)
558
+
559
+ try:
560
+ if not isinstance(inputProfile, ImageCmsProfile):
561
+ inputProfile = ImageCmsProfile(inputProfile)
562
+ if not isinstance(outputProfile, ImageCmsProfile):
563
+ outputProfile = ImageCmsProfile(outputProfile)
564
+ return ImageCmsTransform(
565
+ inputProfile, outputProfile, inMode, outMode, renderingIntent, flags=flags
566
+ )
567
+ except (OSError, TypeError, ValueError) as v:
568
+ raise PyCMSError(v) from v
569
+
570
+
571
+ def buildProofTransform(
572
+ inputProfile: _CmsProfileCompatible,
573
+ outputProfile: _CmsProfileCompatible,
574
+ proofProfile: _CmsProfileCompatible,
575
+ inMode: str,
576
+ outMode: str,
577
+ renderingIntent: Intent = Intent.PERCEPTUAL,
578
+ proofRenderingIntent: Intent = Intent.ABSOLUTE_COLORIMETRIC,
579
+ flags: Flags = Flags.SOFTPROOFING,
580
+ ) -> ImageCmsTransform:
581
+ """
582
+ (pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the
583
+ ``outputProfile``, but tries to simulate the result that would be
584
+ obtained on the ``proofProfile`` device.
585
+
586
+ If the input, output, or proof profiles specified are not valid
587
+ filenames, a :exc:`PyCMSError` will be raised.
588
+
589
+ If an error occurs during creation of the transform,
590
+ a :exc:`PyCMSError` will be raised.
591
+
592
+ If ``inMode`` or ``outMode`` are not a mode supported by the ``outputProfile``
593
+ (or by pyCMS), a :exc:`PyCMSError` will be raised.
594
+
595
+ This function builds and returns an ICC transform from the ``inputProfile``
596
+ to the ``outputProfile``, but tries to simulate the result that would be
597
+ obtained on the ``proofProfile`` device using ``renderingIntent`` and
598
+ ``proofRenderingIntent`` to determine what to do with out-of-gamut
599
+ colors. This is known as "soft-proofing". It will ONLY work for
600
+ converting images that are in ``inMode`` to images that are in outMode
601
+ color format (PIL mode, i.e. "RGB", "RGBA", "CMYK", etc.).
602
+
603
+ Usage of the resulting transform object is exactly the same as with
604
+ ImageCms.buildTransform().
605
+
606
+ Proof profiling is generally used when using an output device to get a
607
+ good idea of what the final printed/displayed image would look like on
608
+ the ``proofProfile`` device when it's quicker and easier to use the
609
+ output device for judging color. Generally, this means that the
610
+ output device is a monitor, or a dye-sub printer (etc.), and the simulated
611
+ device is something more expensive, complicated, or time consuming
612
+ (making it difficult to make a real print for color judgement purposes).
613
+
614
+ Soft-proofing basically functions by adjusting the colors on the
615
+ output device to match the colors of the device being simulated. However,
616
+ when the simulated device has a much wider gamut than the output
617
+ device, you may obtain marginal results.
618
+
619
+ :param inputProfile: String, as a valid filename path to the ICC input
620
+ profile you wish to use for this transform, or a profile object
621
+ :param outputProfile: String, as a valid filename path to the ICC output
622
+ (monitor, usually) profile you wish to use for this transform, or a
623
+ profile object
624
+ :param proofProfile: String, as a valid filename path to the ICC proof
625
+ profile you wish to use for this transform, or a profile object
626
+ :param inMode: String, as a valid PIL mode that the appropriate profile
627
+ also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
628
+ :param outMode: String, as a valid PIL mode that the appropriate profile
629
+ also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
630
+ :param renderingIntent: Integer (0-3) specifying the rendering intent you
631
+ wish to use for the input->proof (simulated) transform
632
+
633
+ ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
634
+ ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
635
+ ImageCms.Intent.SATURATION = 2
636
+ ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
637
+
638
+ see the pyCMS documentation for details on rendering intents and what
639
+ they do.
640
+ :param proofRenderingIntent: Integer (0-3) specifying the rendering intent
641
+ you wish to use for proof->output transform
642
+
643
+ ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
644
+ ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
645
+ ImageCms.Intent.SATURATION = 2
646
+ ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
647
+
648
+ see the pyCMS documentation for details on rendering intents and what
649
+ they do.
650
+ :param flags: Integer (0-...) specifying additional flags
651
+ :returns: A CmsTransform class object.
652
+ :exception PyCMSError:
653
+ """
654
+
655
+ if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3):
656
+ msg = "renderingIntent must be an integer between 0 and 3"
657
+ raise PyCMSError(msg)
658
+
659
+ if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
660
+ msg = f"flags must be an integer between 0 and {_MAX_FLAG}"
661
+ raise PyCMSError(msg)
662
+
663
+ try:
664
+ if not isinstance(inputProfile, ImageCmsProfile):
665
+ inputProfile = ImageCmsProfile(inputProfile)
666
+ if not isinstance(outputProfile, ImageCmsProfile):
667
+ outputProfile = ImageCmsProfile(outputProfile)
668
+ if not isinstance(proofProfile, ImageCmsProfile):
669
+ proofProfile = ImageCmsProfile(proofProfile)
670
+ return ImageCmsTransform(
671
+ inputProfile,
672
+ outputProfile,
673
+ inMode,
674
+ outMode,
675
+ renderingIntent,
676
+ proofProfile,
677
+ proofRenderingIntent,
678
+ flags,
679
+ )
680
+ except (OSError, TypeError, ValueError) as v:
681
+ raise PyCMSError(v) from v
682
+
683
+
684
+ buildTransformFromOpenProfiles = buildTransform
685
+ buildProofTransformFromOpenProfiles = buildProofTransform
686
+
687
+
688
+ def applyTransform(
689
+ im: Image.Image, transform: ImageCmsTransform, inPlace: bool = False
690
+ ) -> Image.Image | None:
691
+ """
692
+ (pyCMS) Applies a transform to a given image.
693
+
694
+ If ``im.mode != transform.input_mode``, a :exc:`PyCMSError` is raised.
695
+
696
+ If ``inPlace`` is ``True`` and ``transform.input_mode != transform.output_mode``, a
697
+ :exc:`PyCMSError` is raised.
698
+
699
+ If ``im.mode``, ``transform.input_mode`` or ``transform.output_mode`` is not
700
+ supported by pyCMSdll or the profiles you used for the transform, a
701
+ :exc:`PyCMSError` is raised.
702
+
703
+ If an error occurs while the transform is being applied,
704
+ a :exc:`PyCMSError` is raised.
705
+
706
+ This function applies a pre-calculated transform (from
707
+ ImageCms.buildTransform() or ImageCms.buildTransformFromOpenProfiles())
708
+ to an image. The transform can be used for multiple images, saving
709
+ considerable calculation time if doing the same conversion multiple times.
710
+
711
+ If you want to modify im in-place instead of receiving a new image as
712
+ the return value, set ``inPlace`` to ``True``. This can only be done if
713
+ ``transform.input_mode`` and ``transform.output_mode`` are the same, because we
714
+ can't change the mode in-place (the buffer sizes for some modes are
715
+ different). The default behavior is to return a new :py:class:`~PIL.Image.Image`
716
+ object of the same dimensions in mode ``transform.output_mode``.
717
+
718
+ :param im: An :py:class:`~PIL.Image.Image` object, and ``im.mode`` must be the same
719
+ as the ``input_mode`` supported by the transform.
720
+ :param transform: A valid CmsTransform class object
721
+ :param inPlace: Bool. If ``True``, ``im`` is modified in place and ``None`` is
722
+ returned, if ``False``, a new :py:class:`~PIL.Image.Image` object with the
723
+ transform applied is returned (and ``im`` is not changed). The default is
724
+ ``False``.
725
+ :returns: Either ``None``, or a new :py:class:`~PIL.Image.Image` object,
726
+ depending on the value of ``inPlace``. The profile will be returned in
727
+ the image's ``info['icc_profile']``.
728
+ :exception PyCMSError:
729
+ """
730
+
731
+ try:
732
+ if inPlace:
733
+ transform.apply_in_place(im)
734
+ imOut = None
735
+ else:
736
+ imOut = transform.apply(im)
737
+ except (TypeError, ValueError) as v:
738
+ raise PyCMSError(v) from v
739
+
740
+ return imOut
741
+
742
+
743
+ def createProfile(
744
+ colorSpace: Literal["LAB", "XYZ", "sRGB"], colorTemp: SupportsFloat = 0
745
+ ) -> core.CmsProfile:
746
+ """
747
+ (pyCMS) Creates a profile.
748
+
749
+ If colorSpace not in ``["LAB", "XYZ", "sRGB"]``,
750
+ a :exc:`PyCMSError` is raised.
751
+
752
+ If using LAB and ``colorTemp`` is not a positive integer,
753
+ a :exc:`PyCMSError` is raised.
754
+
755
+ If an error occurs while creating the profile,
756
+ a :exc:`PyCMSError` is raised.
757
+
758
+ Use this function to create common profiles on-the-fly instead of
759
+ having to supply a profile on disk and knowing the path to it. It
760
+ returns a normal CmsProfile object that can be passed to
761
+ ImageCms.buildTransformFromOpenProfiles() to create a transform to apply
762
+ to images.
763
+
764
+ :param colorSpace: String, the color space of the profile you wish to
765
+ create.
766
+ Currently only "LAB", "XYZ", and "sRGB" are supported.
767
+ :param colorTemp: Positive number for the white point for the profile, in
768
+ degrees Kelvin (i.e. 5000, 6500, 9600, etc.). The default is for D50
769
+ illuminant if omitted (5000k). colorTemp is ONLY applied to LAB
770
+ profiles, and is ignored for XYZ and sRGB.
771
+ :returns: A CmsProfile class object
772
+ :exception PyCMSError:
773
+ """
774
+
775
+ if colorSpace not in ["LAB", "XYZ", "sRGB"]:
776
+ msg = (
777
+ f"Color space not supported for on-the-fly profile creation ({colorSpace})"
778
+ )
779
+ raise PyCMSError(msg)
780
+
781
+ if colorSpace == "LAB":
782
+ try:
783
+ colorTemp = float(colorTemp)
784
+ except (TypeError, ValueError) as e:
785
+ msg = f'Color temperature must be numeric, "{colorTemp}" not valid'
786
+ raise PyCMSError(msg) from e
787
+
788
+ try:
789
+ return core.createProfile(colorSpace, colorTemp)
790
+ except (TypeError, ValueError) as v:
791
+ raise PyCMSError(v) from v
792
+
793
+
794
+ def getProfileName(profile: _CmsProfileCompatible) -> str:
795
+ """
796
+
797
+ (pyCMS) Gets the internal product name for the given profile.
798
+
799
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile,
800
+ a :exc:`PyCMSError` is raised If an error occurs while trying
801
+ to obtain the name tag, a :exc:`PyCMSError` is raised.
802
+
803
+ Use this function to obtain the INTERNAL name of the profile (stored
804
+ in an ICC tag in the profile itself), usually the one used when the
805
+ profile was originally created. Sometimes this tag also contains
806
+ additional information supplied by the creator.
807
+
808
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
809
+ filename of an ICC profile.
810
+ :returns: A string containing the internal name of the profile as stored
811
+ in an ICC tag.
812
+ :exception PyCMSError:
813
+ """
814
+
815
+ try:
816
+ # add an extra newline to preserve pyCMS compatibility
817
+ if not isinstance(profile, ImageCmsProfile):
818
+ profile = ImageCmsProfile(profile)
819
+ # do it in python, not c.
820
+ # // name was "%s - %s" (model, manufacturer) || Description ,
821
+ # // but if the Model and Manufacturer were the same or the model
822
+ # // was long, Just the model, in 1.x
823
+ model = profile.profile.model
824
+ manufacturer = profile.profile.manufacturer
825
+
826
+ if not (model or manufacturer):
827
+ return (profile.profile.profile_description or "") + "\n"
828
+ if not manufacturer or (model and len(model) > 30):
829
+ return f"{model}\n"
830
+ return f"{model} - {manufacturer}\n"
831
+
832
+ except (AttributeError, OSError, TypeError, ValueError) as v:
833
+ raise PyCMSError(v) from v
834
+
835
+
836
+ def getProfileInfo(profile: _CmsProfileCompatible) -> str:
837
+ """
838
+ (pyCMS) Gets the internal product information for the given profile.
839
+
840
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile,
841
+ a :exc:`PyCMSError` is raised.
842
+
843
+ If an error occurs while trying to obtain the info tag,
844
+ a :exc:`PyCMSError` is raised.
845
+
846
+ Use this function to obtain the information stored in the profile's
847
+ info tag. This often contains details about the profile, and how it
848
+ was created, as supplied by the creator.
849
+
850
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
851
+ filename of an ICC profile.
852
+ :returns: A string containing the internal profile information stored in
853
+ an ICC tag.
854
+ :exception PyCMSError:
855
+ """
856
+
857
+ try:
858
+ if not isinstance(profile, ImageCmsProfile):
859
+ profile = ImageCmsProfile(profile)
860
+ # add an extra newline to preserve pyCMS compatibility
861
+ # Python, not C. the white point bits weren't working well,
862
+ # so skipping.
863
+ # info was description \r\n\r\n copyright \r\n\r\n K007 tag \r\n\r\n whitepoint
864
+ description = profile.profile.profile_description
865
+ cpright = profile.profile.copyright
866
+ elements = [element for element in (description, cpright) if element]
867
+ return "\r\n\r\n".join(elements) + "\r\n\r\n"
868
+
869
+ except (AttributeError, OSError, TypeError, ValueError) as v:
870
+ raise PyCMSError(v) from v
871
+
872
+
873
+ def getProfileCopyright(profile: _CmsProfileCompatible) -> str:
874
+ """
875
+ (pyCMS) Gets the copyright for the given profile.
876
+
877
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
878
+ :exc:`PyCMSError` is raised.
879
+
880
+ If an error occurs while trying to obtain the copyright tag,
881
+ a :exc:`PyCMSError` is raised.
882
+
883
+ Use this function to obtain the information stored in the profile's
884
+ copyright tag.
885
+
886
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
887
+ filename of an ICC profile.
888
+ :returns: A string containing the internal profile information stored in
889
+ an ICC tag.
890
+ :exception PyCMSError:
891
+ """
892
+ try:
893
+ # add an extra newline to preserve pyCMS compatibility
894
+ if not isinstance(profile, ImageCmsProfile):
895
+ profile = ImageCmsProfile(profile)
896
+ return (profile.profile.copyright or "") + "\n"
897
+ except (AttributeError, OSError, TypeError, ValueError) as v:
898
+ raise PyCMSError(v) from v
899
+
900
+
901
+ def getProfileManufacturer(profile: _CmsProfileCompatible) -> str:
902
+ """
903
+ (pyCMS) Gets the manufacturer for the given profile.
904
+
905
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
906
+ :exc:`PyCMSError` is raised.
907
+
908
+ If an error occurs while trying to obtain the manufacturer tag, a
909
+ :exc:`PyCMSError` is raised.
910
+
911
+ Use this function to obtain the information stored in the profile's
912
+ manufacturer tag.
913
+
914
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
915
+ filename of an ICC profile.
916
+ :returns: A string containing the internal profile information stored in
917
+ an ICC tag.
918
+ :exception PyCMSError:
919
+ """
920
+ try:
921
+ # add an extra newline to preserve pyCMS compatibility
922
+ if not isinstance(profile, ImageCmsProfile):
923
+ profile = ImageCmsProfile(profile)
924
+ return (profile.profile.manufacturer or "") + "\n"
925
+ except (AttributeError, OSError, TypeError, ValueError) as v:
926
+ raise PyCMSError(v) from v
927
+
928
+
929
+ def getProfileModel(profile: _CmsProfileCompatible) -> str:
930
+ """
931
+ (pyCMS) Gets the model for the given profile.
932
+
933
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
934
+ :exc:`PyCMSError` is raised.
935
+
936
+ If an error occurs while trying to obtain the model tag,
937
+ a :exc:`PyCMSError` is raised.
938
+
939
+ Use this function to obtain the information stored in the profile's
940
+ model tag.
941
+
942
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
943
+ filename of an ICC profile.
944
+ :returns: A string containing the internal profile information stored in
945
+ an ICC tag.
946
+ :exception PyCMSError:
947
+ """
948
+
949
+ try:
950
+ # add an extra newline to preserve pyCMS compatibility
951
+ if not isinstance(profile, ImageCmsProfile):
952
+ profile = ImageCmsProfile(profile)
953
+ return (profile.profile.model or "") + "\n"
954
+ except (AttributeError, OSError, TypeError, ValueError) as v:
955
+ raise PyCMSError(v) from v
956
+
957
+
958
+ def getProfileDescription(profile: _CmsProfileCompatible) -> str:
959
+ """
960
+ (pyCMS) Gets the description for the given profile.
961
+
962
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
963
+ :exc:`PyCMSError` is raised.
964
+
965
+ If an error occurs while trying to obtain the description tag,
966
+ a :exc:`PyCMSError` is raised.
967
+
968
+ Use this function to obtain the information stored in the profile's
969
+ description tag.
970
+
971
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
972
+ filename of an ICC profile.
973
+ :returns: A string containing the internal profile information stored in an
974
+ ICC tag.
975
+ :exception PyCMSError:
976
+ """
977
+
978
+ try:
979
+ # add an extra newline to preserve pyCMS compatibility
980
+ if not isinstance(profile, ImageCmsProfile):
981
+ profile = ImageCmsProfile(profile)
982
+ return (profile.profile.profile_description or "") + "\n"
983
+ except (AttributeError, OSError, TypeError, ValueError) as v:
984
+ raise PyCMSError(v) from v
985
+
986
+
987
+ def getDefaultIntent(profile: _CmsProfileCompatible) -> int:
988
+ """
989
+ (pyCMS) Gets the default intent name for the given profile.
990
+
991
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
992
+ :exc:`PyCMSError` is raised.
993
+
994
+ If an error occurs while trying to obtain the default intent, a
995
+ :exc:`PyCMSError` is raised.
996
+
997
+ Use this function to determine the default (and usually best optimized)
998
+ rendering intent for this profile. Most profiles support multiple
999
+ rendering intents, but are intended mostly for one type of conversion.
1000
+ If you wish to use a different intent than returned, use
1001
+ ImageCms.isIntentSupported() to verify it will work first.
1002
+
1003
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
1004
+ filename of an ICC profile.
1005
+ :returns: Integer 0-3 specifying the default rendering intent for this
1006
+ profile.
1007
+
1008
+ ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
1009
+ ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
1010
+ ImageCms.Intent.SATURATION = 2
1011
+ ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
1012
+
1013
+ see the pyCMS documentation for details on rendering intents and what
1014
+ they do.
1015
+ :exception PyCMSError:
1016
+ """
1017
+
1018
+ try:
1019
+ if not isinstance(profile, ImageCmsProfile):
1020
+ profile = ImageCmsProfile(profile)
1021
+ return profile.profile.rendering_intent
1022
+ except (AttributeError, OSError, TypeError, ValueError) as v:
1023
+ raise PyCMSError(v) from v
1024
+
1025
+
1026
+ def isIntentSupported(
1027
+ profile: _CmsProfileCompatible, intent: Intent, direction: Direction
1028
+ ) -> Literal[-1, 1]:
1029
+ """
1030
+ (pyCMS) Checks if a given intent is supported.
1031
+
1032
+ Use this function to verify that you can use your desired
1033
+ ``intent`` with ``profile``, and that ``profile`` can be used for the
1034
+ input/output/proof profile as you desire.
1035
+
1036
+ Some profiles are created specifically for one "direction", can cannot
1037
+ be used for others. Some profiles can only be used for certain
1038
+ rendering intents, so it's best to either verify this before trying
1039
+ to create a transform with them (using this function), or catch the
1040
+ potential :exc:`PyCMSError` that will occur if they don't
1041
+ support the modes you select.
1042
+
1043
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
1044
+ filename of an ICC profile.
1045
+ :param intent: Integer (0-3) specifying the rendering intent you wish to
1046
+ use with this profile
1047
+
1048
+ ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
1049
+ ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
1050
+ ImageCms.Intent.SATURATION = 2
1051
+ ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
1052
+
1053
+ see the pyCMS documentation for details on rendering intents and what
1054
+ they do.
1055
+ :param direction: Integer specifying if the profile is to be used for
1056
+ input, output, or proof
1057
+
1058
+ INPUT = 0 (or use ImageCms.Direction.INPUT)
1059
+ OUTPUT = 1 (or use ImageCms.Direction.OUTPUT)
1060
+ PROOF = 2 (or use ImageCms.Direction.PROOF)
1061
+
1062
+ :returns: 1 if the intent/direction are supported, -1 if they are not.
1063
+ :exception PyCMSError:
1064
+ """
1065
+
1066
+ try:
1067
+ if not isinstance(profile, ImageCmsProfile):
1068
+ profile = ImageCmsProfile(profile)
1069
+ # FIXME: I get different results for the same data w. different
1070
+ # compilers. Bug in LittleCMS or in the binding?
1071
+ if profile.profile.is_intent_supported(intent, direction):
1072
+ return 1
1073
+ else:
1074
+ return -1
1075
+ except (AttributeError, OSError, TypeError, ValueError) as v:
1076
+ raise PyCMSError(v) from v
.venv/Lib/site-packages/PIL/ImageColor.py ADDED
@@ -0,0 +1,320 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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: str) -> tuple[int, int, int] | tuple[int, int, int, int]:
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
+ rgb_tuple = getrgb(rgb)
48
+ assert len(rgb_tuple) == 3
49
+ colormap[color] = rgb_tuple
50
+ return rgb_tuple
51
+
52
+ # check for known string formats
53
+ if re.match("#[a-f0-9]{3}$", color):
54
+ return int(color[1] * 2, 16), int(color[2] * 2, 16), int(color[3] * 2, 16)
55
+
56
+ if re.match("#[a-f0-9]{4}$", color):
57
+ return (
58
+ int(color[1] * 2, 16),
59
+ int(color[2] * 2, 16),
60
+ int(color[3] * 2, 16),
61
+ int(color[4] * 2, 16),
62
+ )
63
+
64
+ if re.match("#[a-f0-9]{6}$", color):
65
+ return int(color[1:3], 16), int(color[3:5], 16), int(color[5:7], 16)
66
+
67
+ if re.match("#[a-f0-9]{8}$", color):
68
+ return (
69
+ int(color[1:3], 16),
70
+ int(color[3:5], 16),
71
+ int(color[5:7], 16),
72
+ int(color[7:9], 16),
73
+ )
74
+
75
+ m = re.match(r"rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$", color)
76
+ if m:
77
+ return int(m.group(1)), int(m.group(2)), int(m.group(3))
78
+
79
+ m = re.match(r"rgb\(\s*(\d+)%\s*,\s*(\d+)%\s*,\s*(\d+)%\s*\)$", color)
80
+ if m:
81
+ return (
82
+ int((int(m.group(1)) * 255) / 100.0 + 0.5),
83
+ int((int(m.group(2)) * 255) / 100.0 + 0.5),
84
+ int((int(m.group(3)) * 255) / 100.0 + 0.5),
85
+ )
86
+
87
+ m = re.match(
88
+ r"hsl\(\s*(\d+\.?\d*)\s*,\s*(\d+\.?\d*)%\s*,\s*(\d+\.?\d*)%\s*\)$", color
89
+ )
90
+ if m:
91
+ from colorsys import hls_to_rgb
92
+
93
+ rgb_floats = hls_to_rgb(
94
+ float(m.group(1)) / 360.0,
95
+ float(m.group(3)) / 100.0,
96
+ float(m.group(2)) / 100.0,
97
+ )
98
+ return (
99
+ int(rgb_floats[0] * 255 + 0.5),
100
+ int(rgb_floats[1] * 255 + 0.5),
101
+ int(rgb_floats[2] * 255 + 0.5),
102
+ )
103
+
104
+ m = re.match(
105
+ r"hs[bv]\(\s*(\d+\.?\d*)\s*,\s*(\d+\.?\d*)%\s*,\s*(\d+\.?\d*)%\s*\)$", color
106
+ )
107
+ if m:
108
+ from colorsys import hsv_to_rgb
109
+
110
+ rgb_floats = hsv_to_rgb(
111
+ float(m.group(1)) / 360.0,
112
+ float(m.group(2)) / 100.0,
113
+ float(m.group(3)) / 100.0,
114
+ )
115
+ return (
116
+ int(rgb_floats[0] * 255 + 0.5),
117
+ int(rgb_floats[1] * 255 + 0.5),
118
+ int(rgb_floats[2] * 255 + 0.5),
119
+ )
120
+
121
+ m = re.match(r"rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$", color)
122
+ if m:
123
+ return int(m.group(1)), int(m.group(2)), int(m.group(3)), int(m.group(4))
124
+ msg = f"unknown color specifier: {repr(color)}"
125
+ raise ValueError(msg)
126
+
127
+
128
+ @lru_cache
129
+ def getcolor(color: str, mode: str) -> int | tuple[int, ...]:
130
+ """
131
+ Same as :py:func:`~PIL.ImageColor.getrgb` for most modes. However, if
132
+ ``mode`` is HSV, converts the RGB value to a HSV value, or if ``mode`` is
133
+ not color or a palette image, converts the RGB value to a grayscale value.
134
+ If the string cannot be parsed, this function raises a :py:exc:`ValueError`
135
+ exception.
136
+
137
+ .. versionadded:: 1.1.4
138
+
139
+ :param color: A color string
140
+ :param mode: Convert result to this mode
141
+ :return: ``graylevel, (graylevel, alpha) or (red, green, blue[, alpha])``
142
+ """
143
+ # same as getrgb, but converts the result to the given mode
144
+ rgb, alpha = getrgb(color), 255
145
+ if len(rgb) == 4:
146
+ alpha = rgb[3]
147
+ rgb = rgb[:3]
148
+
149
+ if mode == "HSV":
150
+ from colorsys import rgb_to_hsv
151
+
152
+ r, g, b = rgb
153
+ h, s, v = rgb_to_hsv(r / 255, g / 255, b / 255)
154
+ return int(h * 255), int(s * 255), int(v * 255)
155
+ elif Image.getmodebase(mode) == "L":
156
+ r, g, b = rgb
157
+ # ITU-R Recommendation 601-2 for nonlinear RGB
158
+ # scaled to 24 bits to match the convert's implementation.
159
+ graylevel = (r * 19595 + g * 38470 + b * 7471 + 0x8000) >> 16
160
+ if mode[-1] == "A":
161
+ return graylevel, alpha
162
+ return graylevel
163
+ elif mode[-1] == "A":
164
+ return rgb + (alpha,)
165
+ return rgb
166
+
167
+
168
+ colormap: dict[str, str | tuple[int, int, int]] = {
169
+ # X11 colour table from https://drafts.csswg.org/css-color-4/, with
170
+ # gray/grey spelling issues fixed. This is a superset of HTML 4.0
171
+ # colour names used in CSS 1.
172
+ "aliceblue": "#f0f8ff",
173
+ "antiquewhite": "#faebd7",
174
+ "aqua": "#00ffff",
175
+ "aquamarine": "#7fffd4",
176
+ "azure": "#f0ffff",
177
+ "beige": "#f5f5dc",
178
+ "bisque": "#ffe4c4",
179
+ "black": "#000000",
180
+ "blanchedalmond": "#ffebcd",
181
+ "blue": "#0000ff",
182
+ "blueviolet": "#8a2be2",
183
+ "brown": "#a52a2a",
184
+ "burlywood": "#deb887",
185
+ "cadetblue": "#5f9ea0",
186
+ "chartreuse": "#7fff00",
187
+ "chocolate": "#d2691e",
188
+ "coral": "#ff7f50",
189
+ "cornflowerblue": "#6495ed",
190
+ "cornsilk": "#fff8dc",
191
+ "crimson": "#dc143c",
192
+ "cyan": "#00ffff",
193
+ "darkblue": "#00008b",
194
+ "darkcyan": "#008b8b",
195
+ "darkgoldenrod": "#b8860b",
196
+ "darkgray": "#a9a9a9",
197
+ "darkgrey": "#a9a9a9",
198
+ "darkgreen": "#006400",
199
+ "darkkhaki": "#bdb76b",
200
+ "darkmagenta": "#8b008b",
201
+ "darkolivegreen": "#556b2f",
202
+ "darkorange": "#ff8c00",
203
+ "darkorchid": "#9932cc",
204
+ "darkred": "#8b0000",
205
+ "darksalmon": "#e9967a",
206
+ "darkseagreen": "#8fbc8f",
207
+ "darkslateblue": "#483d8b",
208
+ "darkslategray": "#2f4f4f",
209
+ "darkslategrey": "#2f4f4f",
210
+ "darkturquoise": "#00ced1",
211
+ "darkviolet": "#9400d3",
212
+ "deeppink": "#ff1493",
213
+ "deepskyblue": "#00bfff",
214
+ "dimgray": "#696969",
215
+ "dimgrey": "#696969",
216
+ "dodgerblue": "#1e90ff",
217
+ "firebrick": "#b22222",
218
+ "floralwhite": "#fffaf0",
219
+ "forestgreen": "#228b22",
220
+ "fuchsia": "#ff00ff",
221
+ "gainsboro": "#dcdcdc",
222
+ "ghostwhite": "#f8f8ff",
223
+ "gold": "#ffd700",
224
+ "goldenrod": "#daa520",
225
+ "gray": "#808080",
226
+ "grey": "#808080",
227
+ "green": "#008000",
228
+ "greenyellow": "#adff2f",
229
+ "honeydew": "#f0fff0",
230
+ "hotpink": "#ff69b4",
231
+ "indianred": "#cd5c5c",
232
+ "indigo": "#4b0082",
233
+ "ivory": "#fffff0",
234
+ "khaki": "#f0e68c",
235
+ "lavender": "#e6e6fa",
236
+ "lavenderblush": "#fff0f5",
237
+ "lawngreen": "#7cfc00",
238
+ "lemonchiffon": "#fffacd",
239
+ "lightblue": "#add8e6",
240
+ "lightcoral": "#f08080",
241
+ "lightcyan": "#e0ffff",
242
+ "lightgoldenrodyellow": "#fafad2",
243
+ "lightgreen": "#90ee90",
244
+ "lightgray": "#d3d3d3",
245
+ "lightgrey": "#d3d3d3",
246
+ "lightpink": "#ffb6c1",
247
+ "lightsalmon": "#ffa07a",
248
+ "lightseagreen": "#20b2aa",
249
+ "lightskyblue": "#87cefa",
250
+ "lightslategray": "#778899",
251
+ "lightslategrey": "#778899",
252
+ "lightsteelblue": "#b0c4de",
253
+ "lightyellow": "#ffffe0",
254
+ "lime": "#00ff00",
255
+ "limegreen": "#32cd32",
256
+ "linen": "#faf0e6",
257
+ "magenta": "#ff00ff",
258
+ "maroon": "#800000",
259
+ "mediumaquamarine": "#66cdaa",
260
+ "mediumblue": "#0000cd",
261
+ "mediumorchid": "#ba55d3",
262
+ "mediumpurple": "#9370db",
263
+ "mediumseagreen": "#3cb371",
264
+ "mediumslateblue": "#7b68ee",
265
+ "mediumspringgreen": "#00fa9a",
266
+ "mediumturquoise": "#48d1cc",
267
+ "mediumvioletred": "#c71585",
268
+ "midnightblue": "#191970",
269
+ "mintcream": "#f5fffa",
270
+ "mistyrose": "#ffe4e1",
271
+ "moccasin": "#ffe4b5",
272
+ "navajowhite": "#ffdead",
273
+ "navy": "#000080",
274
+ "oldlace": "#fdf5e6",
275
+ "olive": "#808000",
276
+ "olivedrab": "#6b8e23",
277
+ "orange": "#ffa500",
278
+ "orangered": "#ff4500",
279
+ "orchid": "#da70d6",
280
+ "palegoldenrod": "#eee8aa",
281
+ "palegreen": "#98fb98",
282
+ "paleturquoise": "#afeeee",
283
+ "palevioletred": "#db7093",
284
+ "papayawhip": "#ffefd5",
285
+ "peachpuff": "#ffdab9",
286
+ "peru": "#cd853f",
287
+ "pink": "#ffc0cb",
288
+ "plum": "#dda0dd",
289
+ "powderblue": "#b0e0e6",
290
+ "purple": "#800080",
291
+ "rebeccapurple": "#663399",
292
+ "red": "#ff0000",
293
+ "rosybrown": "#bc8f8f",
294
+ "royalblue": "#4169e1",
295
+ "saddlebrown": "#8b4513",
296
+ "salmon": "#fa8072",
297
+ "sandybrown": "#f4a460",
298
+ "seagreen": "#2e8b57",
299
+ "seashell": "#fff5ee",
300
+ "sienna": "#a0522d",
301
+ "silver": "#c0c0c0",
302
+ "skyblue": "#87ceeb",
303
+ "slateblue": "#6a5acd",
304
+ "slategray": "#708090",
305
+ "slategrey": "#708090",
306
+ "snow": "#fffafa",
307
+ "springgreen": "#00ff7f",
308
+ "steelblue": "#4682b4",
309
+ "tan": "#d2b48c",
310
+ "teal": "#008080",
311
+ "thistle": "#d8bfd8",
312
+ "tomato": "#ff6347",
313
+ "turquoise": "#40e0d0",
314
+ "violet": "#ee82ee",
315
+ "wheat": "#f5deb3",
316
+ "white": "#ffffff",
317
+ "whitesmoke": "#f5f5f5",
318
+ "yellow": "#ffff00",
319
+ "yellowgreen": "#9acd32",
320
+ }
.venv/Lib/site-packages/PIL/ImageDraw.py ADDED
@@ -0,0 +1,1035 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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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 struct
36
+ from collections.abc import Sequence
37
+ from typing import cast
38
+
39
+ from . import Image, ImageColor, ImageText
40
+
41
+ TYPE_CHECKING = False
42
+ if TYPE_CHECKING:
43
+ from collections.abc import Callable
44
+ from types import ModuleType
45
+ from typing import Any, AnyStr
46
+
47
+ from . import ImageDraw2, ImageFont
48
+ from ._typing import Coords, _Ink
49
+
50
+ # experimental access to the outline API
51
+ Outline: Callable[[], Image.core._Outline] = Image.core.outline
52
+
53
+ """
54
+ A simple 2D drawing interface for PIL images.
55
+ <p>
56
+ Application code should use the <b>Draw</b> factory, instead of
57
+ directly.
58
+ """
59
+
60
+
61
+ class ImageDraw:
62
+ font: (
63
+ ImageFont.ImageFont | ImageFont.FreeTypeFont | ImageFont.TransposedFont | None
64
+ ) = None
65
+
66
+ def __init__(self, im: Image.Image, mode: str | None = None) -> None:
67
+ """
68
+ Create a drawing instance.
69
+
70
+ :param im: The image to draw in.
71
+ :param mode: Optional mode to use for color values. For RGB
72
+ images, this argument can be RGB or RGBA (to blend the
73
+ drawing into the image). For all other modes, this argument
74
+ must be the same as the image mode. If omitted, the mode
75
+ defaults to the mode of the image.
76
+ """
77
+ im._ensure_mutable()
78
+ blend = 0
79
+ if mode is None:
80
+ mode = im.mode
81
+ if mode != im.mode:
82
+ if mode == "RGBA" and im.mode == "RGB":
83
+ blend = 1
84
+ else:
85
+ msg = "mode mismatch"
86
+ raise ValueError(msg)
87
+ if mode == "P":
88
+ self.palette = im.palette
89
+ else:
90
+ self.palette = None
91
+ self._image = im
92
+ self.im = im.im
93
+ self.draw = Image.core.draw(self.im, blend)
94
+ self.mode = mode
95
+ if mode in ("I", "F"):
96
+ self.ink = self.draw.draw_ink(1)
97
+ else:
98
+ self.ink = self.draw.draw_ink(-1)
99
+ if mode in ("1", "P", "I", "F"):
100
+ # FIXME: fix Fill2 to properly support matte for I+F images
101
+ self.fontmode = "1"
102
+ else:
103
+ self.fontmode = "L" # aliasing is okay for other modes
104
+ self.fill = False
105
+
106
+ def getfont(
107
+ self,
108
+ ) -> ImageFont.ImageFont | ImageFont.FreeTypeFont | ImageFont.TransposedFont:
109
+ """
110
+ Get the current default font.
111
+
112
+ To set the default font for this ImageDraw instance::
113
+
114
+ from PIL import ImageDraw, ImageFont
115
+ draw.font = ImageFont.truetype("Tests/fonts/FreeMono.ttf")
116
+
117
+ To set the default font for all future ImageDraw instances::
118
+
119
+ from PIL import ImageDraw, ImageFont
120
+ ImageDraw.ImageDraw.font = ImageFont.truetype("Tests/fonts/FreeMono.ttf")
121
+
122
+ If the current default font is ``None``,
123
+ it is initialized with ``ImageFont.load_default()``.
124
+
125
+ :returns: An image font."""
126
+ if not self.font:
127
+ # FIXME: should add a font repository
128
+ from . import ImageFont
129
+
130
+ self.font = ImageFont.load_default()
131
+ return self.font
132
+
133
+ def _getfont(
134
+ self, font_size: float | None
135
+ ) -> ImageFont.ImageFont | ImageFont.FreeTypeFont | ImageFont.TransposedFont:
136
+ if font_size is not None:
137
+ from . import ImageFont
138
+
139
+ return ImageFont.load_default(font_size)
140
+ else:
141
+ return self.getfont()
142
+
143
+ def _getink(
144
+ self, ink: _Ink | None, fill: _Ink | None = None
145
+ ) -> tuple[int | None, int | None]:
146
+ result_ink = None
147
+ result_fill = None
148
+ if ink is None and fill is None:
149
+ if self.fill:
150
+ result_fill = self.ink
151
+ else:
152
+ result_ink = self.ink
153
+ else:
154
+ if ink is not None:
155
+ if isinstance(ink, str):
156
+ ink = ImageColor.getcolor(ink, self.mode)
157
+ if self.palette and isinstance(ink, tuple):
158
+ ink = self.palette.getcolor(ink, self._image)
159
+ result_ink = self.draw.draw_ink(ink)
160
+ if fill is not None:
161
+ if isinstance(fill, str):
162
+ fill = ImageColor.getcolor(fill, self.mode)
163
+ if self.palette and isinstance(fill, tuple):
164
+ fill = self.palette.getcolor(fill, self._image)
165
+ result_fill = self.draw.draw_ink(fill)
166
+ return result_ink, result_fill
167
+
168
+ def arc(
169
+ self,
170
+ xy: Coords,
171
+ start: float,
172
+ end: float,
173
+ fill: _Ink | None = None,
174
+ width: int = 1,
175
+ ) -> None:
176
+ """Draw an arc."""
177
+ ink, fill = self._getink(fill)
178
+ if ink is not None:
179
+ self.draw.draw_arc(xy, start, end, ink, width)
180
+
181
+ def bitmap(
182
+ self, xy: Sequence[int], bitmap: Image.Image, fill: _Ink | None = None
183
+ ) -> None:
184
+ """Draw a bitmap."""
185
+ bitmap.load()
186
+ ink, fill = self._getink(fill)
187
+ if ink is None:
188
+ ink = fill
189
+ if ink is not None:
190
+ self.draw.draw_bitmap(xy, bitmap.im, ink)
191
+
192
+ def chord(
193
+ self,
194
+ xy: Coords,
195
+ start: float,
196
+ end: float,
197
+ fill: _Ink | None = None,
198
+ outline: _Ink | None = None,
199
+ width: int = 1,
200
+ ) -> None:
201
+ """Draw a chord."""
202
+ ink, fill_ink = self._getink(outline, fill)
203
+ if fill_ink is not None:
204
+ self.draw.draw_chord(xy, start, end, fill_ink, 1)
205
+ if ink is not None and ink != fill_ink and width != 0:
206
+ self.draw.draw_chord(xy, start, end, ink, 0, width)
207
+
208
+ def ellipse(
209
+ self,
210
+ xy: Coords,
211
+ fill: _Ink | None = None,
212
+ outline: _Ink | None = None,
213
+ width: int = 1,
214
+ ) -> None:
215
+ """Draw an ellipse."""
216
+ ink, fill_ink = self._getink(outline, fill)
217
+ if fill_ink is not None:
218
+ self.draw.draw_ellipse(xy, fill_ink, 1)
219
+ if ink is not None and ink != fill_ink and width != 0:
220
+ self.draw.draw_ellipse(xy, ink, 0, width)
221
+
222
+ def circle(
223
+ self,
224
+ xy: Sequence[float],
225
+ radius: float,
226
+ fill: _Ink | None = None,
227
+ outline: _Ink | None = None,
228
+ width: int = 1,
229
+ ) -> None:
230
+ """Draw a circle given center coordinates and a radius."""
231
+ ellipse_xy = (xy[0] - radius, xy[1] - radius, xy[0] + radius, xy[1] + radius)
232
+ self.ellipse(ellipse_xy, fill, outline, width)
233
+
234
+ def line(
235
+ self,
236
+ xy: Coords,
237
+ fill: _Ink | None = None,
238
+ width: int = 0,
239
+ joint: str | None = None,
240
+ ) -> None:
241
+ """Draw a line, or a connected sequence of line segments."""
242
+ ink = self._getink(fill)[0]
243
+ if ink is not None:
244
+ self.draw.draw_lines(xy, ink, width)
245
+ if joint == "curve" and width > 4:
246
+ points: Sequence[Sequence[float]]
247
+ if isinstance(xy[0], (list, tuple)):
248
+ points = cast(Sequence[Sequence[float]], xy)
249
+ else:
250
+ points = [
251
+ cast(Sequence[float], tuple(xy[i : i + 2]))
252
+ for i in range(0, len(xy), 2)
253
+ ]
254
+ for i in range(1, len(points) - 1):
255
+ point = points[i]
256
+ angles = [
257
+ math.degrees(math.atan2(end[0] - start[0], start[1] - end[1]))
258
+ % 360
259
+ for start, end in (
260
+ (points[i - 1], point),
261
+ (point, points[i + 1]),
262
+ )
263
+ ]
264
+ if angles[0] == angles[1]:
265
+ # This is a straight line, so no joint is required
266
+ continue
267
+
268
+ def coord_at_angle(
269
+ coord: Sequence[float], angle: float
270
+ ) -> tuple[float, ...]:
271
+ x, y = coord
272
+ angle -= 90
273
+ distance = width / 2 - 1
274
+ return tuple(
275
+ p + (math.floor(p_d) if p_d > 0 else math.ceil(p_d))
276
+ for p, p_d in (
277
+ (x, distance * math.cos(math.radians(angle))),
278
+ (y, distance * math.sin(math.radians(angle))),
279
+ )
280
+ )
281
+
282
+ flipped = (
283
+ angles[1] > angles[0] and angles[1] - 180 > angles[0]
284
+ ) or (angles[1] < angles[0] and angles[1] + 180 > angles[0])
285
+ coords = [
286
+ (point[0] - width / 2 + 1, point[1] - width / 2 + 1),
287
+ (point[0] + width / 2 - 1, point[1] + width / 2 - 1),
288
+ ]
289
+ if flipped:
290
+ start, end = (angles[1] + 90, angles[0] + 90)
291
+ else:
292
+ start, end = (angles[0] - 90, angles[1] - 90)
293
+ self.pieslice(coords, start - 90, end - 90, fill)
294
+
295
+ if width > 8:
296
+ # Cover potential gaps between the line and the joint
297
+ if flipped:
298
+ gap_coords = [
299
+ coord_at_angle(point, angles[0] + 90),
300
+ point,
301
+ coord_at_angle(point, angles[1] + 90),
302
+ ]
303
+ else:
304
+ gap_coords = [
305
+ coord_at_angle(point, angles[0] - 90),
306
+ point,
307
+ coord_at_angle(point, angles[1] - 90),
308
+ ]
309
+ self.line(gap_coords, fill, width=3)
310
+
311
+ def shape(
312
+ self,
313
+ shape: Image.core._Outline,
314
+ fill: _Ink | None = None,
315
+ outline: _Ink | None = None,
316
+ ) -> None:
317
+ """(Experimental) Draw a shape."""
318
+ shape.close()
319
+ ink, fill_ink = self._getink(outline, fill)
320
+ if fill_ink is not None:
321
+ self.draw.draw_outline(shape, fill_ink, 1)
322
+ if ink is not None and ink != fill_ink:
323
+ self.draw.draw_outline(shape, ink, 0)
324
+
325
+ def pieslice(
326
+ self,
327
+ xy: Coords,
328
+ start: float,
329
+ end: float,
330
+ fill: _Ink | None = None,
331
+ outline: _Ink | None = None,
332
+ width: int = 1,
333
+ ) -> None:
334
+ """Draw a pieslice."""
335
+ ink, fill_ink = self._getink(outline, fill)
336
+ if fill_ink is not None:
337
+ self.draw.draw_pieslice(xy, start, end, fill_ink, 1)
338
+ if ink is not None and ink != fill_ink and width != 0:
339
+ self.draw.draw_pieslice(xy, start, end, ink, 0, width)
340
+
341
+ def point(self, xy: Coords, fill: _Ink | None = None) -> None:
342
+ """Draw one or more individual pixels."""
343
+ ink, fill = self._getink(fill)
344
+ if ink is not None:
345
+ self.draw.draw_points(xy, ink)
346
+
347
+ def polygon(
348
+ self,
349
+ xy: Coords,
350
+ fill: _Ink | None = None,
351
+ outline: _Ink | None = None,
352
+ width: int = 1,
353
+ ) -> None:
354
+ """Draw a polygon."""
355
+ ink, fill_ink = self._getink(outline, fill)
356
+ if fill_ink is not None:
357
+ self.draw.draw_polygon(xy, fill_ink, 1)
358
+ if ink is not None and ink != fill_ink and width != 0:
359
+ if width == 1:
360
+ self.draw.draw_polygon(xy, ink, 0, width)
361
+ elif self.im is not None:
362
+ # To avoid expanding the polygon outwards,
363
+ # use the fill as a mask
364
+ mask = Image.new("1", self.im.size)
365
+ mask_ink = self._getink(1)[0]
366
+ draw = Draw(mask)
367
+ draw.draw.draw_polygon(xy, mask_ink, 1)
368
+
369
+ self.draw.draw_polygon(xy, ink, 0, width * 2 - 1, mask.im)
370
+
371
+ def regular_polygon(
372
+ self,
373
+ bounding_circle: Sequence[Sequence[float] | float],
374
+ n_sides: int,
375
+ rotation: float = 0,
376
+ fill: _Ink | None = None,
377
+ outline: _Ink | None = None,
378
+ width: int = 1,
379
+ ) -> None:
380
+ """Draw a regular polygon."""
381
+ xy = _compute_regular_polygon_vertices(bounding_circle, n_sides, rotation)
382
+ self.polygon(xy, fill, outline, width)
383
+
384
+ def rectangle(
385
+ self,
386
+ xy: Coords,
387
+ fill: _Ink | None = None,
388
+ outline: _Ink | None = None,
389
+ width: int = 1,
390
+ ) -> None:
391
+ """Draw a rectangle."""
392
+ ink, fill_ink = self._getink(outline, fill)
393
+ if fill_ink is not None:
394
+ self.draw.draw_rectangle(xy, fill_ink, 1)
395
+ if ink is not None and ink != fill_ink and width != 0:
396
+ self.draw.draw_rectangle(xy, ink, 0, width)
397
+
398
+ def rounded_rectangle(
399
+ self,
400
+ xy: Coords,
401
+ radius: float = 0,
402
+ fill: _Ink | None = None,
403
+ outline: _Ink | None = None,
404
+ width: int = 1,
405
+ *,
406
+ corners: tuple[bool, bool, bool, bool] | None = None,
407
+ ) -> None:
408
+ """Draw a rounded rectangle."""
409
+ if isinstance(xy[0], (list, tuple)):
410
+ (x0, y0), (x1, y1) = cast(Sequence[Sequence[float]], xy)
411
+ else:
412
+ x0, y0, x1, y1 = cast(Sequence[float], xy)
413
+ if x1 < x0:
414
+ msg = "x1 must be greater than or equal to x0"
415
+ raise ValueError(msg)
416
+ if y1 < y0:
417
+ msg = "y1 must be greater than or equal to y0"
418
+ raise ValueError(msg)
419
+ if corners is None:
420
+ corners = (True, True, True, True)
421
+
422
+ d = radius * 2
423
+
424
+ x0 = round(x0)
425
+ y0 = round(y0)
426
+ x1 = round(x1)
427
+ y1 = round(y1)
428
+ full_x, full_y = False, False
429
+ if all(corners):
430
+ full_x = d >= x1 - x0 - 1
431
+ if full_x:
432
+ # The two left and two right corners are joined
433
+ d = x1 - x0
434
+ full_y = d >= y1 - y0 - 1
435
+ if full_y:
436
+ # The two top and two bottom corners are joined
437
+ d = y1 - y0
438
+ if full_x and full_y:
439
+ # If all corners are joined, that is a circle
440
+ return self.ellipse(xy, fill, outline, width)
441
+
442
+ if d == 0 or not any(corners):
443
+ # If the corners have no curve,
444
+ # or there are no corners,
445
+ # that is a rectangle
446
+ return self.rectangle(xy, fill, outline, width)
447
+
448
+ r = int(d // 2)
449
+ ink, fill_ink = self._getink(outline, fill)
450
+
451
+ def draw_corners(pieslice: bool) -> None:
452
+ parts: tuple[tuple[tuple[float, float, float, float], int, int], ...]
453
+ if full_x:
454
+ # Draw top and bottom halves
455
+ parts = (
456
+ ((x0, y0, x0 + d, y0 + d), 180, 360),
457
+ ((x0, y1 - d, x0 + d, y1), 0, 180),
458
+ )
459
+ elif full_y:
460
+ # Draw left and right halves
461
+ parts = (
462
+ ((x0, y0, x0 + d, y0 + d), 90, 270),
463
+ ((x1 - d, y0, x1, y0 + d), 270, 90),
464
+ )
465
+ else:
466
+ # Draw four separate corners
467
+ parts = tuple(
468
+ part
469
+ for i, part in enumerate(
470
+ (
471
+ ((x0, y0, x0 + d, y0 + d), 180, 270),
472
+ ((x1 - d, y0, x1, y0 + d), 270, 360),
473
+ ((x1 - d, y1 - d, x1, y1), 0, 90),
474
+ ((x0, y1 - d, x0 + d, y1), 90, 180),
475
+ )
476
+ )
477
+ if corners[i]
478
+ )
479
+ for part in parts:
480
+ if pieslice:
481
+ self.draw.draw_pieslice(*(part + (fill_ink, 1)))
482
+ else:
483
+ self.draw.draw_arc(*(part + (ink, width)))
484
+
485
+ if fill_ink is not None:
486
+ draw_corners(True)
487
+
488
+ if full_x:
489
+ self.draw.draw_rectangle((x0, y0 + r + 1, x1, y1 - r - 1), fill_ink, 1)
490
+ elif x1 - r - 1 >= x0 + r + 1:
491
+ self.draw.draw_rectangle((x0 + r + 1, y0, x1 - r - 1, y1), fill_ink, 1)
492
+ if not full_x and not full_y:
493
+ left = [x0, y0, x0 + r, y1]
494
+ if corners[0]:
495
+ left[1] += r + 1
496
+ if corners[3]:
497
+ left[3] -= r + 1
498
+ self.draw.draw_rectangle(left, fill_ink, 1)
499
+
500
+ right = [x1 - r, y0, x1, y1]
501
+ if corners[1]:
502
+ right[1] += r + 1
503
+ if corners[2]:
504
+ right[3] -= r + 1
505
+ self.draw.draw_rectangle(right, fill_ink, 1)
506
+ if ink is not None and ink != fill_ink and width != 0:
507
+ draw_corners(False)
508
+
509
+ if not full_x:
510
+ top = [x0, y0, x1, y0 + width - 1]
511
+ if corners[0]:
512
+ top[0] += r + 1
513
+ if corners[1]:
514
+ top[2] -= r + 1
515
+ self.draw.draw_rectangle(top, ink, 1)
516
+
517
+ bottom = [x0, y1 - width + 1, x1, y1]
518
+ if corners[3]:
519
+ bottom[0] += r + 1
520
+ if corners[2]:
521
+ bottom[2] -= r + 1
522
+ self.draw.draw_rectangle(bottom, ink, 1)
523
+ if not full_y:
524
+ left = [x0, y0, x0 + width - 1, y1]
525
+ if corners[0]:
526
+ left[1] += r + 1
527
+ if corners[3]:
528
+ left[3] -= r + 1
529
+ self.draw.draw_rectangle(left, ink, 1)
530
+
531
+ right = [x1 - width + 1, y0, x1, y1]
532
+ if corners[1]:
533
+ right[1] += r + 1
534
+ if corners[2]:
535
+ right[3] -= r + 1
536
+ self.draw.draw_rectangle(right, ink, 1)
537
+
538
+ def text(
539
+ self,
540
+ xy: tuple[float, float],
541
+ text: AnyStr | ImageText.Text[AnyStr],
542
+ fill: _Ink | None = None,
543
+ font: (
544
+ ImageFont.ImageFont
545
+ | ImageFont.FreeTypeFont
546
+ | ImageFont.TransposedFont
547
+ | None
548
+ ) = None,
549
+ anchor: str | None = None,
550
+ spacing: float = 4,
551
+ align: str = "left",
552
+ direction: str | None = None,
553
+ features: list[str] | None = None,
554
+ language: str | None = None,
555
+ stroke_width: float = 0,
556
+ stroke_fill: _Ink | None = None,
557
+ embedded_color: bool = False,
558
+ *args: Any,
559
+ **kwargs: Any,
560
+ ) -> None:
561
+ """Draw text."""
562
+ if isinstance(text, ImageText.Text):
563
+ image_text = text
564
+ else:
565
+ if font is None:
566
+ font = self._getfont(kwargs.get("font_size"))
567
+ image_text = ImageText.Text(
568
+ text, font, self.mode, spacing, direction, features, language
569
+ )
570
+ if embedded_color:
571
+ image_text.embed_color()
572
+ if stroke_width:
573
+ image_text.stroke(stroke_width, stroke_fill)
574
+
575
+ def getink(fill: _Ink | None) -> int:
576
+ ink, fill_ink = self._getink(fill)
577
+ if ink is None:
578
+ assert fill_ink is not None
579
+ return fill_ink
580
+ return ink
581
+
582
+ ink = getink(fill)
583
+ if ink is None:
584
+ return
585
+
586
+ stroke_ink = None
587
+ if image_text.stroke_width:
588
+ stroke_ink = (
589
+ getink(image_text.stroke_fill)
590
+ if image_text.stroke_fill is not None
591
+ else ink
592
+ )
593
+
594
+ for line in image_text._split(xy, anchor, align):
595
+
596
+ def draw_text(ink: int, stroke_width: float = 0) -> None:
597
+ mode = self.fontmode
598
+ if stroke_width == 0 and embedded_color:
599
+ mode = "RGBA"
600
+ x = int(line.x)
601
+ y = int(line.y)
602
+ start = (math.modf(line.x)[0], math.modf(line.y)[0])
603
+ try:
604
+ mask, offset = image_text.font.getmask2( # type: ignore[union-attr,misc]
605
+ line.text,
606
+ mode,
607
+ direction=direction,
608
+ features=features,
609
+ language=language,
610
+ stroke_width=stroke_width,
611
+ stroke_filled=True,
612
+ anchor=line.anchor,
613
+ ink=ink,
614
+ start=start,
615
+ *args,
616
+ **kwargs,
617
+ )
618
+ x += offset[0]
619
+ y += offset[1]
620
+ except AttributeError:
621
+ try:
622
+ mask = image_text.font.getmask( # type: ignore[misc]
623
+ line.text,
624
+ mode,
625
+ direction,
626
+ features,
627
+ language,
628
+ stroke_width,
629
+ line.anchor,
630
+ ink,
631
+ start=start,
632
+ *args,
633
+ **kwargs,
634
+ )
635
+ except TypeError:
636
+ mask = image_text.font.getmask(line.text)
637
+ if mode == "RGBA":
638
+ # image_text.font.getmask2(mode="RGBA")
639
+ # returns color in RGB bands and mask in A
640
+ # extract mask and set text alpha
641
+ color, mask = mask, mask.getband(3)
642
+ ink_alpha = struct.pack("i", ink)[3]
643
+ color.fillband(3, ink_alpha)
644
+ if self.im is not None:
645
+ self.im.paste(
646
+ color, (x, y, x + mask.size[0], y + mask.size[1]), mask
647
+ )
648
+ else:
649
+ self.draw.draw_bitmap((x, y), mask, ink)
650
+
651
+ if stroke_ink is not None:
652
+ # Draw stroked text
653
+ draw_text(stroke_ink, image_text.stroke_width)
654
+
655
+ # Draw normal text
656
+ if ink != stroke_ink:
657
+ draw_text(ink)
658
+ else:
659
+ # Only draw normal text
660
+ draw_text(ink)
661
+
662
+ def multiline_text(
663
+ self,
664
+ xy: tuple[float, float],
665
+ text: AnyStr,
666
+ fill: _Ink | None = None,
667
+ font: (
668
+ ImageFont.ImageFont
669
+ | ImageFont.FreeTypeFont
670
+ | ImageFont.TransposedFont
671
+ | None
672
+ ) = None,
673
+ anchor: str | None = None,
674
+ spacing: float = 4,
675
+ align: str = "left",
676
+ direction: str | None = None,
677
+ features: list[str] | None = None,
678
+ language: str | None = None,
679
+ stroke_width: float = 0,
680
+ stroke_fill: _Ink | None = None,
681
+ embedded_color: bool = False,
682
+ *,
683
+ font_size: float | None = None,
684
+ ) -> None:
685
+ return self.text(
686
+ xy,
687
+ text,
688
+ fill,
689
+ font,
690
+ anchor,
691
+ spacing,
692
+ align,
693
+ direction,
694
+ features,
695
+ language,
696
+ stroke_width,
697
+ stroke_fill,
698
+ embedded_color,
699
+ font_size=font_size,
700
+ )
701
+
702
+ def textlength(
703
+ self,
704
+ text: AnyStr,
705
+ font: (
706
+ ImageFont.ImageFont
707
+ | ImageFont.FreeTypeFont
708
+ | ImageFont.TransposedFont
709
+ | None
710
+ ) = None,
711
+ direction: str | None = None,
712
+ features: list[str] | None = None,
713
+ language: str | None = None,
714
+ embedded_color: bool = False,
715
+ *,
716
+ font_size: float | None = None,
717
+ ) -> float:
718
+ """Get the length of a given string, in pixels with 1/64 precision."""
719
+ if font is None:
720
+ font = self._getfont(font_size)
721
+ image_text = ImageText.Text(
722
+ text,
723
+ font,
724
+ self.mode,
725
+ direction=direction,
726
+ features=features,
727
+ language=language,
728
+ )
729
+ if embedded_color:
730
+ image_text.embed_color()
731
+ return image_text.get_length()
732
+
733
+ def textbbox(
734
+ self,
735
+ xy: tuple[float, float],
736
+ text: AnyStr,
737
+ font: (
738
+ ImageFont.ImageFont
739
+ | ImageFont.FreeTypeFont
740
+ | ImageFont.TransposedFont
741
+ | None
742
+ ) = None,
743
+ anchor: str | None = None,
744
+ spacing: float = 4,
745
+ align: str = "left",
746
+ direction: str | None = None,
747
+ features: list[str] | None = None,
748
+ language: str | None = None,
749
+ stroke_width: float = 0,
750
+ embedded_color: bool = False,
751
+ *,
752
+ font_size: float | None = None,
753
+ ) -> tuple[float, float, float, float]:
754
+ """Get the bounding box of a given string, in pixels."""
755
+ if font is None:
756
+ font = self._getfont(font_size)
757
+ image_text = ImageText.Text(
758
+ text, font, self.mode, spacing, direction, features, language
759
+ )
760
+ if embedded_color:
761
+ image_text.embed_color()
762
+ if stroke_width:
763
+ image_text.stroke(stroke_width)
764
+ return image_text.get_bbox(xy, anchor, align)
765
+
766
+ def multiline_textbbox(
767
+ self,
768
+ xy: tuple[float, float],
769
+ text: AnyStr,
770
+ font: (
771
+ ImageFont.ImageFont
772
+ | ImageFont.FreeTypeFont
773
+ | ImageFont.TransposedFont
774
+ | None
775
+ ) = None,
776
+ anchor: str | None = None,
777
+ spacing: float = 4,
778
+ align: str = "left",
779
+ direction: str | None = None,
780
+ features: list[str] | None = None,
781
+ language: str | None = None,
782
+ stroke_width: float = 0,
783
+ embedded_color: bool = False,
784
+ *,
785
+ font_size: float | None = None,
786
+ ) -> tuple[float, float, float, float]:
787
+ return self.textbbox(
788
+ xy,
789
+ text,
790
+ font,
791
+ anchor,
792
+ spacing,
793
+ align,
794
+ direction,
795
+ features,
796
+ language,
797
+ stroke_width,
798
+ embedded_color,
799
+ font_size=font_size,
800
+ )
801
+
802
+
803
+ def Draw(im: Image.Image, mode: str | None = None) -> ImageDraw:
804
+ """
805
+ A simple 2D drawing interface for PIL images.
806
+
807
+ :param im: The image to draw in.
808
+ :param mode: Optional mode to use for color values. For RGB
809
+ images, this argument can be RGB or RGBA (to blend the
810
+ drawing into the image). For all other modes, this argument
811
+ must be the same as the image mode. If omitted, the mode
812
+ defaults to the mode of the image.
813
+ """
814
+ try:
815
+ return getattr(im, "getdraw")(mode)
816
+ except AttributeError:
817
+ return ImageDraw(im, mode)
818
+
819
+
820
+ def getdraw(im: Image.Image | None = None) -> tuple[ImageDraw2.Draw | None, ModuleType]:
821
+ """
822
+ :param im: The image to draw in.
823
+ :returns: A (drawing context, drawing resource factory) tuple.
824
+ """
825
+ from . import ImageDraw2
826
+
827
+ draw = ImageDraw2.Draw(im) if im is not None else None
828
+ return draw, ImageDraw2
829
+
830
+
831
+ def floodfill(
832
+ image: Image.Image,
833
+ xy: tuple[int, int],
834
+ value: float | tuple[int, ...],
835
+ border: float | tuple[int, ...] | None = None,
836
+ thresh: float = 0,
837
+ ) -> None:
838
+ """
839
+ .. warning:: This method is experimental.
840
+
841
+ Fills a bounded region with a given color.
842
+
843
+ :param image: Target image.
844
+ :param xy: Seed position (a 2-item coordinate tuple). See
845
+ :ref:`coordinate-system`.
846
+ :param value: Fill color.
847
+ :param border: Optional border value. If given, the region consists of
848
+ pixels with a color different from the border color. If not given,
849
+ the region consists of pixels having the same color as the seed
850
+ pixel.
851
+ :param thresh: Optional threshold value which specifies a maximum
852
+ tolerable difference of a pixel value from the 'background' in
853
+ order for it to be replaced. Useful for filling regions of
854
+ non-homogeneous, but similar, colors.
855
+ """
856
+ # based on an implementation by Eric S. Raymond
857
+ # amended by yo1995 @20180806
858
+ pixel = image.load()
859
+ assert pixel is not None
860
+ x, y = xy
861
+ try:
862
+ background = pixel[x, y]
863
+ if _color_diff(value, background) <= thresh:
864
+ return # seed point already has fill color
865
+ pixel[x, y] = value
866
+ except (ValueError, IndexError):
867
+ return # seed point outside image
868
+ edge = {(x, y)}
869
+ # use a set to keep record of current and previous edge pixels
870
+ # to reduce memory consumption
871
+ full_edge = set()
872
+ while edge:
873
+ new_edge = set()
874
+ for x, y in edge: # 4 adjacent method
875
+ for s, t in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)):
876
+ # If already processed, or if a coordinate is negative, skip
877
+ if (s, t) in full_edge or s < 0 or t < 0:
878
+ continue
879
+ try:
880
+ p = pixel[s, t]
881
+ except (ValueError, IndexError):
882
+ pass
883
+ else:
884
+ full_edge.add((s, t))
885
+ if border is None:
886
+ fill = _color_diff(p, background) <= thresh
887
+ else:
888
+ fill = p not in (value, border)
889
+ if fill:
890
+ pixel[s, t] = value
891
+ new_edge.add((s, t))
892
+ full_edge = edge # discard pixels processed
893
+ edge = new_edge
894
+
895
+
896
+ def _compute_regular_polygon_vertices(
897
+ bounding_circle: Sequence[Sequence[float] | float], n_sides: int, rotation: float
898
+ ) -> list[tuple[float, float]]:
899
+ """
900
+ Generate a list of vertices for a 2D regular polygon.
901
+
902
+ :param bounding_circle: The bounding circle is a sequence defined
903
+ by a point and radius. The polygon is inscribed in this circle.
904
+ (e.g. ``bounding_circle=(x, y, r)`` or ``((x, y), r)``)
905
+ :param n_sides: Number of sides
906
+ (e.g. ``n_sides=3`` for a triangle, ``6`` for a hexagon)
907
+ :param rotation: Apply an arbitrary rotation to the polygon
908
+ (e.g. ``rotation=90``, applies a 90 degree rotation)
909
+ :return: List of regular polygon vertices
910
+ (e.g. ``[(25, 50), (50, 50), (50, 25), (25, 25)]``)
911
+
912
+ How are the vertices computed?
913
+ 1. Compute the following variables
914
+ - theta: Angle between the apothem & the nearest polygon vertex
915
+ - side_length: Length of each polygon edge
916
+ - centroid: Center of bounding circle (1st, 2nd elements of bounding_circle)
917
+ - polygon_radius: Polygon radius (last element of bounding_circle)
918
+ - angles: Location of each polygon vertex in polar grid
919
+ (e.g. A square with 0 degree rotation => [225.0, 315.0, 45.0, 135.0])
920
+
921
+ 2. For each angle in angles, get the polygon vertex at that angle
922
+ The vertex is computed using the equation below.
923
+ X= xcos(φ) + ysin(φ)
924
+ Y= −xsin(φ) + ycos(φ)
925
+
926
+ Note:
927
+ φ = angle in degrees
928
+ x = 0
929
+ y = polygon_radius
930
+
931
+ The formula above assumes rotation around the origin.
932
+ In our case, we are rotating around the centroid.
933
+ To account for this, we use the formula below
934
+ X = xcos(φ) + ysin(φ) + centroid_x
935
+ Y = −xsin(φ) + ycos(φ) + centroid_y
936
+ """
937
+ # 1. Error Handling
938
+ # 1.1 Check `n_sides` has an appropriate value
939
+ if not isinstance(n_sides, int):
940
+ msg = "n_sides should be an int" # type: ignore[unreachable]
941
+ raise TypeError(msg)
942
+ if n_sides < 3:
943
+ msg = "n_sides should be an int > 2"
944
+ raise ValueError(msg)
945
+
946
+ # 1.2 Check `bounding_circle` has an appropriate value
947
+ if not isinstance(bounding_circle, (list, tuple)):
948
+ msg = "bounding_circle should be a sequence"
949
+ raise TypeError(msg)
950
+
951
+ if len(bounding_circle) == 3:
952
+ if not all(isinstance(i, (int, float)) for i in bounding_circle):
953
+ msg = "bounding_circle should only contain numeric data"
954
+ raise ValueError(msg)
955
+
956
+ *centroid, polygon_radius = cast(list[float], list(bounding_circle))
957
+ elif len(bounding_circle) == 2 and isinstance(bounding_circle[0], (list, tuple)):
958
+ if not all(
959
+ isinstance(i, (int, float)) for i in bounding_circle[0]
960
+ ) or not isinstance(bounding_circle[1], (int, float)):
961
+ msg = "bounding_circle should only contain numeric data"
962
+ raise ValueError(msg)
963
+
964
+ if len(bounding_circle[0]) != 2:
965
+ msg = "bounding_circle centre should contain 2D coordinates (e.g. (x, y))"
966
+ raise ValueError(msg)
967
+
968
+ centroid = cast(list[float], list(bounding_circle[0]))
969
+ polygon_radius = cast(float, bounding_circle[1])
970
+ else:
971
+ msg = (
972
+ "bounding_circle should contain 2D coordinates "
973
+ "and a radius (e.g. (x, y, r) or ((x, y), r) )"
974
+ )
975
+ raise ValueError(msg)
976
+
977
+ if polygon_radius <= 0:
978
+ msg = "bounding_circle radius should be > 0"
979
+ raise ValueError(msg)
980
+
981
+ # 1.3 Check `rotation` has an appropriate value
982
+ if not isinstance(rotation, (int, float)):
983
+ msg = "rotation should be an int or float" # type: ignore[unreachable]
984
+ raise ValueError(msg)
985
+
986
+ # 2. Define Helper Functions
987
+ def _apply_rotation(point: list[float], degrees: float) -> tuple[float, float]:
988
+ return (
989
+ round(
990
+ point[0] * math.cos(math.radians(360 - degrees))
991
+ - point[1] * math.sin(math.radians(360 - degrees))
992
+ + centroid[0],
993
+ 2,
994
+ ),
995
+ round(
996
+ point[1] * math.cos(math.radians(360 - degrees))
997
+ + point[0] * math.sin(math.radians(360 - degrees))
998
+ + centroid[1],
999
+ 2,
1000
+ ),
1001
+ )
1002
+
1003
+ def _compute_polygon_vertex(angle: float) -> tuple[float, float]:
1004
+ start_point = [polygon_radius, 0]
1005
+ return _apply_rotation(start_point, angle)
1006
+
1007
+ def _get_angles(n_sides: int, rotation: float) -> list[float]:
1008
+ angles = []
1009
+ degrees = 360 / n_sides
1010
+ # Start with the bottom left polygon vertex
1011
+ current_angle = (270 - 0.5 * degrees) + rotation
1012
+ for _ in range(n_sides):
1013
+ angles.append(current_angle)
1014
+ current_angle += degrees
1015
+ if current_angle > 360:
1016
+ current_angle -= 360
1017
+ return angles
1018
+
1019
+ # 3. Variable Declarations
1020
+ angles = _get_angles(n_sides, rotation)
1021
+
1022
+ # 4. Compute Vertices
1023
+ return [_compute_polygon_vertex(angle) for angle in angles]
1024
+
1025
+
1026
+ def _color_diff(
1027
+ color1: float | tuple[int, ...], color2: float | tuple[int, ...]
1028
+ ) -> float:
1029
+ """
1030
+ Uses 1-norm distance to calculate difference between two values.
1031
+ """
1032
+ first = color1 if isinstance(color1, tuple) else (color1,)
1033
+ second = color2 if isinstance(color2, tuple) else (color2,)
1034
+
1035
+ return sum(abs(first[i] - second[i]) for i in range(len(second)))
.venv/Lib/site-packages/PIL/ImageDraw2.py ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
26
+ from __future__ import annotations
27
+
28
+ from typing import Any, AnyStr, BinaryIO
29
+
30
+ from . import Image, ImageColor, ImageDraw, ImageFont, ImagePath
31
+ from ._typing import Coords, StrOrBytesPath
32
+
33
+
34
+ class Pen:
35
+ """Stores an outline color and width."""
36
+
37
+ def __init__(self, color: str, width: int = 1, opacity: int = 255) -> None:
38
+ self.color = ImageColor.getrgb(color)
39
+ self.width = width
40
+
41
+
42
+ class Brush:
43
+ """Stores a fill color"""
44
+
45
+ def __init__(self, color: str, opacity: int = 255) -> None:
46
+ self.color = ImageColor.getrgb(color)
47
+
48
+
49
+ class Font:
50
+ """Stores a TrueType font and color"""
51
+
52
+ def __init__(
53
+ self, color: str, file: StrOrBytesPath | BinaryIO, size: float = 12
54
+ ) -> None:
55
+ # FIXME: add support for bitmap fonts
56
+ self.color = ImageColor.getrgb(color)
57
+ self.font = ImageFont.truetype(file, size)
58
+
59
+
60
+ class Draw:
61
+ """
62
+ (Experimental) WCK-style drawing interface
63
+ """
64
+
65
+ def __init__(
66
+ self,
67
+ image: Image.Image | str,
68
+ size: tuple[int, int] | list[int] | None = None,
69
+ color: float | tuple[float, ...] | str | None = None,
70
+ ) -> None:
71
+ if isinstance(image, str):
72
+ if size is None:
73
+ msg = "If image argument is mode string, size must be a list or tuple"
74
+ raise ValueError(msg)
75
+ image = Image.new(image, size, color)
76
+ self.draw = ImageDraw.Draw(image)
77
+ self.image = image
78
+ self.transform: tuple[float, float, float, float, float, float] | None = None
79
+
80
+ def flush(self) -> Image.Image:
81
+ return self.image
82
+
83
+ def render(
84
+ self,
85
+ op: str,
86
+ xy: Coords,
87
+ pen: Pen | Brush | None,
88
+ brush: Brush | Pen | None = None,
89
+ **kwargs: Any,
90
+ ) -> None:
91
+ # handle color arguments
92
+ outline = fill = None
93
+ width = 1
94
+ if isinstance(pen, Pen):
95
+ outline = pen.color
96
+ width = pen.width
97
+ elif isinstance(brush, Pen):
98
+ outline = brush.color
99
+ width = brush.width
100
+ if isinstance(brush, Brush):
101
+ fill = brush.color
102
+ elif isinstance(pen, Brush):
103
+ fill = pen.color
104
+ # handle transformation
105
+ if self.transform:
106
+ path = ImagePath.Path(xy)
107
+ path.transform(self.transform)
108
+ xy = path
109
+ # render the item
110
+ if op in ("arc", "line"):
111
+ kwargs.setdefault("fill", outline)
112
+ else:
113
+ kwargs.setdefault("fill", fill)
114
+ kwargs.setdefault("outline", outline)
115
+ if op == "line":
116
+ kwargs.setdefault("width", width)
117
+ getattr(self.draw, op)(xy, **kwargs)
118
+
119
+ def settransform(self, offset: tuple[float, float]) -> None:
120
+ """Sets a transformation offset."""
121
+ xoffset, yoffset = offset
122
+ self.transform = (1, 0, xoffset, 0, 1, yoffset)
123
+
124
+ def arc(
125
+ self,
126
+ xy: Coords,
127
+ pen: Pen | Brush | None,
128
+ start: float,
129
+ end: float,
130
+ *options: Any,
131
+ ) -> None:
132
+ """
133
+ Draws an arc (a portion of a circle outline) between the start and end
134
+ angles, inside the given bounding box.
135
+
136
+ .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.arc`
137
+ """
138
+ self.render("arc", xy, pen, *options, start=start, end=end)
139
+
140
+ def chord(
141
+ self,
142
+ xy: Coords,
143
+ pen: Pen | Brush | None,
144
+ start: float,
145
+ end: float,
146
+ *options: Any,
147
+ ) -> None:
148
+ """
149
+ Same as :py:meth:`~PIL.ImageDraw2.Draw.arc`, but connects the end points
150
+ with a straight line.
151
+
152
+ .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.chord`
153
+ """
154
+ self.render("chord", xy, pen, *options, start=start, end=end)
155
+
156
+ def ellipse(self, xy: Coords, pen: Pen | Brush | None, *options: Any) -> None:
157
+ """
158
+ Draws an ellipse inside the given bounding box.
159
+
160
+ .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.ellipse`
161
+ """
162
+ self.render("ellipse", xy, pen, *options)
163
+
164
+ def line(self, xy: Coords, pen: Pen | Brush | None, *options: Any) -> None:
165
+ """
166
+ Draws a line between the coordinates in the ``xy`` list.
167
+
168
+ .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.line`
169
+ """
170
+ self.render("line", xy, pen, *options)
171
+
172
+ def pieslice(
173
+ self,
174
+ xy: Coords,
175
+ pen: Pen | Brush | None,
176
+ start: float,
177
+ end: float,
178
+ *options: Any,
179
+ ) -> None:
180
+ """
181
+ Same as arc, but also draws straight lines between the end points and the
182
+ center of the bounding box.
183
+
184
+ .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.pieslice`
185
+ """
186
+ self.render("pieslice", xy, pen, *options, start=start, end=end)
187
+
188
+ def polygon(self, xy: Coords, pen: Pen | Brush | None, *options: Any) -> None:
189
+ """
190
+ Draws a polygon.
191
+
192
+ The polygon outline consists of straight lines between the given
193
+ coordinates, plus a straight line between the last and the first
194
+ coordinate.
195
+
196
+
197
+ .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.polygon`
198
+ """
199
+ self.render("polygon", xy, pen, *options)
200
+
201
+ def rectangle(self, xy: Coords, pen: Pen | Brush | None, *options: Any) -> None:
202
+ """
203
+ Draws a rectangle.
204
+
205
+ .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.rectangle`
206
+ """
207
+ self.render("rectangle", xy, pen, *options)
208
+
209
+ def text(self, xy: tuple[float, float], text: AnyStr, font: Font) -> None:
210
+ """
211
+ Draws the string at the given position.
212
+
213
+ .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.text`
214
+ """
215
+ if self.transform:
216
+ path = ImagePath.Path(xy)
217
+ path.transform(self.transform)
218
+ xy = path
219
+ self.draw.text(xy, text, font=font.font, fill=font.color)
220
+
221
+ def textbbox(
222
+ self, xy: tuple[float, float], text: AnyStr, font: Font
223
+ ) -> tuple[float, float, float, float]:
224
+ """
225
+ Returns bounding box (in pixels) of given text.
226
+
227
+ :return: ``(left, top, right, bottom)`` bounding box
228
+
229
+ .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.textbbox`
230
+ """
231
+ if self.transform:
232
+ path = ImagePath.Path(xy)
233
+ path.transform(self.transform)
234
+ xy = path
235
+ return self.draw.textbbox(xy, text, font=font.font)
236
+
237
+ def textlength(self, text: AnyStr, font: Font) -> float:
238
+ """
239
+ Returns length (in pixels) of given text.
240
+ This is the amount by which following text should be offset.
241
+
242
+ .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.textlength`
243
+ """
244
+ return self.draw.textlength(text, font=font.font)
.venv/Lib/site-packages/PIL/ImageEnhance.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ image: Image.Image
27
+ degenerate: Image.Image
28
+
29
+ def enhance(self, factor: float) -> Image.Image:
30
+ """
31
+ Returns an enhanced image.
32
+
33
+ :param factor: A floating point value controlling the enhancement.
34
+ Factor 1.0 always returns a copy of the original image,
35
+ lower factors mean less color (brightness, contrast,
36
+ etc), and higher values more. There are no restrictions
37
+ on this value.
38
+ :rtype: :py:class:`~PIL.Image.Image`
39
+ """
40
+ return Image.blend(self.degenerate, self.image, factor)
41
+
42
+
43
+ class Color(_Enhance):
44
+ """Adjust image color balance.
45
+
46
+ This class can be used to adjust the colour balance of an image, in
47
+ a manner similar to the controls on a colour TV set. An enhancement
48
+ factor of 0.0 gives a black and white image. A factor of 1.0 gives
49
+ the original image.
50
+ """
51
+
52
+ def __init__(self, image: Image.Image) -> None:
53
+ self.image = image
54
+ self.intermediate_mode = "L"
55
+ if "A" in image.getbands():
56
+ self.intermediate_mode = "LA"
57
+
58
+ if self.intermediate_mode != image.mode:
59
+ image = image.convert(self.intermediate_mode).convert(image.mode)
60
+ self.degenerate = image
61
+
62
+
63
+ class Contrast(_Enhance):
64
+ """Adjust image contrast.
65
+
66
+ This class can be used to control the contrast of an image, similar
67
+ to the contrast control on a TV set. An enhancement factor of 0.0
68
+ gives a solid gray image. A factor of 1.0 gives the original image.
69
+ """
70
+
71
+ def __init__(self, image: Image.Image) -> None:
72
+ self.image = image
73
+ if image.mode != "L":
74
+ image = image.convert("L")
75
+ mean = int(ImageStat.Stat(image).mean[0] + 0.5)
76
+ self.degenerate = Image.new("L", image.size, mean)
77
+ if self.degenerate.mode != self.image.mode:
78
+ self.degenerate = self.degenerate.convert(self.image.mode)
79
+
80
+ if "A" in self.image.getbands():
81
+ self.degenerate.putalpha(self.image.getchannel("A"))
82
+
83
+
84
+ class Brightness(_Enhance):
85
+ """Adjust image brightness.
86
+
87
+ This class can be used to control the brightness of an image. An
88
+ enhancement factor of 0.0 gives a black image. A factor of 1.0 gives the
89
+ original image.
90
+ """
91
+
92
+ def __init__(self, image: Image.Image) -> None:
93
+ self.image = image
94
+ self.degenerate = Image.new(image.mode, image.size, 0)
95
+
96
+ if "A" in image.getbands():
97
+ self.degenerate.putalpha(image.getchannel("A"))
98
+
99
+
100
+ class Sharpness(_Enhance):
101
+ """Adjust image sharpness.
102
+
103
+ This class can be used to adjust the sharpness of an image. An
104
+ enhancement factor of 0.0 gives a blurred image, a factor of 1.0 gives the
105
+ original image, and a factor of 2.0 gives a sharpened image.
106
+ """
107
+
108
+ def __init__(self, image: Image.Image) -> None:
109
+ self.image = image
110
+ self.degenerate = image.filter(ImageFilter.SMOOTH)
111
+
112
+ if "A" in image.getbands():
113
+ self.degenerate.putalpha(image.getchannel("A"))
.venv/Lib/site-packages/PIL/ImageFile.py ADDED
@@ -0,0 +1,935 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 abc
32
+ import io
33
+ import itertools
34
+ import logging
35
+ import os
36
+ import struct
37
+ from typing import IO, Any, NamedTuple, cast
38
+
39
+ from . import ExifTags, Image
40
+ from ._util import DeferredError, is_path
41
+
42
+ TYPE_CHECKING = False
43
+ if TYPE_CHECKING:
44
+ from ._typing import StrOrBytesPath
45
+
46
+ logger = logging.getLogger(__name__)
47
+
48
+ MAXBLOCK = 65536
49
+ """
50
+ By default, Pillow processes image data in blocks. This helps to prevent excessive use
51
+ of resources. Codecs may disable this behaviour with ``_pulls_fd`` or ``_pushes_fd``.
52
+
53
+ When reading an image, this is the number of bytes to read at once.
54
+
55
+ When writing an image, this is the number of bytes to write at once.
56
+ If the image width times 4 is greater, then that will be used instead.
57
+ Plugins may also set a greater number.
58
+
59
+ User code may set this to another number.
60
+ """
61
+
62
+ SAFEBLOCK = 1024 * 1024
63
+
64
+ LOAD_TRUNCATED_IMAGES = False
65
+ """Whether or not to load truncated image files. User code may change this."""
66
+
67
+ ERRORS = {
68
+ -1: "image buffer overrun error",
69
+ -2: "decoding error",
70
+ -3: "unknown error",
71
+ -8: "bad configuration",
72
+ -9: "out of memory error",
73
+ }
74
+ """
75
+ Dict of known error codes returned from :meth:`.PyDecoder.decode`,
76
+ :meth:`.PyEncoder.encode` :meth:`.PyEncoder.encode_to_pyfd` and
77
+ :meth:`.PyEncoder.encode_to_file`.
78
+ """
79
+
80
+
81
+ #
82
+ # --------------------------------------------------------------------
83
+ # Helpers
84
+
85
+
86
+ def _get_oserror(error: int, *, encoder: bool) -> OSError:
87
+ try:
88
+ msg = Image.core.getcodecstatus(error)
89
+ except AttributeError:
90
+ msg = ERRORS.get(error)
91
+ if not msg:
92
+ msg = f"{'encoder' if encoder else 'decoder'} error {error}"
93
+ msg += f" when {'writing' if encoder else 'reading'} image file"
94
+ return OSError(msg)
95
+
96
+
97
+ def _tilesort(t: _Tile) -> int:
98
+ # sort on offset
99
+ return t[2]
100
+
101
+
102
+ class _Tile(NamedTuple):
103
+ codec_name: str
104
+ extents: tuple[int, int, int, int] | None
105
+ offset: int = 0
106
+ args: tuple[Any, ...] | str | None = None
107
+
108
+
109
+ #
110
+ # --------------------------------------------------------------------
111
+ # ImageFile base class
112
+
113
+
114
+ class ImageFile(Image.Image):
115
+ """Base class for image file format handlers."""
116
+
117
+ def __init__(
118
+ self, fp: StrOrBytesPath | IO[bytes], filename: str | bytes | None = None
119
+ ) -> None:
120
+ super().__init__()
121
+
122
+ self._min_frame = 0
123
+
124
+ self.custom_mimetype: str | None = None
125
+
126
+ self.tile: list[_Tile] = []
127
+ """ A list of tile descriptors """
128
+
129
+ self.readonly = 1 # until we know better
130
+
131
+ self.decoderconfig: tuple[Any, ...] = ()
132
+ self.decodermaxblock = MAXBLOCK
133
+
134
+ self.fp: IO[bytes] | None
135
+ self._fp: IO[bytes] | DeferredError
136
+ if is_path(fp):
137
+ # filename
138
+ self.fp = open(fp, "rb")
139
+ self.filename = os.fspath(fp)
140
+ self._exclusive_fp = True
141
+ else:
142
+ # stream
143
+ self.fp = cast(IO[bytes], fp)
144
+ self.filename = filename if filename is not None else ""
145
+ # can be overridden
146
+ self._exclusive_fp = False
147
+
148
+ try:
149
+ try:
150
+ self._open()
151
+
152
+ if isinstance(self, StubImageFile):
153
+ if loader := self._load():
154
+ loader.open(self)
155
+ except (
156
+ IndexError, # end of data
157
+ TypeError, # end of data (ord)
158
+ KeyError, # unsupported mode
159
+ EOFError, # got header but not the first frame
160
+ struct.error,
161
+ ) as v:
162
+ raise SyntaxError(v) from v
163
+
164
+ if not self.mode or self.size[0] <= 0 or self.size[1] <= 0:
165
+ msg = "not identified by this driver"
166
+ raise SyntaxError(msg)
167
+ except BaseException:
168
+ # close the file only if we have opened it this constructor
169
+ if self._exclusive_fp:
170
+ self.fp.close()
171
+ raise
172
+
173
+ def _open(self) -> None:
174
+ pass
175
+
176
+ # Context manager support
177
+ def __enter__(self) -> ImageFile:
178
+ return self
179
+
180
+ def _close_fp(self) -> None:
181
+ if getattr(self, "_fp", False) and not isinstance(self._fp, DeferredError):
182
+ if self._fp != self.fp:
183
+ self._fp.close()
184
+ self._fp = DeferredError(ValueError("Operation on closed image"))
185
+ if self.fp:
186
+ self.fp.close()
187
+
188
+ def __exit__(self, *args: object) -> None:
189
+ if getattr(self, "_exclusive_fp", False):
190
+ self._close_fp()
191
+ self.fp = None
192
+
193
+ def close(self) -> None:
194
+ """
195
+ Closes the file pointer, if possible.
196
+
197
+ This operation will destroy the image core and release its memory.
198
+ The image data will be unusable afterward.
199
+
200
+ This function is required to close images that have multiple frames or
201
+ have not had their file read and closed by the
202
+ :py:meth:`~PIL.Image.Image.load` method. See :ref:`file-handling` for
203
+ more information.
204
+ """
205
+ try:
206
+ self._close_fp()
207
+ self.fp = None
208
+ except Exception as msg:
209
+ logger.debug("Error closing: %s", msg)
210
+
211
+ super().close()
212
+
213
+ def get_child_images(self) -> list[ImageFile]:
214
+ child_images = []
215
+ exif = self.getexif()
216
+ ifds = []
217
+ if ExifTags.Base.SubIFDs in exif:
218
+ subifd_offsets = exif[ExifTags.Base.SubIFDs]
219
+ if subifd_offsets:
220
+ if not isinstance(subifd_offsets, tuple):
221
+ subifd_offsets = (subifd_offsets,)
222
+ ifds = [
223
+ (exif._get_ifd_dict(subifd_offset), subifd_offset)
224
+ for subifd_offset in subifd_offsets
225
+ ]
226
+ ifd1 = exif.get_ifd(ExifTags.IFD.IFD1)
227
+ if ifd1 and ifd1.get(ExifTags.Base.JpegIFOffset):
228
+ assert exif._info is not None
229
+ ifds.append((ifd1, exif._info.next))
230
+
231
+ offset = None
232
+ for ifd, ifd_offset in ifds:
233
+ assert self.fp is not None
234
+ current_offset = self.fp.tell()
235
+ if offset is None:
236
+ offset = current_offset
237
+
238
+ fp = self.fp
239
+ if ifd is not None:
240
+ thumbnail_offset = ifd.get(ExifTags.Base.JpegIFOffset)
241
+ if thumbnail_offset is not None:
242
+ thumbnail_offset += getattr(self, "_exif_offset", 0)
243
+ self.fp.seek(thumbnail_offset)
244
+
245
+ length = ifd.get(ExifTags.Base.JpegIFByteCount)
246
+ assert isinstance(length, int)
247
+ data = self.fp.read(length)
248
+ fp = io.BytesIO(data)
249
+
250
+ with Image.open(fp) as im:
251
+ from . import TiffImagePlugin
252
+
253
+ if thumbnail_offset is None and isinstance(
254
+ im, TiffImagePlugin.TiffImageFile
255
+ ):
256
+ im._frame_pos = [ifd_offset]
257
+ im._seek(0)
258
+ im.load()
259
+ child_images.append(im)
260
+
261
+ if offset is not None:
262
+ assert self.fp is not None
263
+ self.fp.seek(offset)
264
+ return child_images
265
+
266
+ def get_format_mimetype(self) -> str | None:
267
+ if self.custom_mimetype:
268
+ return self.custom_mimetype
269
+ if self.format is not None:
270
+ return Image.MIME.get(self.format.upper())
271
+ return None
272
+
273
+ def __getstate__(self) -> list[Any]:
274
+ return super().__getstate__() + [self.filename]
275
+
276
+ def __setstate__(self, state: list[Any]) -> None:
277
+ self.tile = []
278
+ if len(state) > 5:
279
+ self.filename = state[5]
280
+ super().__setstate__(state)
281
+
282
+ def verify(self) -> None:
283
+ """Check file integrity"""
284
+
285
+ # raise exception if something's wrong. must be called
286
+ # directly after open, and closes file when finished.
287
+ if self._exclusive_fp and self.fp:
288
+ self.fp.close()
289
+ self.fp = None
290
+
291
+ def load(self) -> Image.core.PixelAccess | None:
292
+ """Load image data based on tile list"""
293
+
294
+ if not self.tile and self._im is None:
295
+ msg = "cannot load this image"
296
+ raise OSError(msg)
297
+
298
+ pixel = Image.Image.load(self)
299
+ if not self.tile:
300
+ return pixel
301
+
302
+ self.map: mmap.mmap | None = None
303
+ use_mmap = self.filename and len(self.tile) == 1
304
+
305
+ assert self.fp is not None
306
+ readonly = 0
307
+
308
+ # look for read/seek overrides
309
+ if hasattr(self, "load_read"):
310
+ read = self.load_read
311
+ # don't use mmap if there are custom read/seek functions
312
+ use_mmap = False
313
+ else:
314
+ read = self.fp.read
315
+
316
+ if hasattr(self, "load_seek"):
317
+ seek = self.load_seek
318
+ use_mmap = False
319
+ else:
320
+ seek = self.fp.seek
321
+
322
+ if use_mmap:
323
+ # try memory mapping
324
+ decoder_name, extents, offset, args = self.tile[0]
325
+ if isinstance(args, str):
326
+ args = (args, 0, 1)
327
+ if (
328
+ decoder_name == "raw"
329
+ and isinstance(args, tuple)
330
+ and len(args) >= 3
331
+ and args[0] == self.mode
332
+ and args[0] in Image._MAPMODES
333
+ ):
334
+ if offset < 0:
335
+ msg = "Tile offset cannot be negative"
336
+ raise ValueError(msg)
337
+ try:
338
+ # use mmap, if possible
339
+ import mmap
340
+
341
+ with open(self.filename) as fp:
342
+ self.map = mmap.mmap(fp.fileno(), 0, access=mmap.ACCESS_READ)
343
+ if offset + self.size[1] * args[1] > self.map.size():
344
+ msg = "buffer is not large enough"
345
+ raise OSError(msg)
346
+ self.im = Image.core.map_buffer(
347
+ self.map, self.size, decoder_name, offset, args
348
+ )
349
+ readonly = 1
350
+ # After trashing self.im,
351
+ # we might need to reload the palette data.
352
+ if self.palette:
353
+ self.palette.dirty = 1
354
+ except (AttributeError, OSError, ImportError):
355
+ self.map = None
356
+
357
+ self.load_prepare()
358
+ err_code = -3 # initialize to unknown error
359
+ if not self.map:
360
+ # sort tiles in file order
361
+ self.tile.sort(key=_tilesort)
362
+
363
+ # FIXME: This is a hack to handle TIFF's JpegTables tag.
364
+ prefix = getattr(self, "tile_prefix", b"")
365
+
366
+ # Remove consecutive duplicates that only differ by their offset
367
+ self.tile = [
368
+ list(tiles)[-1]
369
+ for _, tiles in itertools.groupby(
370
+ self.tile, lambda tile: (tile[0], tile[1], tile[3])
371
+ )
372
+ ]
373
+ for i, (decoder_name, extents, offset, args) in enumerate(self.tile):
374
+ seek(offset)
375
+ decoder = Image._getdecoder(
376
+ self.mode, decoder_name, args, self.decoderconfig
377
+ )
378
+ try:
379
+ decoder.setimage(self.im, extents)
380
+ if decoder.pulls_fd:
381
+ decoder.setfd(self.fp)
382
+ err_code = decoder.decode(b"")[1]
383
+ else:
384
+ b = prefix
385
+ while True:
386
+ read_bytes = self.decodermaxblock
387
+ if i + 1 < len(self.tile):
388
+ next_offset = self.tile[i + 1].offset
389
+ if next_offset > offset:
390
+ read_bytes = next_offset - offset
391
+ try:
392
+ s = read(read_bytes)
393
+ except (IndexError, struct.error) as e:
394
+ # truncated png/gif
395
+ if LOAD_TRUNCATED_IMAGES:
396
+ break
397
+ else:
398
+ msg = "image file is truncated"
399
+ raise OSError(msg) from e
400
+
401
+ if not s: # truncated jpeg
402
+ if LOAD_TRUNCATED_IMAGES:
403
+ break
404
+ else:
405
+ msg = (
406
+ "image file is truncated "
407
+ f"({len(b)} bytes not processed)"
408
+ )
409
+ raise OSError(msg)
410
+
411
+ b = b + s
412
+ n, err_code = decoder.decode(b)
413
+ if n < 0:
414
+ break
415
+ b = b[n:]
416
+ finally:
417
+ # Need to cleanup here to prevent leaks
418
+ decoder.cleanup()
419
+
420
+ self.tile = []
421
+ self.readonly = readonly
422
+
423
+ self.load_end()
424
+
425
+ if self._exclusive_fp and self._close_exclusive_fp_after_loading:
426
+ self.fp.close()
427
+ self.fp = None
428
+
429
+ if not self.map and not LOAD_TRUNCATED_IMAGES and err_code < 0:
430
+ # still raised if decoder fails to return anything
431
+ raise _get_oserror(err_code, encoder=False)
432
+
433
+ return Image.Image.load(self)
434
+
435
+ def load_prepare(self) -> None:
436
+ # create image memory if necessary
437
+ if self._im is None:
438
+ self.im = Image.core.new(self.mode, self.size)
439
+ # create palette (optional)
440
+ if self.mode == "P":
441
+ Image.Image.load(self)
442
+
443
+ def load_end(self) -> None:
444
+ # may be overridden
445
+ pass
446
+
447
+ # may be defined for contained formats
448
+ # def load_seek(self, pos: int) -> None:
449
+ # pass
450
+
451
+ # may be defined for blocked formats (e.g. PNG)
452
+ # def load_read(self, read_bytes: int) -> bytes:
453
+ # pass
454
+
455
+ def _seek_check(self, frame: int) -> bool:
456
+ if (
457
+ frame < self._min_frame
458
+ # Only check upper limit on frames if additional seek operations
459
+ # are not required to do so
460
+ or (
461
+ not (hasattr(self, "_n_frames") and self._n_frames is None)
462
+ and frame >= getattr(self, "n_frames") + self._min_frame
463
+ )
464
+ ):
465
+ msg = "attempt to seek outside sequence"
466
+ raise EOFError(msg)
467
+
468
+ return self.tell() != frame
469
+
470
+
471
+ class StubHandler(abc.ABC):
472
+ def open(self, im: StubImageFile) -> None:
473
+ pass
474
+
475
+ @abc.abstractmethod
476
+ def load(self, im: StubImageFile) -> Image.Image:
477
+ pass
478
+
479
+
480
+ class StubImageFile(ImageFile, metaclass=abc.ABCMeta):
481
+ """
482
+ Base class for stub image loaders.
483
+
484
+ A stub loader is an image loader that can identify files of a
485
+ certain format, but relies on external code to load the file.
486
+ """
487
+
488
+ @abc.abstractmethod
489
+ def _open(self) -> None:
490
+ pass
491
+
492
+ def load(self) -> Image.core.PixelAccess | None:
493
+ loader = self._load()
494
+ if loader is None:
495
+ msg = f"cannot find loader for this {self.format} file"
496
+ raise OSError(msg)
497
+ image = loader.load(self)
498
+ assert image is not None
499
+ # become the other object (!)
500
+ self.__class__ = image.__class__ # type: ignore[assignment]
501
+ self.__dict__ = image.__dict__
502
+ return image.load()
503
+
504
+ @abc.abstractmethod
505
+ def _load(self) -> StubHandler | None:
506
+ """(Hook) Find actual image loader."""
507
+ pass
508
+
509
+
510
+ class Parser:
511
+ """
512
+ Incremental image parser. This class implements the standard
513
+ feed/close consumer interface.
514
+ """
515
+
516
+ incremental = None
517
+ image: Image.Image | None = None
518
+ data: bytes | None = None
519
+ decoder: Image.core.ImagingDecoder | PyDecoder | None = None
520
+ offset = 0
521
+ finished = 0
522
+
523
+ def reset(self) -> None:
524
+ """
525
+ (Consumer) Reset the parser. Note that you can only call this
526
+ method immediately after you've created a parser; parser
527
+ instances cannot be reused.
528
+ """
529
+ assert self.data is None, "cannot reuse parsers"
530
+
531
+ def feed(self, data: bytes) -> None:
532
+ """
533
+ (Consumer) Feed data to the parser.
534
+
535
+ :param data: A string buffer.
536
+ :exception OSError: If the parser failed to parse the image file.
537
+ """
538
+ # collect data
539
+
540
+ if self.finished:
541
+ return
542
+
543
+ if self.data is None:
544
+ self.data = data
545
+ else:
546
+ self.data = self.data + data
547
+
548
+ # parse what we have
549
+ if self.decoder:
550
+ if self.offset > 0:
551
+ # skip header
552
+ skip = min(len(self.data), self.offset)
553
+ self.data = self.data[skip:]
554
+ self.offset = self.offset - skip
555
+ if self.offset > 0 or not self.data:
556
+ return
557
+
558
+ n, e = self.decoder.decode(self.data)
559
+
560
+ if n < 0:
561
+ # end of stream
562
+ self.data = None
563
+ self.finished = 1
564
+ if e < 0:
565
+ # decoding error
566
+ self.image = None
567
+ raise _get_oserror(e, encoder=False)
568
+ else:
569
+ # end of image
570
+ return
571
+ self.data = self.data[n:]
572
+
573
+ elif self.image:
574
+ # if we end up here with no decoder, this file cannot
575
+ # be incrementally parsed. wait until we've gotten all
576
+ # available data
577
+ pass
578
+
579
+ else:
580
+ # attempt to open this file
581
+ try:
582
+ with io.BytesIO(self.data) as fp:
583
+ im = Image.open(fp)
584
+ except OSError:
585
+ pass # not enough data
586
+ else:
587
+ flag = hasattr(im, "load_seek") or hasattr(im, "load_read")
588
+ if not flag and len(im.tile) == 1:
589
+ # initialize decoder
590
+ im.load_prepare()
591
+ d, e, o, a = im.tile[0]
592
+ im.tile = []
593
+ self.decoder = Image._getdecoder(im.mode, d, a, im.decoderconfig)
594
+ self.decoder.setimage(im.im, e)
595
+
596
+ # calculate decoder offset
597
+ self.offset = o
598
+ if self.offset <= len(self.data):
599
+ self.data = self.data[self.offset :]
600
+ self.offset = 0
601
+
602
+ self.image = im
603
+
604
+ def __enter__(self) -> Parser:
605
+ return self
606
+
607
+ def __exit__(self, *args: object) -> None:
608
+ self.close()
609
+
610
+ def close(self) -> Image.Image:
611
+ """
612
+ (Consumer) Close the stream.
613
+
614
+ :returns: An image object.
615
+ :exception OSError: If the parser failed to parse the image file either
616
+ because it cannot be identified or cannot be
617
+ decoded.
618
+ """
619
+ # finish decoding
620
+ if self.decoder:
621
+ # get rid of what's left in the buffers
622
+ self.feed(b"")
623
+ self.data = self.decoder = None
624
+ if not self.finished:
625
+ msg = "image was incomplete"
626
+ raise OSError(msg)
627
+ if not self.image:
628
+ msg = "cannot parse this image"
629
+ raise OSError(msg)
630
+ if self.data:
631
+ # incremental parsing not possible; reopen the file
632
+ # not that we have all data
633
+ with io.BytesIO(self.data) as fp:
634
+ try:
635
+ self.image = Image.open(fp)
636
+ finally:
637
+ self.image.load()
638
+ return self.image
639
+
640
+
641
+ # --------------------------------------------------------------------
642
+
643
+
644
+ def _save(im: Image.Image, fp: IO[bytes], tile: list[_Tile], bufsize: int = 0) -> None:
645
+ """Helper to save image based on tile list
646
+
647
+ :param im: Image object.
648
+ :param fp: File object.
649
+ :param tile: Tile list.
650
+ :param bufsize: Optional buffer size
651
+ """
652
+
653
+ im.load()
654
+ if not hasattr(im, "encoderconfig"):
655
+ im.encoderconfig = ()
656
+ tile.sort(key=_tilesort)
657
+ # FIXME: make MAXBLOCK a configuration parameter
658
+ # It would be great if we could have the encoder specify what it needs
659
+ # But, it would need at least the image size in most cases. RawEncode is
660
+ # a tricky case.
661
+ bufsize = max(MAXBLOCK, bufsize, im.size[0] * 4) # see RawEncode.c
662
+ try:
663
+ fh = fp.fileno()
664
+ fp.flush()
665
+ _encode_tile(im, fp, tile, bufsize, fh)
666
+ except (AttributeError, io.UnsupportedOperation) as exc:
667
+ _encode_tile(im, fp, tile, bufsize, None, exc)
668
+ if hasattr(fp, "flush"):
669
+ fp.flush()
670
+
671
+
672
+ def _encode_tile(
673
+ im: Image.Image,
674
+ fp: IO[bytes],
675
+ tile: list[_Tile],
676
+ bufsize: int,
677
+ fh: int | None,
678
+ exc: BaseException | None = None,
679
+ ) -> None:
680
+ for encoder_name, extents, offset, args in tile:
681
+ if offset > 0:
682
+ fp.seek(offset)
683
+ encoder = Image._getencoder(im.mode, encoder_name, args, im.encoderconfig)
684
+ try:
685
+ encoder.setimage(im.im, extents)
686
+ if encoder.pushes_fd:
687
+ encoder.setfd(fp)
688
+ errcode = encoder.encode_to_pyfd()[1]
689
+ else:
690
+ if exc:
691
+ # compress to Python file-compatible object
692
+ while True:
693
+ errcode, data = encoder.encode(bufsize)[1:]
694
+ fp.write(data)
695
+ if errcode:
696
+ break
697
+ else:
698
+ # slight speedup: compress to real file object
699
+ assert fh is not None
700
+ errcode = encoder.encode_to_file(fh, bufsize)
701
+ if errcode < 0:
702
+ raise _get_oserror(errcode, encoder=True) from exc
703
+ finally:
704
+ encoder.cleanup()
705
+
706
+
707
+ def _safe_read(fp: IO[bytes], size: int) -> bytes:
708
+ """
709
+ Reads large blocks in a safe way. Unlike fp.read(n), this function
710
+ doesn't trust the user. If the requested size is larger than
711
+ SAFEBLOCK, the file is read block by block.
712
+
713
+ :param fp: File handle. Must implement a <b>read</b> method.
714
+ :param size: Number of bytes to read.
715
+ :returns: A string containing <i>size</i> bytes of data.
716
+
717
+ Raises an OSError if the file is truncated and the read cannot be completed
718
+
719
+ """
720
+ if size <= 0:
721
+ return b""
722
+ if size <= SAFEBLOCK:
723
+ data = fp.read(size)
724
+ if len(data) < size:
725
+ msg = "Truncated File Read"
726
+ raise OSError(msg)
727
+ return data
728
+ blocks: list[bytes] = []
729
+ remaining_size = size
730
+ while remaining_size > 0:
731
+ block = fp.read(min(remaining_size, SAFEBLOCK))
732
+ if not block:
733
+ break
734
+ blocks.append(block)
735
+ remaining_size -= len(block)
736
+ if sum(len(block) for block in blocks) < size:
737
+ msg = "Truncated File Read"
738
+ raise OSError(msg)
739
+ return b"".join(blocks)
740
+
741
+
742
+ class PyCodecState:
743
+ def __init__(self) -> None:
744
+ self.xsize = 0
745
+ self.ysize = 0
746
+ self.xoff = 0
747
+ self.yoff = 0
748
+
749
+ def extents(self) -> tuple[int, int, int, int]:
750
+ return self.xoff, self.yoff, self.xoff + self.xsize, self.yoff + self.ysize
751
+
752
+
753
+ class PyCodec:
754
+ fd: IO[bytes] | None
755
+
756
+ def __init__(self, mode: str, *args: Any) -> None:
757
+ self.im: Image.core.ImagingCore | None = None
758
+ self.state = PyCodecState()
759
+ self.fd = None
760
+ self.mode = mode
761
+ self.init(args)
762
+
763
+ def init(self, args: tuple[Any, ...]) -> None:
764
+ """
765
+ Override to perform codec specific initialization
766
+
767
+ :param args: Tuple of arg items from the tile entry
768
+ :returns: None
769
+ """
770
+ self.args = args
771
+
772
+ def cleanup(self) -> None:
773
+ """
774
+ Override to perform codec specific cleanup
775
+
776
+ :returns: None
777
+ """
778
+ pass
779
+
780
+ def setfd(self, fd: IO[bytes]) -> None:
781
+ """
782
+ Called from ImageFile to set the Python file-like object
783
+
784
+ :param fd: A Python file-like object
785
+ :returns: None
786
+ """
787
+ self.fd = fd
788
+
789
+ def setimage(
790
+ self,
791
+ im: Image.core.ImagingCore,
792
+ extents: tuple[int, int, int, int] | None = None,
793
+ ) -> None:
794
+ """
795
+ Called from ImageFile to set the core output image for the codec
796
+
797
+ :param im: A core image object
798
+ :param extents: a 4 tuple of (x0, y0, x1, y1) defining the rectangle
799
+ for this tile
800
+ :returns: None
801
+ """
802
+
803
+ # following c code
804
+ self.im = im
805
+
806
+ if extents:
807
+ x0, y0, x1, y1 = extents
808
+
809
+ if x0 < 0 or y0 < 0 or x1 > self.im.size[0] or y1 > self.im.size[1]:
810
+ msg = "Tile cannot extend outside image"
811
+ raise ValueError(msg)
812
+
813
+ self.state.xoff = x0
814
+ self.state.yoff = y0
815
+ self.state.xsize = x1 - x0
816
+ self.state.ysize = y1 - y0
817
+ else:
818
+ self.state.xsize, self.state.ysize = self.im.size
819
+
820
+ if self.state.xsize <= 0 or self.state.ysize <= 0:
821
+ msg = "Size must be positive"
822
+ raise ValueError(msg)
823
+
824
+
825
+ class PyDecoder(PyCodec):
826
+ """
827
+ Python implementation of a format decoder. Override this class and
828
+ add the decoding logic in the :meth:`decode` method.
829
+
830
+ See :ref:`Writing Your Own File Codec in Python<file-codecs-py>`
831
+ """
832
+
833
+ _pulls_fd = False
834
+
835
+ @property
836
+ def pulls_fd(self) -> bool:
837
+ return self._pulls_fd
838
+
839
+ def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:
840
+ """
841
+ Override to perform the decoding process.
842
+
843
+ :param buffer: A bytes object with the data to be decoded.
844
+ :returns: A tuple of ``(bytes consumed, errcode)``.
845
+ If finished with decoding return -1 for the bytes consumed.
846
+ Err codes are from :data:`.ImageFile.ERRORS`.
847
+ """
848
+ msg = "unavailable in base decoder"
849
+ raise NotImplementedError(msg)
850
+
851
+ def set_as_raw(
852
+ self, data: bytes, rawmode: str | None = None, extra: tuple[Any, ...] = ()
853
+ ) -> None:
854
+ """
855
+ Convenience method to set the internal image from a stream of raw data
856
+
857
+ :param data: Bytes to be set
858
+ :param rawmode: The rawmode to be used for the decoder.
859
+ If not specified, it will default to the mode of the image
860
+ :param extra: Extra arguments for the decoder.
861
+ :returns: None
862
+ """
863
+
864
+ if not rawmode:
865
+ rawmode = self.mode
866
+ d = Image._getdecoder(self.mode, "raw", rawmode, extra)
867
+ assert self.im is not None
868
+ d.setimage(self.im, self.state.extents())
869
+ s = d.decode(data)
870
+
871
+ if s[0] >= 0:
872
+ msg = "not enough image data"
873
+ raise ValueError(msg)
874
+ if s[1] != 0:
875
+ msg = "cannot decode image data"
876
+ raise ValueError(msg)
877
+
878
+
879
+ class PyEncoder(PyCodec):
880
+ """
881
+ Python implementation of a format encoder. Override this class and
882
+ add the decoding logic in the :meth:`encode` method.
883
+
884
+ See :ref:`Writing Your Own File Codec in Python<file-codecs-py>`
885
+ """
886
+
887
+ _pushes_fd = False
888
+
889
+ @property
890
+ def pushes_fd(self) -> bool:
891
+ return self._pushes_fd
892
+
893
+ def encode(self, bufsize: int) -> tuple[int, int, bytes]:
894
+ """
895
+ Override to perform the encoding process.
896
+
897
+ :param bufsize: Buffer size.
898
+ :returns: A tuple of ``(bytes encoded, errcode, bytes)``.
899
+ If finished with encoding return 1 for the error code.
900
+ Err codes are from :data:`.ImageFile.ERRORS`.
901
+ """
902
+ msg = "unavailable in base encoder"
903
+ raise NotImplementedError(msg)
904
+
905
+ def encode_to_pyfd(self) -> tuple[int, int]:
906
+ """
907
+ If ``pushes_fd`` is ``True``, then this method will be used,
908
+ and ``encode()`` will only be called once.
909
+
910
+ :returns: A tuple of ``(bytes consumed, errcode)``.
911
+ Err codes are from :data:`.ImageFile.ERRORS`.
912
+ """
913
+ if not self.pushes_fd:
914
+ return 0, -8 # bad configuration
915
+ bytes_consumed, errcode, data = self.encode(0)
916
+ if data:
917
+ assert self.fd is not None
918
+ self.fd.write(data)
919
+ return bytes_consumed, errcode
920
+
921
+ def encode_to_file(self, fh: int, bufsize: int) -> int:
922
+ """
923
+ :param fh: File handle.
924
+ :param bufsize: Buffer size.
925
+
926
+ :returns: If finished successfully, return 0.
927
+ Otherwise, return an error code. Err codes are from
928
+ :data:`.ImageFile.ERRORS`.
929
+ """
930
+ errcode = 0
931
+ while errcode == 0:
932
+ status, errcode, buf = self.encode(bufsize)
933
+ if status > 0:
934
+ os.write(fh, buf[status:])
935
+ return errcode
.venv/Lib/site-packages/PIL/ImageFilter.py ADDED
@@ -0,0 +1,607 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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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 abc
20
+ import functools
21
+ from collections.abc import Sequence
22
+ from typing import cast
23
+
24
+ TYPE_CHECKING = False
25
+ if TYPE_CHECKING:
26
+ from collections.abc import Callable
27
+ from types import ModuleType
28
+ from typing import Any
29
+
30
+ from . import _imaging
31
+ from ._typing import NumpyArray
32
+
33
+
34
+ class Filter(abc.ABC):
35
+ @abc.abstractmethod
36
+ def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
37
+ pass
38
+
39
+
40
+ class MultibandFilter(Filter):
41
+ pass
42
+
43
+
44
+ class BuiltinFilter(MultibandFilter):
45
+ filterargs: tuple[Any, ...]
46
+
47
+ def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
48
+ if image.mode == "P":
49
+ msg = "cannot filter palette images"
50
+ raise ValueError(msg)
51
+ return image.filter(*self.filterargs)
52
+
53
+
54
+ class Kernel(BuiltinFilter):
55
+ """
56
+ Create a convolution kernel. This only supports 3x3 and 5x5 integer and floating
57
+ point kernels.
58
+
59
+ Kernels can only be applied to "L" and "RGB" images.
60
+
61
+ :param size: Kernel size, given as (width, height). This must be (3,3) or (5,5).
62
+ :param kernel: A sequence containing kernel weights. The kernel will be flipped
63
+ vertically before being applied to the image.
64
+ :param scale: Scale factor. If given, the result for each pixel is divided by this
65
+ value. The default is the sum of the kernel weights.
66
+ :param offset: Offset. If given, this value is added to the result, after it has
67
+ been divided by the scale factor.
68
+ """
69
+
70
+ name = "Kernel"
71
+
72
+ def __init__(
73
+ self,
74
+ size: tuple[int, int],
75
+ kernel: Sequence[float],
76
+ scale: float | None = None,
77
+ offset: float = 0,
78
+ ) -> None:
79
+ if scale is None:
80
+ # default scale is sum of kernel
81
+ scale = functools.reduce(lambda a, b: a + b, kernel)
82
+ if size[0] * size[1] != len(kernel):
83
+ msg = "not enough coefficients in kernel"
84
+ raise ValueError(msg)
85
+ self.filterargs = size, scale, offset, kernel
86
+
87
+
88
+ class RankFilter(Filter):
89
+ """
90
+ Create a rank filter. The rank filter sorts all pixels in
91
+ a window of the given size, and returns the ``rank``'th value.
92
+
93
+ :param size: The kernel size, in pixels.
94
+ :param rank: What pixel value to pick. Use 0 for a min filter,
95
+ ``size * size / 2`` for a median filter, ``size * size - 1``
96
+ for a max filter, etc.
97
+ """
98
+
99
+ name = "Rank"
100
+
101
+ def __init__(self, size: int, rank: int) -> None:
102
+ self.size = size
103
+ self.rank = rank
104
+
105
+ def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
106
+ if image.mode == "P":
107
+ msg = "cannot filter palette images"
108
+ raise ValueError(msg)
109
+ image = image.expand(self.size // 2, self.size // 2)
110
+ return image.rankfilter(self.size, self.rank)
111
+
112
+
113
+ class MedianFilter(RankFilter):
114
+ """
115
+ Create a median filter. Picks the median pixel value in a window with the
116
+ given size.
117
+
118
+ :param size: The kernel size, in pixels.
119
+ """
120
+
121
+ name = "Median"
122
+
123
+ def __init__(self, size: int = 3) -> None:
124
+ self.size = size
125
+ self.rank = size * size // 2
126
+
127
+
128
+ class MinFilter(RankFilter):
129
+ """
130
+ Create a min filter. Picks the lowest pixel value in a window with the
131
+ given size.
132
+
133
+ :param size: The kernel size, in pixels.
134
+ """
135
+
136
+ name = "Min"
137
+
138
+ def __init__(self, size: int = 3) -> None:
139
+ self.size = size
140
+ self.rank = 0
141
+
142
+
143
+ class MaxFilter(RankFilter):
144
+ """
145
+ Create a max filter. Picks the largest pixel value in a window with the
146
+ given size.
147
+
148
+ :param size: The kernel size, in pixels.
149
+ """
150
+
151
+ name = "Max"
152
+
153
+ def __init__(self, size: int = 3) -> None:
154
+ self.size = size
155
+ self.rank = size * size - 1
156
+
157
+
158
+ class ModeFilter(Filter):
159
+ """
160
+ Create a mode filter. Picks the most frequent pixel value in a box with the
161
+ given size. Pixel values that occur only once or twice are ignored; if no
162
+ pixel value occurs more than twice, the original pixel value is preserved.
163
+
164
+ :param size: The kernel size, in pixels.
165
+ """
166
+
167
+ name = "Mode"
168
+
169
+ def __init__(self, size: int = 3) -> None:
170
+ self.size = size
171
+
172
+ def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
173
+ return image.modefilter(self.size)
174
+
175
+
176
+ class GaussianBlur(MultibandFilter):
177
+ """Blurs the image with a sequence of extended box filters, which
178
+ approximates a Gaussian kernel. For details on accuracy see
179
+ <https://www.mia.uni-saarland.de/Publications/gwosdek-ssvm11.pdf>
180
+
181
+ :param radius: Standard deviation of the Gaussian kernel. Either a sequence of two
182
+ numbers for x and y, or a single number for both.
183
+ """
184
+
185
+ name = "GaussianBlur"
186
+
187
+ def __init__(self, radius: float | Sequence[float] = 2) -> None:
188
+ self.radius = radius
189
+
190
+ def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
191
+ xy = self.radius
192
+ if isinstance(xy, (int, float)):
193
+ xy = (xy, xy)
194
+ if xy == (0, 0):
195
+ return image.copy()
196
+ return image.gaussian_blur(xy)
197
+
198
+
199
+ class BoxBlur(MultibandFilter):
200
+ """Blurs the image by setting each pixel to the average value of the pixels
201
+ in a square box extending radius pixels in each direction.
202
+ Supports float radius of arbitrary size. Uses an optimized implementation
203
+ which runs in linear time relative to the size of the image
204
+ for any radius value.
205
+
206
+ :param radius: Size of the box in a direction. Either a sequence of two numbers for
207
+ x and y, or a single number for both.
208
+
209
+ Radius 0 does not blur, returns an identical image.
210
+ Radius 1 takes 1 pixel in each direction, i.e. 9 pixels in total.
211
+ """
212
+
213
+ name = "BoxBlur"
214
+
215
+ def __init__(self, radius: float | Sequence[float]) -> None:
216
+ xy = radius if isinstance(radius, (tuple, list)) else (radius, radius)
217
+ if xy[0] < 0 or xy[1] < 0:
218
+ msg = "radius must be >= 0"
219
+ raise ValueError(msg)
220
+ self.radius = radius
221
+
222
+ def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
223
+ xy = self.radius
224
+ if isinstance(xy, (int, float)):
225
+ xy = (xy, xy)
226
+ if xy == (0, 0):
227
+ return image.copy()
228
+ return image.box_blur(xy)
229
+
230
+
231
+ class UnsharpMask(MultibandFilter):
232
+ """Unsharp mask filter.
233
+
234
+ See Wikipedia's entry on `digital unsharp masking`_ for an explanation of
235
+ the parameters.
236
+
237
+ :param radius: Blur Radius
238
+ :param percent: Unsharp strength, in percent
239
+ :param threshold: Threshold controls the minimum brightness change that
240
+ will be sharpened
241
+
242
+ .. _digital unsharp masking: https://en.wikipedia.org/wiki/Unsharp_masking#Digital_unsharp_masking
243
+
244
+ """
245
+
246
+ name = "UnsharpMask"
247
+
248
+ def __init__(
249
+ self, radius: float = 2, percent: int = 150, threshold: int = 3
250
+ ) -> None:
251
+ self.radius = radius
252
+ self.percent = percent
253
+ self.threshold = threshold
254
+
255
+ def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
256
+ return image.unsharp_mask(self.radius, self.percent, self.threshold)
257
+
258
+
259
+ class BLUR(BuiltinFilter):
260
+ name = "Blur"
261
+ # fmt: off
262
+ filterargs = (5, 5), 16, 0, (
263
+ 1, 1, 1, 1, 1,
264
+ 1, 0, 0, 0, 1,
265
+ 1, 0, 0, 0, 1,
266
+ 1, 0, 0, 0, 1,
267
+ 1, 1, 1, 1, 1,
268
+ )
269
+ # fmt: on
270
+
271
+
272
+ class CONTOUR(BuiltinFilter):
273
+ name = "Contour"
274
+ # fmt: off
275
+ filterargs = (3, 3), 1, 255, (
276
+ -1, -1, -1,
277
+ -1, 8, -1,
278
+ -1, -1, -1,
279
+ )
280
+ # fmt: on
281
+
282
+
283
+ class DETAIL(BuiltinFilter):
284
+ name = "Detail"
285
+ # fmt: off
286
+ filterargs = (3, 3), 6, 0, (
287
+ 0, -1, 0,
288
+ -1, 10, -1,
289
+ 0, -1, 0,
290
+ )
291
+ # fmt: on
292
+
293
+
294
+ class EDGE_ENHANCE(BuiltinFilter):
295
+ name = "Edge-enhance"
296
+ # fmt: off
297
+ filterargs = (3, 3), 2, 0, (
298
+ -1, -1, -1,
299
+ -1, 10, -1,
300
+ -1, -1, -1,
301
+ )
302
+ # fmt: on
303
+
304
+
305
+ class EDGE_ENHANCE_MORE(BuiltinFilter):
306
+ name = "Edge-enhance More"
307
+ # fmt: off
308
+ filterargs = (3, 3), 1, 0, (
309
+ -1, -1, -1,
310
+ -1, 9, -1,
311
+ -1, -1, -1,
312
+ )
313
+ # fmt: on
314
+
315
+
316
+ class EMBOSS(BuiltinFilter):
317
+ name = "Emboss"
318
+ # fmt: off
319
+ filterargs = (3, 3), 1, 128, (
320
+ -1, 0, 0,
321
+ 0, 1, 0,
322
+ 0, 0, 0,
323
+ )
324
+ # fmt: on
325
+
326
+
327
+ class FIND_EDGES(BuiltinFilter):
328
+ name = "Find Edges"
329
+ # fmt: off
330
+ filterargs = (3, 3), 1, 0, (
331
+ -1, -1, -1,
332
+ -1, 8, -1,
333
+ -1, -1, -1,
334
+ )
335
+ # fmt: on
336
+
337
+
338
+ class SHARPEN(BuiltinFilter):
339
+ name = "Sharpen"
340
+ # fmt: off
341
+ filterargs = (3, 3), 16, 0, (
342
+ -2, -2, -2,
343
+ -2, 32, -2,
344
+ -2, -2, -2,
345
+ )
346
+ # fmt: on
347
+
348
+
349
+ class SMOOTH(BuiltinFilter):
350
+ name = "Smooth"
351
+ # fmt: off
352
+ filterargs = (3, 3), 13, 0, (
353
+ 1, 1, 1,
354
+ 1, 5, 1,
355
+ 1, 1, 1,
356
+ )
357
+ # fmt: on
358
+
359
+
360
+ class SMOOTH_MORE(BuiltinFilter):
361
+ name = "Smooth More"
362
+ # fmt: off
363
+ filterargs = (5, 5), 100, 0, (
364
+ 1, 1, 1, 1, 1,
365
+ 1, 5, 5, 5, 1,
366
+ 1, 5, 44, 5, 1,
367
+ 1, 5, 5, 5, 1,
368
+ 1, 1, 1, 1, 1,
369
+ )
370
+ # fmt: on
371
+
372
+
373
+ class Color3DLUT(MultibandFilter):
374
+ """Three-dimensional color lookup table.
375
+
376
+ Transforms 3-channel pixels using the values of the channels as coordinates
377
+ in the 3D lookup table and interpolating the nearest elements.
378
+
379
+ This method allows you to apply almost any color transformation
380
+ in constant time by using pre-calculated decimated tables.
381
+
382
+ .. versionadded:: 5.2.0
383
+
384
+ :param size: Size of the table. One int or tuple of (int, int, int).
385
+ Minimal size in any dimension is 2, maximum is 65.
386
+ :param table: Flat lookup table. A list of ``channels * size**3``
387
+ float elements or a list of ``size**3`` channels-sized
388
+ tuples with floats. Channels are changed first,
389
+ then first dimension, then second, then third.
390
+ Value 0.0 corresponds lowest value of output, 1.0 highest.
391
+ :param channels: Number of channels in the table. Could be 3 or 4.
392
+ Default is 3.
393
+ :param target_mode: A mode for the result image. Should have not less
394
+ than ``channels`` channels. Default is ``None``,
395
+ which means that mode wouldn't be changed.
396
+ """
397
+
398
+ name = "Color 3D LUT"
399
+
400
+ def __init__(
401
+ self,
402
+ size: int | tuple[int, int, int],
403
+ table: Sequence[float] | Sequence[Sequence[int]] | NumpyArray,
404
+ channels: int = 3,
405
+ target_mode: str | None = None,
406
+ **kwargs: bool,
407
+ ) -> None:
408
+ if channels not in (3, 4):
409
+ msg = "Only 3 or 4 output channels are supported"
410
+ raise ValueError(msg)
411
+ self.size = size = self._check_size(size)
412
+ self.channels = channels
413
+ self.mode = target_mode
414
+
415
+ # Hidden flag `_copy_table=False` could be used to avoid extra copying
416
+ # of the table if the table is specially made for the constructor.
417
+ copy_table = kwargs.get("_copy_table", True)
418
+ items = size[0] * size[1] * size[2]
419
+ wrong_size = False
420
+
421
+ numpy: ModuleType | None = None
422
+ if hasattr(table, "shape"):
423
+ try:
424
+ import numpy
425
+ except ImportError:
426
+ pass
427
+
428
+ if numpy and isinstance(table, numpy.ndarray):
429
+ numpy_table: NumpyArray = table
430
+ if copy_table:
431
+ numpy_table = numpy_table.copy()
432
+
433
+ if numpy_table.shape in [
434
+ (items * channels,),
435
+ (items, channels),
436
+ (size[2], size[1], size[0], channels),
437
+ ]:
438
+ table = numpy_table.reshape(items * channels)
439
+ else:
440
+ wrong_size = True
441
+
442
+ else:
443
+ if copy_table:
444
+ table = list(table)
445
+
446
+ # Convert to a flat list
447
+ if table and isinstance(table[0], (list, tuple)):
448
+ raw_table = cast(Sequence[Sequence[int]], table)
449
+ flat_table: list[int] = []
450
+ for pixel in raw_table:
451
+ if len(pixel) != channels:
452
+ msg = (
453
+ "The elements of the table should "
454
+ f"have a length of {channels}."
455
+ )
456
+ raise ValueError(msg)
457
+ flat_table.extend(pixel)
458
+ table = flat_table
459
+
460
+ if wrong_size or len(table) != items * channels:
461
+ msg = (
462
+ "The table should have either channels * size**3 float items "
463
+ "or size**3 items of channels-sized tuples with floats. "
464
+ f"Table should be: {channels}x{size[0]}x{size[1]}x{size[2]}. "
465
+ f"Actual length: {len(table)}"
466
+ )
467
+ raise ValueError(msg)
468
+ self.table = table
469
+
470
+ @staticmethod
471
+ def _check_size(size: Any) -> tuple[int, int, int]:
472
+ try:
473
+ _, _, _ = size
474
+ except ValueError as e:
475
+ msg = "Size should be either an integer or a tuple of three integers."
476
+ raise ValueError(msg) from e
477
+ except TypeError:
478
+ size = (size, size, size)
479
+ size = tuple(int(x) for x in size)
480
+ for size_1d in size:
481
+ if not 2 <= size_1d <= 65:
482
+ msg = "Size should be in [2, 65] range."
483
+ raise ValueError(msg)
484
+ return size
485
+
486
+ @classmethod
487
+ def generate(
488
+ cls,
489
+ size: int | tuple[int, int, int],
490
+ callback: Callable[[float, float, float], tuple[float, ...]],
491
+ channels: int = 3,
492
+ target_mode: str | None = None,
493
+ ) -> Color3DLUT:
494
+ """Generates new LUT using provided callback.
495
+
496
+ :param size: Size of the table. Passed to the constructor.
497
+ :param callback: Function with three parameters which correspond
498
+ three color channels. Will be called ``size**3``
499
+ times with values from 0.0 to 1.0 and should return
500
+ a tuple with ``channels`` elements.
501
+ :param channels: The number of channels which should return callback.
502
+ :param target_mode: Passed to the constructor of the resulting
503
+ lookup table.
504
+ """
505
+ size_1d, size_2d, size_3d = cls._check_size(size)
506
+ if channels not in (3, 4):
507
+ msg = "Only 3 or 4 output channels are supported"
508
+ raise ValueError(msg)
509
+
510
+ table: list[float] = [0] * (size_1d * size_2d * size_3d * channels)
511
+ idx_out = 0
512
+ for b in range(size_3d):
513
+ for g in range(size_2d):
514
+ for r in range(size_1d):
515
+ table[idx_out : idx_out + channels] = callback(
516
+ r / (size_1d - 1), g / (size_2d - 1), b / (size_3d - 1)
517
+ )
518
+ idx_out += channels
519
+
520
+ return cls(
521
+ (size_1d, size_2d, size_3d),
522
+ table,
523
+ channels=channels,
524
+ target_mode=target_mode,
525
+ _copy_table=False,
526
+ )
527
+
528
+ def transform(
529
+ self,
530
+ callback: Callable[..., tuple[float, ...]],
531
+ with_normals: bool = False,
532
+ channels: int | None = None,
533
+ target_mode: str | None = None,
534
+ ) -> Color3DLUT:
535
+ """Transforms the table values using provided callback and returns
536
+ a new LUT with altered values.
537
+
538
+ :param callback: A function which takes old lookup table values
539
+ and returns a new set of values. The number
540
+ of arguments which function should take is
541
+ ``self.channels`` or ``3 + self.channels``
542
+ if ``with_normals`` flag is set.
543
+ Should return a tuple of ``self.channels`` or
544
+ ``channels`` elements if it is set.
545
+ :param with_normals: If true, ``callback`` will be called with
546
+ coordinates in the color cube as the first
547
+ three arguments. Otherwise, ``callback``
548
+ will be called only with actual color values.
549
+ :param channels: The number of channels in the resulting lookup table.
550
+ :param target_mode: Passed to the constructor of the resulting
551
+ lookup table.
552
+ """
553
+ if channels not in (None, 3, 4):
554
+ msg = "Only 3 or 4 output channels are supported"
555
+ raise ValueError(msg)
556
+ ch_in = self.channels
557
+ ch_out = channels or ch_in
558
+ size_1d, size_2d, size_3d = self.size
559
+
560
+ table: list[float] = [0] * (size_1d * size_2d * size_3d * ch_out)
561
+ idx_in = 0
562
+ idx_out = 0
563
+ for b in range(size_3d):
564
+ for g in range(size_2d):
565
+ for r in range(size_1d):
566
+ values = self.table[idx_in : idx_in + ch_in]
567
+ if with_normals:
568
+ values = callback(
569
+ r / (size_1d - 1),
570
+ g / (size_2d - 1),
571
+ b / (size_3d - 1),
572
+ *values,
573
+ )
574
+ else:
575
+ values = callback(*values)
576
+ table[idx_out : idx_out + ch_out] = values
577
+ idx_in += ch_in
578
+ idx_out += ch_out
579
+
580
+ return type(self)(
581
+ self.size,
582
+ table,
583
+ channels=ch_out,
584
+ target_mode=target_mode or self.mode,
585
+ _copy_table=False,
586
+ )
587
+
588
+ def __repr__(self) -> str:
589
+ r = [
590
+ f"{self.__class__.__name__} from {self.table.__class__.__name__}",
591
+ "size={:d}x{:d}x{:d}".format(*self.size),
592
+ f"channels={self.channels:d}",
593
+ ]
594
+ if self.mode:
595
+ r.append(f"target_mode={self.mode}")
596
+ return "<{}>".format(" ".join(r))
597
+
598
+ def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
599
+ from . import Image
600
+
601
+ return image.color_lut_3d(
602
+ self.mode or image.mode,
603
+ Image.Resampling.BILINEAR,
604
+ self.channels,
605
+ self.size,
606
+ self.table,
607
+ )
.venv/Lib/site-packages/PIL/ImageFont.py ADDED
@@ -0,0 +1,1309 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 types import ModuleType
37
+ from typing import IO, Any, BinaryIO, TypedDict, cast
38
+
39
+ from . import Image
40
+ from ._typing import StrOrBytesPath
41
+ from ._util import DeferredError, is_path
42
+
43
+ TYPE_CHECKING = False
44
+ if TYPE_CHECKING:
45
+ from . import ImageFile
46
+ from ._imaging import ImagingFont
47
+ from ._imagingft import Font
48
+
49
+
50
+ class Axis(TypedDict):
51
+ minimum: int | None
52
+ default: int | None
53
+ maximum: int | None
54
+ name: bytes | None
55
+
56
+
57
+ class Layout(IntEnum):
58
+ BASIC = 0
59
+ RAQM = 1
60
+
61
+
62
+ MAX_STRING_LENGTH = 1_000_000
63
+
64
+
65
+ core: ModuleType | DeferredError
66
+ try:
67
+ from . import _imagingft as core
68
+ except ImportError as ex:
69
+ core = DeferredError.new(ex)
70
+
71
+
72
+ def _string_length_check(text: str | bytes | bytearray) -> None:
73
+ if MAX_STRING_LENGTH is not None and len(text) > MAX_STRING_LENGTH:
74
+ msg = "too many characters in string"
75
+ raise ValueError(msg)
76
+
77
+
78
+ # FIXME: add support for pilfont2 format (see FontFile.py)
79
+
80
+ # --------------------------------------------------------------------
81
+ # Font metrics format:
82
+ # "PILfont" LF
83
+ # fontdescriptor LF
84
+ # (optional) key=value... LF
85
+ # "DATA" LF
86
+ # binary data: 256*10*2 bytes (dx, dy, dstbox, srcbox)
87
+ #
88
+ # To place a character, cut out srcbox and paste at dstbox,
89
+ # relative to the character position. Then move the character
90
+ # position according to dx, dy.
91
+ # --------------------------------------------------------------------
92
+
93
+
94
+ class ImageFont:
95
+ """PIL font wrapper"""
96
+
97
+ font: ImagingFont
98
+
99
+ def _load_pilfont(self, filename: str) -> None:
100
+ with open(filename, "rb") as fp:
101
+ image: ImageFile.ImageFile | None = None
102
+ root = os.path.splitext(filename)[0]
103
+
104
+ for ext in (".png", ".gif", ".pbm"):
105
+ if image:
106
+ image.close()
107
+ try:
108
+ fullname = root + ext
109
+ image = Image.open(fullname)
110
+ except Exception:
111
+ pass
112
+ else:
113
+ if image.mode in ("1", "L"):
114
+ break
115
+ else:
116
+ if image:
117
+ image.close()
118
+
119
+ msg = f"cannot find glyph data file {root}.{{gif|pbm|png}}"
120
+ raise OSError(msg)
121
+
122
+ self.file = fullname
123
+
124
+ self._load_pilfont_data(fp, image)
125
+ image.close()
126
+
127
+ def _load_pilfont_data(self, file: IO[bytes], image: Image.Image) -> None:
128
+ # check image
129
+ if image.mode not in ("1", "L"):
130
+ image.close()
131
+
132
+ msg = "invalid font image mode"
133
+ raise TypeError(msg)
134
+
135
+ # read PILfont header
136
+ if file.read(8) != b"PILfont\n":
137
+ image.close()
138
+
139
+ msg = "Not a PILfont file"
140
+ raise SyntaxError(msg)
141
+ file.readline()
142
+ self.info = [] # FIXME: should be a dictionary
143
+ while True:
144
+ s = file.readline()
145
+ if not s or s == b"DATA\n":
146
+ break
147
+ self.info.append(s)
148
+
149
+ # read PILfont metrics
150
+ data = file.read(256 * 20)
151
+
152
+ self._load(image, data)
153
+
154
+ def _load(self, image: Image.Image, data: bytes) -> None:
155
+ image.load()
156
+
157
+ self.font = Image.core.font(image.im, data)
158
+
159
+ def getmask(
160
+ self, text: str | bytes, mode: str = "", *args: Any, **kwargs: Any
161
+ ) -> Image.core.ImagingCore:
162
+ """
163
+ Create a bitmap for the text.
164
+
165
+ If the font uses antialiasing, the bitmap should have mode ``L`` and use a
166
+ maximum value of 255. Otherwise, it should have mode ``1``.
167
+
168
+ :param text: Text to render.
169
+ :param mode: Used by some graphics drivers to indicate what mode the
170
+ driver prefers; if empty, the renderer may return either
171
+ mode. Note that the mode is always a string, to simplify
172
+ C-level implementations.
173
+
174
+ .. versionadded:: 1.1.5
175
+
176
+ :return: An internal PIL storage memory instance as defined by the
177
+ :py:mod:`PIL.Image.core` interface module.
178
+ """
179
+ _string_length_check(text)
180
+ Image._decompression_bomb_check(self.font.getsize(text))
181
+ return self.font.getmask(text, mode)
182
+
183
+ def getbbox(
184
+ self, text: str | bytes | bytearray, *args: Any, **kwargs: Any
185
+ ) -> tuple[int, int, int, int]:
186
+ """
187
+ Returns bounding box (in pixels) of given text.
188
+
189
+ .. versionadded:: 9.2.0
190
+
191
+ :param text: Text to render.
192
+
193
+ :return: ``(left, top, right, bottom)`` bounding box
194
+ """
195
+ _string_length_check(text)
196
+ width, height = self.font.getsize(text)
197
+ return 0, 0, width, height
198
+
199
+ def getlength(
200
+ self, text: str | bytes | bytearray, *args: Any, **kwargs: Any
201
+ ) -> int:
202
+ """
203
+ Returns length (in pixels) of given text.
204
+ This is the amount by which following text should be offset.
205
+
206
+ .. versionadded:: 9.2.0
207
+ """
208
+ _string_length_check(text)
209
+ width, height = self.font.getsize(text)
210
+ return width
211
+
212
+
213
+ ##
214
+ # Wrapper for FreeType fonts. Application code should use the
215
+ # <b>truetype</b> factory function to create font objects.
216
+
217
+
218
+ class FreeTypeFont:
219
+ """FreeType font wrapper (requires _imagingft service)"""
220
+
221
+ font: Font
222
+ font_bytes: bytes
223
+
224
+ def __init__(
225
+ self,
226
+ font: StrOrBytesPath | BinaryIO,
227
+ size: float = 10,
228
+ index: int = 0,
229
+ encoding: str = "",
230
+ layout_engine: Layout | None = None,
231
+ ) -> None:
232
+ # FIXME: use service provider instead
233
+
234
+ if isinstance(core, DeferredError):
235
+ raise core.ex
236
+
237
+ if size <= 0:
238
+ msg = f"font size must be greater than 0, not {size}"
239
+ raise ValueError(msg)
240
+
241
+ self.path = font
242
+ self.size = size
243
+ self.index = index
244
+ self.encoding = encoding
245
+
246
+ if layout_engine not in (Layout.BASIC, Layout.RAQM):
247
+ layout_engine = Layout.BASIC
248
+ if core.HAVE_RAQM:
249
+ layout_engine = Layout.RAQM
250
+ elif layout_engine == Layout.RAQM and not core.HAVE_RAQM:
251
+ warnings.warn(
252
+ "Raqm layout was requested, but Raqm is not available. "
253
+ "Falling back to basic layout."
254
+ )
255
+ layout_engine = Layout.BASIC
256
+
257
+ self.layout_engine = layout_engine
258
+
259
+ def load_from_bytes(f: IO[bytes]) -> None:
260
+ self.font_bytes = f.read()
261
+ self.font = core.getfont(
262
+ "", size, index, encoding, self.font_bytes, layout_engine
263
+ )
264
+
265
+ if is_path(font):
266
+ font = os.fspath(font)
267
+ if sys.platform == "win32":
268
+ font_bytes_path = font if isinstance(font, bytes) else font.encode()
269
+ try:
270
+ font_bytes_path.decode("ascii")
271
+ except UnicodeDecodeError:
272
+ # FreeType cannot load fonts with non-ASCII characters on Windows
273
+ # So load it into memory first
274
+ with open(font, "rb") as f:
275
+ load_from_bytes(f)
276
+ return
277
+ self.font = core.getfont(
278
+ font, size, index, encoding, layout_engine=layout_engine
279
+ )
280
+ else:
281
+ load_from_bytes(cast(IO[bytes], font))
282
+
283
+ def __getstate__(self) -> list[Any]:
284
+ return [self.path, self.size, self.index, self.encoding, self.layout_engine]
285
+
286
+ def __setstate__(self, state: list[Any]) -> None:
287
+ path, size, index, encoding, layout_engine = state
288
+ FreeTypeFont.__init__(self, path, size, index, encoding, layout_engine)
289
+
290
+ def getname(self) -> tuple[str | None, str | None]:
291
+ """
292
+ :return: A tuple of the font family (e.g. Helvetica) and the font style
293
+ (e.g. Bold)
294
+ """
295
+ return self.font.family, self.font.style
296
+
297
+ def getmetrics(self) -> tuple[int, int]:
298
+ """
299
+ :return: A tuple of the font ascent (the distance from the baseline to
300
+ the highest outline point) and descent (the distance from the
301
+ baseline to the lowest outline point, a negative value)
302
+ """
303
+ return self.font.ascent, self.font.descent
304
+
305
+ def getlength(
306
+ self,
307
+ text: str | bytes,
308
+ mode: str = "",
309
+ direction: str | None = None,
310
+ features: list[str] | None = None,
311
+ language: str | None = None,
312
+ ) -> float:
313
+ """
314
+ Returns length (in pixels with 1/64 precision) of given text when rendered
315
+ in font with provided direction, features, and language.
316
+
317
+ This is the amount by which following text should be offset.
318
+ Text bounding box may extend past the length in some fonts,
319
+ e.g. when using italics or accents.
320
+
321
+ The result is returned as a float; it is a whole number if using basic layout.
322
+
323
+ Note that the sum of two lengths may not equal the length of a concatenated
324
+ string due to kerning. If you need to adjust for kerning, include the following
325
+ character and subtract its length.
326
+
327
+ For example, instead of ::
328
+
329
+ hello = font.getlength("Hello")
330
+ world = font.getlength("World")
331
+ hello_world = hello + world # not adjusted for kerning
332
+ assert hello_world == font.getlength("HelloWorld") # may fail
333
+
334
+ use ::
335
+
336
+ hello = font.getlength("HelloW") - font.getlength("W") # adjusted for kerning
337
+ world = font.getlength("World")
338
+ hello_world = hello + world # adjusted for kerning
339
+ assert hello_world == font.getlength("HelloWorld") # True
340
+
341
+ or disable kerning with (requires libraqm) ::
342
+
343
+ hello = draw.textlength("Hello", font, features=["-kern"])
344
+ world = draw.textlength("World", font, features=["-kern"])
345
+ hello_world = hello + world # kerning is disabled, no need to adjust
346
+ assert hello_world == draw.textlength("HelloWorld", font, features=["-kern"])
347
+
348
+ .. versionadded:: 8.0.0
349
+
350
+ :param text: Text to measure.
351
+ :param mode: Used by some graphics drivers to indicate what mode the
352
+ driver prefers; if empty, the renderer may return either
353
+ mode. Note that the mode is always a string, to simplify
354
+ C-level implementations.
355
+
356
+ :param direction: Direction of the text. It can be 'rtl' (right to
357
+ left), 'ltr' (left to right) or 'ttb' (top to bottom).
358
+ Requires libraqm.
359
+
360
+ :param features: A list of OpenType font features to be used during text
361
+ layout. This is usually used to turn on optional
362
+ font features that are not enabled by default,
363
+ for example 'dlig' or 'ss01', but can be also
364
+ used to turn off default font features for
365
+ example '-liga' to disable ligatures or '-kern'
366
+ to disable kerning. To get all supported
367
+ features, see
368
+ https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist
369
+ Requires libraqm.
370
+
371
+ :param language: Language of the text. Different languages may use
372
+ different glyph shapes or ligatures. This parameter tells
373
+ the font which language the text is in, and to apply the
374
+ correct substitutions as appropriate, if available.
375
+ It should be a `BCP 47 language code
376
+ <https://www.w3.org/International/articles/language-tags/>`_
377
+ Requires libraqm.
378
+
379
+ :return: Either width for horizontal text, or height for vertical text.
380
+ """
381
+ _string_length_check(text)
382
+ return self.font.getlength(text, mode, direction, features, language) / 64
383
+
384
+ def getbbox(
385
+ self,
386
+ text: str | bytes,
387
+ mode: str = "",
388
+ direction: str | None = None,
389
+ features: list[str] | None = None,
390
+ language: str | None = None,
391
+ stroke_width: float = 0,
392
+ anchor: str | None = None,
393
+ ) -> tuple[float, float, float, float]:
394
+ """
395
+ Returns bounding box (in pixels) of given text relative to given anchor
396
+ when rendered in font with provided direction, features, and language.
397
+
398
+ Use :py:meth:`getlength()` to get the offset of following text with
399
+ 1/64 pixel precision. The bounding box includes extra margins for
400
+ some fonts, e.g. italics or accents.
401
+
402
+ .. versionadded:: 8.0.0
403
+
404
+ :param text: Text to render.
405
+ :param mode: Used by some graphics drivers to indicate what mode the
406
+ driver prefers; if empty, the renderer may return either
407
+ mode. Note that the mode is always a string, to simplify
408
+ C-level implementations.
409
+
410
+ :param direction: Direction of the text. It can be 'rtl' (right to
411
+ left), 'ltr' (left to right) or 'ttb' (top to bottom).
412
+ Requires libraqm.
413
+
414
+ :param features: A list of OpenType font features to be used during text
415
+ layout. This is usually used to turn on optional
416
+ font features that are not enabled by default,
417
+ for example 'dlig' or 'ss01', but can be also
418
+ used to turn off default font features for
419
+ example '-liga' to disable ligatures or '-kern'
420
+ to disable kerning. To get all supported
421
+ features, see
422
+ https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist
423
+ Requires libraqm.
424
+
425
+ :param language: Language of the text. Different languages may use
426
+ different glyph shapes or ligatures. This parameter tells
427
+ the font which language the text is in, and to apply the
428
+ correct substitutions as appropriate, if available.
429
+ It should be a `BCP 47 language code
430
+ <https://www.w3.org/International/articles/language-tags/>`_
431
+ Requires libraqm.
432
+
433
+ :param stroke_width: The width of the text stroke.
434
+
435
+ :param anchor: The text anchor alignment. Determines the relative location of
436
+ the anchor to the text. The default alignment is top left,
437
+ specifically ``la`` for horizontal text and ``lt`` for
438
+ vertical text. See :ref:`text-anchors` for details.
439
+
440
+ :return: ``(left, top, right, bottom)`` bounding box
441
+ """
442
+ _string_length_check(text)
443
+ size, offset = self.font.getsize(
444
+ text, mode, direction, features, language, anchor
445
+ )
446
+ left, top = offset[0] - stroke_width, offset[1] - stroke_width
447
+ width, height = size[0] + 2 * stroke_width, size[1] + 2 * stroke_width
448
+ return left, top, left + width, top + height
449
+
450
+ def getmask(
451
+ self,
452
+ text: str | bytes,
453
+ mode: str = "",
454
+ direction: str | None = None,
455
+ features: list[str] | None = None,
456
+ language: str | None = None,
457
+ stroke_width: float = 0,
458
+ anchor: str | None = None,
459
+ ink: int = 0,
460
+ start: tuple[float, float] | None = None,
461
+ ) -> Image.core.ImagingCore:
462
+ """
463
+ Create a bitmap for the text.
464
+
465
+ If the font uses antialiasing, the bitmap should have mode ``L`` and use a
466
+ maximum value of 255. If the font has embedded color data, the bitmap
467
+ should have mode ``RGBA``. Otherwise, it should have mode ``1``.
468
+
469
+ :param text: Text to render.
470
+ :param mode: Used by some graphics drivers to indicate what mode the
471
+ driver prefers; if empty, the renderer may return either
472
+ mode. Note that the mode is always a string, to simplify
473
+ C-level implementations.
474
+
475
+ .. versionadded:: 1.1.5
476
+
477
+ :param direction: Direction of the text. It can be 'rtl' (right to
478
+ left), 'ltr' (left to right) or 'ttb' (top to bottom).
479
+ Requires libraqm.
480
+
481
+ .. versionadded:: 4.2.0
482
+
483
+ :param features: A list of OpenType font features to be used during text
484
+ layout. This is usually used to turn on optional
485
+ font features that are not enabled by default,
486
+ for example 'dlig' or 'ss01', but can be also
487
+ used to turn off default font features for
488
+ example '-liga' to disable ligatures or '-kern'
489
+ to disable kerning. To get all supported
490
+ features, see
491
+ https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist
492
+ Requires libraqm.
493
+
494
+ .. versionadded:: 4.2.0
495
+
496
+ :param language: Language of the text. Different languages may use
497
+ different glyph shapes or ligatures. This parameter tells
498
+ the font which language the text is in, and to apply the
499
+ correct substitutions as appropriate, if available.
500
+ It should be a `BCP 47 language code
501
+ <https://www.w3.org/International/articles/language-tags/>`_
502
+ Requires libraqm.
503
+
504
+ .. versionadded:: 6.0.0
505
+
506
+ :param stroke_width: The width of the text stroke.
507
+
508
+ .. versionadded:: 6.2.0
509
+
510
+ :param anchor: The text anchor alignment. Determines the relative location of
511
+ the anchor to the text. The default alignment is top left,
512
+ specifically ``la`` for horizontal text and ``lt`` for
513
+ vertical text. See :ref:`text-anchors` for details.
514
+
515
+ .. versionadded:: 8.0.0
516
+
517
+ :param ink: Foreground ink for rendering in RGBA mode.
518
+
519
+ .. versionadded:: 8.0.0
520
+
521
+ :param start: Tuple of horizontal and vertical offset, as text may render
522
+ differently when starting at fractional coordinates.
523
+
524
+ .. versionadded:: 9.4.0
525
+
526
+ :return: An internal PIL storage memory instance as defined by the
527
+ :py:mod:`PIL.Image.core` interface module.
528
+ """
529
+ return self.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
+ )[0]
540
+
541
+ def getmask2(
542
+ self,
543
+ text: str | bytes,
544
+ mode: str = "",
545
+ direction: str | None = None,
546
+ features: list[str] | None = None,
547
+ language: str | None = None,
548
+ stroke_width: float = 0,
549
+ anchor: str | None = None,
550
+ ink: int = 0,
551
+ start: tuple[float, float] | None = None,
552
+ *args: Any,
553
+ **kwargs: Any,
554
+ ) -> tuple[Image.core.ImagingCore, tuple[int, int]]:
555
+ """
556
+ Create a bitmap for the text.
557
+
558
+ If the font uses antialiasing, the bitmap should have mode ``L`` and use a
559
+ maximum value of 255. If the font has embedded color data, the bitmap
560
+ should have mode ``RGBA``. Otherwise, it should have mode ``1``.
561
+
562
+ :param text: Text to render.
563
+ :param mode: Used by some graphics drivers to indicate what mode the
564
+ driver prefers; if empty, the renderer may return either
565
+ mode. Note that the mode is always a string, to simplify
566
+ C-level implementations.
567
+
568
+ .. versionadded:: 1.1.5
569
+
570
+ :param direction: Direction of the text. It can be 'rtl' (right to
571
+ left), 'ltr' (left to right) or 'ttb' (top to bottom).
572
+ Requires libraqm.
573
+
574
+ .. versionadded:: 4.2.0
575
+
576
+ :param features: A list of OpenType font features to be used during text
577
+ layout. This is usually used to turn on optional
578
+ font features that are not enabled by default,
579
+ for example 'dlig' or 'ss01', but can be also
580
+ used to turn off default font features for
581
+ example '-liga' to disable ligatures or '-kern'
582
+ to disable kerning. To get all supported
583
+ features, see
584
+ https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist
585
+ Requires libraqm.
586
+
587
+ .. versionadded:: 4.2.0
588
+
589
+ :param language: Language of the text. Different languages may use
590
+ different glyph shapes or ligatures. This parameter tells
591
+ the font which language the text is in, and to apply the
592
+ correct substitutions as appropriate, if available.
593
+ It should be a `BCP 47 language code
594
+ <https://www.w3.org/International/articles/language-tags/>`_
595
+ Requires libraqm.
596
+
597
+ .. versionadded:: 6.0.0
598
+
599
+ :param stroke_width: The width of the text stroke.
600
+
601
+ .. versionadded:: 6.2.0
602
+
603
+ :param anchor: The text anchor alignment. Determines the relative location of
604
+ the anchor to the text. The default alignment is top left,
605
+ specifically ``la`` for horizontal text and ``lt`` for
606
+ vertical text. See :ref:`text-anchors` for details.
607
+
608
+ .. versionadded:: 8.0.0
609
+
610
+ :param ink: Foreground ink for rendering in RGBA mode.
611
+
612
+ .. versionadded:: 8.0.0
613
+
614
+ :param start: Tuple of horizontal and vertical offset, as text may render
615
+ differently when starting at fractional coordinates.
616
+
617
+ .. versionadded:: 9.4.0
618
+
619
+ :return: A tuple of an internal PIL storage memory instance as defined by the
620
+ :py:mod:`PIL.Image.core` interface module, and the text offset, the
621
+ gap between the starting coordinate and the first marking
622
+ """
623
+ _string_length_check(text)
624
+ if start is None:
625
+ start = (0, 0)
626
+
627
+ def fill(width: int, height: int) -> Image.core.ImagingCore:
628
+ size = (width, height)
629
+ Image._decompression_bomb_check(size)
630
+ return Image.core.fill("RGBA" if mode == "RGBA" else "L", size)
631
+
632
+ return self.font.render(
633
+ text,
634
+ fill,
635
+ mode,
636
+ direction,
637
+ features,
638
+ language,
639
+ stroke_width,
640
+ kwargs.get("stroke_filled", False),
641
+ anchor,
642
+ ink,
643
+ start,
644
+ )
645
+
646
+ def font_variant(
647
+ self,
648
+ font: StrOrBytesPath | BinaryIO | None = None,
649
+ size: float | None = None,
650
+ index: int | None = None,
651
+ encoding: str | None = None,
652
+ layout_engine: Layout | None = None,
653
+ ) -> FreeTypeFont:
654
+ """
655
+ Create a copy of this FreeTypeFont object,
656
+ using any specified arguments to override the settings.
657
+
658
+ Parameters are identical to the parameters used to initialize this
659
+ object.
660
+
661
+ :return: A FreeTypeFont object.
662
+ """
663
+ if font is None:
664
+ try:
665
+ font = BytesIO(self.font_bytes)
666
+ except AttributeError:
667
+ font = self.path
668
+ return FreeTypeFont(
669
+ font=font,
670
+ size=self.size if size is None else size,
671
+ index=self.index if index is None else index,
672
+ encoding=self.encoding if encoding is None else encoding,
673
+ layout_engine=layout_engine or self.layout_engine,
674
+ )
675
+
676
+ def get_variation_names(self) -> list[bytes]:
677
+ """
678
+ :returns: A list of the named styles in a variation font.
679
+ :exception OSError: If the font is not a variation font.
680
+ """
681
+ names = []
682
+ for name in self.font.getvarnames():
683
+ name = name.replace(b"\x00", b"")
684
+ if name not in names:
685
+ names.append(name)
686
+ return names
687
+
688
+ def set_variation_by_name(self, name: str | bytes) -> None:
689
+ """
690
+ :param name: The name of the style.
691
+ :exception OSError: If the font is not a variation font.
692
+ """
693
+ names = self.get_variation_names()
694
+ if not isinstance(name, bytes):
695
+ name = name.encode()
696
+ index = names.index(name) + 1
697
+
698
+ if index == getattr(self, "_last_variation_index", None):
699
+ # When the same name is set twice in a row,
700
+ # there is an 'unknown freetype error'
701
+ # https://savannah.nongnu.org/bugs/?56186
702
+ return
703
+ self._last_variation_index = index
704
+
705
+ self.font.setvarname(index)
706
+
707
+ def get_variation_axes(self) -> list[Axis]:
708
+ """
709
+ :returns: A list of the axes in a variation font.
710
+ :exception OSError: If the font is not a variation font.
711
+ """
712
+ axes = self.font.getvaraxes()
713
+ for axis in axes:
714
+ if axis["name"]:
715
+ axis["name"] = axis["name"].replace(b"\x00", b"")
716
+ return axes
717
+
718
+ def set_variation_by_axes(self, axes: list[float]) -> None:
719
+ """
720
+ :param axes: A list of values for each axis.
721
+ :exception OSError: If the font is not a variation font.
722
+ """
723
+ self.font.setvaraxes(axes)
724
+
725
+
726
+ class TransposedFont:
727
+ """Wrapper for writing rotated or mirrored text"""
728
+
729
+ def __init__(
730
+ self, font: ImageFont | FreeTypeFont, orientation: Image.Transpose | None = None
731
+ ):
732
+ """
733
+ Wrapper that creates a transposed font from any existing font
734
+ object.
735
+
736
+ :param font: A font object.
737
+ :param orientation: An optional orientation. If given, this should
738
+ be one of Image.Transpose.FLIP_LEFT_RIGHT, Image.Transpose.FLIP_TOP_BOTTOM,
739
+ Image.Transpose.ROTATE_90, Image.Transpose.ROTATE_180, or
740
+ Image.Transpose.ROTATE_270.
741
+ """
742
+ self.font = font
743
+ self.orientation = orientation # any 'transpose' argument, or None
744
+
745
+ def getmask(
746
+ self, text: str | bytes, mode: str = "", *args: Any, **kwargs: Any
747
+ ) -> Image.core.ImagingCore:
748
+ im = self.font.getmask(text, mode, *args, **kwargs)
749
+ if self.orientation is not None:
750
+ return im.transpose(self.orientation)
751
+ return im
752
+
753
+ def getbbox(
754
+ self, text: str | bytes, *args: Any, **kwargs: Any
755
+ ) -> tuple[int, int, float, float]:
756
+ # TransposedFont doesn't support getmask2, move top-left point to (0, 0)
757
+ # this has no effect on ImageFont and simulates anchor="lt" for FreeTypeFont
758
+ left, top, right, bottom = self.font.getbbox(text, *args, **kwargs)
759
+ width = right - left
760
+ height = bottom - top
761
+ if self.orientation in (Image.Transpose.ROTATE_90, Image.Transpose.ROTATE_270):
762
+ return 0, 0, height, width
763
+ return 0, 0, width, height
764
+
765
+ def getlength(self, text: str | bytes, *args: Any, **kwargs: Any) -> float:
766
+ if self.orientation in (Image.Transpose.ROTATE_90, Image.Transpose.ROTATE_270):
767
+ msg = "text length is undefined for text rotated by 90 or 270 degrees"
768
+ raise ValueError(msg)
769
+ return self.font.getlength(text, *args, **kwargs)
770
+
771
+
772
+ def load(filename: str) -> ImageFont:
773
+ """
774
+ Load a font file. This function loads a font object from the given
775
+ bitmap font file, and returns the corresponding font object. For loading TrueType
776
+ or OpenType fonts instead, see :py:func:`~PIL.ImageFont.truetype`.
777
+
778
+ :param filename: Name of font file.
779
+ :return: A font object.
780
+ :exception OSError: If the file could not be read.
781
+ """
782
+ f = ImageFont()
783
+ f._load_pilfont(filename)
784
+ return f
785
+
786
+
787
+ def truetype(
788
+ font: StrOrBytesPath | BinaryIO,
789
+ size: float = 10,
790
+ index: int = 0,
791
+ encoding: str = "",
792
+ layout_engine: Layout | None = None,
793
+ ) -> FreeTypeFont:
794
+ """
795
+ Load a TrueType or OpenType font from a file or file-like object,
796
+ and create a font object. This function loads a font object from the given
797
+ file or file-like object, and creates a font object for a font of the given
798
+ size. For loading bitmap fonts instead, see :py:func:`~PIL.ImageFont.load`
799
+ and :py:func:`~PIL.ImageFont.load_path`.
800
+
801
+ Pillow uses FreeType to open font files. On Windows, be aware that FreeType
802
+ will keep the file open as long as the FreeTypeFont object exists. Windows
803
+ limits the number of files that can be open in C at once to 512, so if many
804
+ fonts are opened simultaneously and that limit is approached, an
805
+ ``OSError`` may be thrown, reporting that FreeType "cannot open resource".
806
+ A workaround would be to copy the file(s) into memory, and open that instead.
807
+
808
+ This function requires the _imagingft service.
809
+
810
+ :param font: A filename or file-like object containing a TrueType font.
811
+ If the file is not found in this filename, the loader may also
812
+ search in other directories, such as:
813
+
814
+ * The :file:`fonts/` directory on Windows,
815
+ * :file:`/Library/Fonts/`, :file:`/System/Library/Fonts/`
816
+ and :file:`~/Library/Fonts/` on macOS.
817
+ * :file:`~/.local/share/fonts`, :file:`/usr/local/share/fonts`,
818
+ and :file:`/usr/share/fonts` on Linux; or those specified by
819
+ the ``XDG_DATA_HOME`` and ``XDG_DATA_DIRS`` environment variables
820
+ for user-installed and system-wide fonts, respectively.
821
+
822
+ :param size: The requested size, in pixels.
823
+ :param index: Which font face to load (default is first available face).
824
+ :param encoding: Which font encoding to use (default is Unicode). Possible
825
+ encodings include (see the FreeType documentation for more
826
+ information):
827
+
828
+ * "unic" (Unicode)
829
+ * "symb" (Microsoft Symbol)
830
+ * "ADOB" (Adobe Standard)
831
+ * "ADBE" (Adobe Expert)
832
+ * "ADBC" (Adobe Custom)
833
+ * "armn" (Apple Roman)
834
+ * "sjis" (Shift JIS)
835
+ * "gb " (PRC)
836
+ * "big5"
837
+ * "wans" (Extended Wansung)
838
+ * "joha" (Johab)
839
+ * "lat1" (Latin-1)
840
+
841
+ This specifies the character set to use. It does not alter the
842
+ encoding of any text provided in subsequent operations.
843
+ :param layout_engine: Which layout engine to use, if available:
844
+ :attr:`.ImageFont.Layout.BASIC` or :attr:`.ImageFont.Layout.RAQM`.
845
+ If it is available, Raqm layout will be used by default.
846
+ Otherwise, basic layout will be used.
847
+
848
+ Raqm layout is recommended for all non-English text. If Raqm layout
849
+ is not required, basic layout will have better performance.
850
+
851
+ You can check support for Raqm layout using
852
+ :py:func:`PIL.features.check_feature` with ``feature="raqm"``.
853
+
854
+ .. versionadded:: 4.2.0
855
+ :return: A font object.
856
+ :exception OSError: If the file could not be read.
857
+ :exception ValueError: If the font size is not greater than zero.
858
+ """
859
+
860
+ def freetype(font: StrOrBytesPath | BinaryIO) -> FreeTypeFont:
861
+ return FreeTypeFont(font, size, index, encoding, layout_engine)
862
+
863
+ try:
864
+ return freetype(font)
865
+ except OSError:
866
+ if not is_path(font):
867
+ raise
868
+ ttf_filename = os.path.basename(font)
869
+
870
+ dirs = []
871
+ if sys.platform == "win32":
872
+ # check the windows font repository
873
+ # NOTE: must use uppercase WINDIR, to work around bugs in
874
+ # 1.5.2's os.environ.get()
875
+ windir = os.environ.get("WINDIR")
876
+ if windir:
877
+ dirs.append(os.path.join(windir, "fonts"))
878
+ elif sys.platform in ("linux", "linux2"):
879
+ data_home = os.environ.get("XDG_DATA_HOME")
880
+ if not data_home:
881
+ # The freedesktop spec defines the following default directory for
882
+ # when XDG_DATA_HOME is unset or empty. This user-level directory
883
+ # takes precedence over system-level directories.
884
+ data_home = os.path.expanduser("~/.local/share")
885
+ xdg_dirs = [data_home]
886
+
887
+ data_dirs = os.environ.get("XDG_DATA_DIRS")
888
+ if not data_dirs:
889
+ # Similarly, defaults are defined for the system-level directories
890
+ data_dirs = "/usr/local/share:/usr/share"
891
+ xdg_dirs += data_dirs.split(":")
892
+
893
+ dirs += [os.path.join(xdg_dir, "fonts") for xdg_dir in xdg_dirs]
894
+ elif sys.platform == "darwin":
895
+ dirs += [
896
+ "/Library/Fonts",
897
+ "/System/Library/Fonts",
898
+ os.path.expanduser("~/Library/Fonts"),
899
+ ]
900
+
901
+ ext = os.path.splitext(ttf_filename)[1]
902
+ first_font_with_a_different_extension = None
903
+ for directory in dirs:
904
+ for walkroot, walkdir, walkfilenames in os.walk(directory):
905
+ for walkfilename in walkfilenames:
906
+ if ext and walkfilename == ttf_filename:
907
+ return freetype(os.path.join(walkroot, walkfilename))
908
+ elif not ext and os.path.splitext(walkfilename)[0] == ttf_filename:
909
+ fontpath = os.path.join(walkroot, walkfilename)
910
+ if os.path.splitext(fontpath)[1] == ".ttf":
911
+ return freetype(fontpath)
912
+ if not ext and first_font_with_a_different_extension is None:
913
+ first_font_with_a_different_extension = fontpath
914
+ if first_font_with_a_different_extension:
915
+ return freetype(first_font_with_a_different_extension)
916
+ raise
917
+
918
+
919
+ def load_path(filename: str | bytes) -> ImageFont:
920
+ """
921
+ Load font file. Same as :py:func:`~PIL.ImageFont.load`, but searches for a
922
+ bitmap font along the Python path.
923
+
924
+ :param filename: Name of font file.
925
+ :return: A font object.
926
+ :exception OSError: If the file could not be read.
927
+ """
928
+ if not isinstance(filename, str):
929
+ filename = filename.decode("utf-8")
930
+ for directory in sys.path:
931
+ try:
932
+ return load(os.path.join(directory, filename))
933
+ except OSError: # noqa: PERF203
934
+ pass
935
+ msg = f'cannot find font file "{filename}" in sys.path'
936
+ if os.path.exists(filename):
937
+ msg += f', did you mean ImageFont.load("{filename}") instead?'
938
+
939
+ raise OSError(msg)
940
+
941
+
942
+ def load_default_imagefont() -> ImageFont:
943
+ f = ImageFont()
944
+ f._load_pilfont_data(
945
+ # courB08
946
+ BytesIO(base64.b64decode(b"""
947
+ UElMZm9udAo7Ozs7OzsxMDsKREFUQQoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
948
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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AAAAAf/5AAQAAQAeAAAAIQAIAAYAAAAB//kABAAB
962
+ ACEAAAAkAAgABgAAAAD/+QAE//0AJAAAACgABAAGAAAAAP/6AAX//wAoAAAALQAFAAYAAAAB//8A
963
+ BAACAC0AAAAwAAMABgAAAAD//AAF//0AMAAAADUAAQAGAAAAAf//AAMAAAA1AAAANwABAAYAAAAB
964
+ //kABQABADcAAAA7AAgABgAAAAD/+QAFAAAAOwAAAEAABwAGAAAAAP/5AAYAAABAAAAARgAHAAYA
965
+ AAAA//kABQAAAEYAAABLAAcABgAAAAD/+QAFAAAASwAAAFAABwAGAAAAAP/5AAYAAABQAAAAVgAH
966
+ AAYAAAAA//kABQAAAFYAAABbAAcABgAAAAD/+QAFAAAAWwAAAGAABwAGAAAAAP/5AAUAAABgAAAA
967
+ ZQAHAAYAAAAA//kABQAAAGUAAABqAAcABgAAAAD/+QAFAAAAagAAAG8ABwAGAAAAAf/8AAMAAABv
968
+ AAAAcQAEAAYAAAAA//wAAwACAHEAAAB0AAYABgAAAAD/+gAE//8AdAAAAHgABQAGAAAAAP/7AAT/
969
+ /gB4AAAAfAADAAYAAAAB//oABf//AHwAAACAAAUABgAAAAD/+gAFAAAAgAAAAIUABgAGAAAAAP/5
970
+ AAYAAQCFAAAAiwAIAAYAAP////oABgAAAIsAAACSAAYABgAA////+gAFAAAAkgAAAJgABgAGAAAA
971
+ AP/6AAUAAACYAAAAnQAGAAYAAP////oABQAAAJ0AAACjAAYABgAA////+gAFAAAAowAAAKkABgAG
972
+ AAD////6AAUAAACpAAAArwAGAAYAAAAA//oABQAAAK8AAAC0AAYABgAA////+gAGAAAAtAAAALsA
973
+ BgAGAAAAAP/6AAQAAAC7AAAAvwAGAAYAAP////oABQAAAL8AAADFAAYABgAA////+gAGAAAAxQAA
974
+ AMwABgAGAAD////6AAUAAADMAAAA0gAGAAYAAP////oABQAAANIAAADYAAYABgAA////+gAGAAAA
975
+ 2AAAAN8ABgAGAAAAAP/6AAUAAADfAAAA5AAGAAYAAP////oABQAAAOQAAADqAAYABgAAAAD/+gAF
976
+ AAEA6gAAAO8ABwAGAAD////6AAYAAADvAAAA9gAGAAYAAAAA//oABQAAAPYAAAD7AAYABgAA////
977
+ +gAFAAAA+wAAAQEABgAGAAD////6AAYAAAEBAAABCAAGAAYAAP////oABgAAAQgAAAEPAAYABgAA
978
+ ////+gAGAAABDwAAARYABgAGAAAAAP/6AAYAAAEWAAABHAAGAAYAAP////oABgAAARwAAAEjAAYA
979
+ BgAAAAD/+gAFAAABIwAAASgABgAGAAAAAf/5AAQAAQEoAAABKwAIAAYAAAAA//kABAABASsAAAEv
980
+ AAgABgAAAAH/+QAEAAEBLwAAATIACAAGAAAAAP/5AAX//AEyAAABNwADAAYAAAAAAAEABgACATcA
981
+ AAE9AAEABgAAAAH/+QAE//wBPQAAAUAAAwAGAAAAAP/7AAYAAAFAAAABRgAFAAYAAP////kABQAA
982
+ AUYAAAFMAAcABgAAAAD/+wAFAAABTAAAAVEABQAGAAAAAP/5AAYAAAFRAAABVwAHAAYAAAAA//sA
983
+ BQAAAVcAAAFcAAUABgAAAAD/+QAFAAABXAAAAWEABwAGAAAAAP/7AAYAAgFhAAABZwAHAAYAAP//
984
+ //kABQAAAWcAAAFtAAcABgAAAAD/+QAGAAABbQAAAXMABwAGAAAAAP/5AAQAAgFzAAABdwAJAAYA
985
+ AP////kABgAAAXcAAAF+AAcABgAAAAD/+QAGAAABfgAAAYQABwAGAAD////7AAUAAAGEAAABigAF
986
+ AAYAAP////sABQAAAYoAAAGQAAUABgAAAAD/+wAFAAABkAAAAZUABQAGAAD////7AAUAAgGVAAAB
987
+ mwAHAAYAAAAA//sABgACAZsAAAGhAAcABgAAAAD/+wAGAAABoQAAAacABQAGAAAAAP/7AAYAAAGn
988
+ AAABrQAFAAYAAAAA//kABgAAAa0AAAGzAAcABgAA////+wAGAAABswAAAboABQAGAAD////7AAUA
989
+ AAG6AAABwAAFAAYAAP////sABgAAAcAAAAHHAAUABgAAAAD/+wAGAA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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
1003
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAAB
1004
+ //sAAwACAecAAAHpAAcABgAAAAD/+QAFAAEB6QAAAe4ACAAGAAAAAP/5AAYAAAHuAAAB9AAHAAYA
1005
+ AAAA//oABf//AfQAAAH5AAUABgAAAAD/+QAGAAAB+QAAAf8ABwAGAAAAAv/5AAMAAgH/AAACAAAJ
1006
+ AAYAAAAA//kABQABAgAAAAIFAAgABgAAAAH/+gAE//sCBQAAAggAAQAGAAAAAP/5AAYAAAIIAAAC
1007
+ DgAHAAYAAAAB//kABf/+Ag4AAAISAAUABgAA////+wAGAAACEgAAAhkABQAGAAAAAP/7AAX//gIZ
1008
+ AAACHgADAAYAAAAA//wABf/9Ah4AAAIjAAEABgAAAAD/+QAHAAACIwAAAioABwAGAAAAAP/6AAT/
1009
+ +wIqAAACLgABAAYAAAAA//kABP/8Ai4AAAIyAAMABgAAAAD/+gAFAAACMgAAAjcABgAGAAAAAf/5
1010
+ AAT//QI3AAACOgAEAAYAAAAB//kABP/9AjoAAAI9AAQABgAAAAL/+QAE//sCPQAAAj8AAgAGAAD/
1011
+ ///7AAYAAgI/AAACRgAHAAYAAAAA//kABgABAkYAAAJMAAgABgAAAAH//AAD//0CTAAAAk4AAQAG
1012
+ AAAAAf//AAQAAgJOAAACUQADAAYAAAAB//kABP/9AlEAAAJUAAQABgAAAAH/+QAF//4CVAAAAlgA
1013
+ BQAGAAD////7AAYAAAJYAAACXwAFAAYAAP////kABgAAAl8AAAJmAAcABgAA////+QAGAAACZgAA
1014
+ Am0ABwAGAAD////5AAYAAAJtAAACdAAHAAYAAAAA//sABQACAnQAAAJ5AAcABgAA////9wAGAAAC
1015
+ eQAAAoAACQAGAAD////3AAYAAAKAAAAChwAJAAYAAP////cABgAAAocAAAKOAAkABgAA////9wAG
1016
+ AAACjgAAApUACQAGAAD////4AAYAAAKVAAACnAAIAAYAAP////cABgAAApwAAAKjAAkABgAA////
1017
+ +gAGAAACowAAAqoABgAGAAAAAP/6AAUAAgKqAAACrwAIAAYAAP////cABQAAAq8AAAK1AAkABgAA
1018
+ ////9wAFAAACtQAAArsACQAGAAD////3AAUAAAK7AAACwQAJAAYAAP////gABQAAAsEAAALHAAgA
1019
+ BgAAAAD/9wAEAAACxwAAAssACQAGAAAAAP/3AAQAAALLAAACzwAJAAYAAAAA//cABAAAAs8AAALT
1020
+ AAkABgAAAAD/+AAEAAAC0wAAAtcACAAGAAD////6AAUAAALXAAAC3QAGAAYAAP////cABgAAAt0A
1021
+ AALkAAkABgAAAAD/9wAFAAAC5AAAAukACQAGAAAAAP/3AAUAAALpAAAC7gAJAAYAAAAA//cABQAA
1022
+ Au4AAALzAAkABgAAAAD/9wAFAAAC8wAAAvgACQAGAAAAAP/4AAUAAAL4AAAC/QAIAAYAAAAA//oA
1023
+ Bf//Av0AAAMCAAUABgAA////+gAGAAADAgAAAwkABgAGAAD////3AAYAAAMJAAADEAAJAAYAAP//
1024
+ //cABgAAAxAAAAMXAAkABgAA////9wAGAAADFwAAAx4ACQAGAAD////4AAYAAAAAAAoABwASAAYA
1025
+ AP////cABgAAAAcACgAOABMABgAA////+gAFAAAADgAKABQAEAAGAAD////6AAYAAAAUAAoAGwAQ
1026
+ AAYAAAAA//gABgAAABsACgAhABIABgAAAAD/+AAGAAAAIQAKACcAEgAGAAAAAP/4AAYAAAAnAAoA
1027
+ LQASAAYAAAAA//gABgAAAC0ACgAzABIABgAAAAD/+QAGAAAAMwAKADkAEQAGAAAAAP/3AAYAAAA5
1028
+ AAoAPwATAAYAAP////sABQAAAD8ACgBFAA8ABgAAAAD/+wAFAAIARQAKAEoAEQAGAAAAAP/4AAUA
1029
+ AABKAAoATwASAAYAAAAA//gABQAAAE8ACgBUABIABgAAAAD/+AAFAAAAVAAKAFkAEgAGAAAAAP/5
1030
+ AAUAAABZAAoAXgARAAYAAAAA//gABgAAAF4ACgBkABIABgAAAAD/+AAGAAAAZAAKAGoAEgAGAAAA
1031
+ AP/4AAYAAABqAAoAcAASAAYAAAAA//kABgAAAHAACgB2ABEABgAAAAD/+AAFAAAAdgAKAHsAEgAG
1032
+ AAD////4AAYAAAB7AAoAggASAAYAAAAA//gABQAAAIIACgCHABIABgAAAAD/+AAFAAAAhwAKAIwA
1033
+ EgAGAAAAAP/4AAUAAACMAAoAkQASAAYAAAAA//gABQAAAJEACgCWABIABgAAAAD/+QAFAAAAlgAK
1034
+ AJsAEQAGAAAAAP/6AAX//wCbAAoAoAAPAAYAAAAA//oABQABAKAACgClABEABgAA////+AAGAAAA
1035
+ pQAKAKwAEgAGAAD////4AAYAAACsAAoAswASAAYAAP////gABgAAALMACgC6ABIABgAA////+QAG
1036
+ AAAAugAKAMEAEQAGAAD////4AAYAAgDBAAoAyAAUAAYAAP////kABQACAMgACgDOABMABgAA////
1037
+ +QAGAAIAzgAKANUAEw==
1038
+ """)),
1039
+ Image.open(BytesIO(base64.b64decode(b"""
1040
+ iVBORw0KGgoAAAANSUhEUgAAAx4AAAAUAQAAAAArMtZoAAAEwElEQVR4nABlAJr/AHVE4czCI/4u
1041
+ Mc4b7vuds/xzjz5/3/7u/n9vMe7vnfH/9++vPn/xyf5zhxzjt8GHw8+2d83u8x27199/nxuQ6Od9
1042
+ M43/5z2I+9n9ZtmDBwMQECDRQw/eQIQohJXxpBCNVE6QCCAAAAD//wBlAJr/AgALyj1t/wINwq0g
1043
+ LeNZUworuN1cjTPIzrTX6ofHWeo3v336qPzfEwRmBnHTtf95/fglZK5N0PDgfRTslpGBvz7LFc4F
1044
+ IUXBWQGjQ5MGCx34EDFPwXiY4YbYxavpnhHFrk14CDAAAAD//wBlAJr/AgKqRooH2gAgPeggvUAA
1045
+ Bu2WfgPoAwzRAABAAAAAAACQgLz/3Uv4Gv+gX7BJgDeeGP6AAAD1NMDzKHD7ANWr3loYbxsAD791
1046
+ NAADfcoID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iWLci5v1+HmFXDqcnULE/MxgYGBj+f6CaJQAA
1060
+ AAD//2Ji2FrkY3iYpYC5qDeGgeEMAwPDvwQBBoYvcTwOVLMEAAAA//9isDBgkP///0EOg9z35v//
1061
+ Gc/eeW7BwPj5+QGZhANUswMAAAD//2JgqGBgYGBgqEMXlvhMPUsAAAAA//8iYDd1AAAAAP//AwDR
1062
+ w7IkEbzhVQAAAABJRU5ErkJggg==
1063
+ """))),
1064
+ )
1065
+ return f
1066
+
1067
+
1068
+ def load_default(size: float | None = None) -> FreeTypeFont | ImageFont:
1069
+ """If FreeType support is available, load a version of Aileron Regular,
1070
+ https://dotcolon.net/fonts/aileron, with a more limited character set.
1071
+
1072
+ Otherwise, load a "better than nothing" font.
1073
+
1074
+ .. versionadded:: 1.1.4
1075
+
1076
+ :param size: The font size of Aileron Regular.
1077
+
1078
+ .. versionadded:: 10.1.0
1079
+
1080
+ :return: A font object.
1081
+ """
1082
+ if isinstance(core, ModuleType) or size is not None:
1083
+ return truetype(
1084
+ BytesIO(base64.b64decode(b"""
1085
+ AAEAAAAPAIAAAwBwRkZUTYwDlUAAADFoAAAAHEdERUYAqADnAAAo8AAAACRHUE9ThhmITwAAKfgAA
1086
+ AduR1NVQnHxefoAACkUAAAA4k9TLzJovoHLAAABeAAAAGBjbWFw5lFQMQAAA6gAAAGqZ2FzcP//AA
1087
+ MAACjoAAAACGdseWYmRXoPAAAGQAAAHfhoZWFkE18ayQAAAPwAAAA2aGhlYQboArEAAAE0AAAAJGh
1088
+ tdHjjERZ8AAAB2AAAAdBsb2NhuOexrgAABVQAAADqbWF4cAC7AEYAAAFYAAAAIG5hbWUr+h5lAAAk
1089
+ OAAAA6Jwb3N0D3oPTQAAJ9wAAAEKAAEAAAABGhxJDqIhXw889QALA+gAAAAA0Bqf2QAAAADhCh2h/
1090
+ 2r/LgOxAyAAAAAIAAIAAAAAAAAAAQAAA8r/GgAAA7j/av9qA7EAAQAAAAAAAAAAAAAAAAAAAHQAAQ
1091
+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AAAQAJAAAAAAAAAAAAAAAAAAAAGAAAA
1298
+ AAABwAAAAAAAAAAAAAAFQAFAAAAAAAYABgAAAAUAAAACgAAAAwAAgAPABEAFgAAAAAAAAAAAAAAAA
1299
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAEAEQBdAAYAAAAAAAAAAAAAAAAAAAAAAAA
1300
+ AAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAcAAAAAAAAABwAAAAAACAAAAAAAAAAAAAcAAAAHAAAAEwAJ
1301
+ ABUADgAPAAAACwAQAAAAAAAAAAAAAAAAAAUAGAACAAIAAgAAAAIAGAAXAAAAGAAAABYAFgACABYAA
1302
+ gAWAAAAEQADAAoAFAAMAA0ABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASAAAAEgAGAAEAHgAkAC
1303
+ YAJwApACoALQAuAC8AMgAzADcAOAA5ADoAPAA9AEUASABOAE8AUgBTAFUAVwBZAFoAWwBcAF0AcwA
1304
+ AAAAAAQAAAADa3tfFAAAAANAan9kAAAAA4QodoQ==
1305
+ """)),
1306
+ 10 if size is None else size,
1307
+ layout_engine=Layout.BASIC,
1308
+ )
1309
+ return load_default_imagefont()
.venv/Lib/site-packages/PIL/ImageGrab.py ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ TYPE_CHECKING = False
29
+ if TYPE_CHECKING:
30
+ from . import ImageWin
31
+
32
+
33
+ def grab(
34
+ bbox: tuple[int, int, int, int] | None = None,
35
+ include_layered_windows: bool = False,
36
+ all_screens: bool = False,
37
+ xdisplay: str | None = None,
38
+ window: int | ImageWin.HWND | None = None,
39
+ ) -> Image.Image:
40
+ im: Image.Image
41
+ if xdisplay is None:
42
+ if sys.platform == "darwin":
43
+ fh, filepath = tempfile.mkstemp(".png")
44
+ os.close(fh)
45
+ args = ["screencapture"]
46
+ if window is not None:
47
+ args += ["-l", str(window)]
48
+ elif bbox:
49
+ left, top, right, bottom = bbox
50
+ args += ["-R", f"{left},{top},{right-left},{bottom-top}"]
51
+ args += ["-x", filepath]
52
+ retcode = subprocess.call(args)
53
+ if retcode:
54
+ raise subprocess.CalledProcessError(retcode, args)
55
+ im = Image.open(filepath)
56
+ im.load()
57
+ os.unlink(filepath)
58
+ if bbox:
59
+ if window is not None:
60
+ # Determine if the window was in Retina mode or not
61
+ # by capturing it without the shadow,
62
+ # and checking how different the width is
63
+ fh, filepath = tempfile.mkstemp(".png")
64
+ os.close(fh)
65
+ args = ["screencapture", "-l", str(window), "-o", "-x", filepath]
66
+ retcode = subprocess.call(args)
67
+ if retcode:
68
+ raise subprocess.CalledProcessError(retcode, args)
69
+ with Image.open(filepath) as im_no_shadow:
70
+ retina = im.width - im_no_shadow.width > 100
71
+ os.unlink(filepath)
72
+
73
+ # Since screencapture's -R does not work with -l,
74
+ # crop the image manually
75
+ if retina:
76
+ left, top, right, bottom = bbox
77
+ im_cropped = im.resize(
78
+ (right - left, bottom - top),
79
+ box=tuple(coord * 2 for coord in bbox),
80
+ )
81
+ else:
82
+ im_cropped = im.crop(bbox)
83
+ im.close()
84
+ return im_cropped
85
+ else:
86
+ im_resized = im.resize((right - left, bottom - top))
87
+ im.close()
88
+ return im_resized
89
+ return im
90
+ elif sys.platform == "win32":
91
+ if window is not None:
92
+ all_screens = -1
93
+ offset, size, data = Image.core.grabscreen_win32(
94
+ include_layered_windows,
95
+ all_screens,
96
+ int(window) if window is not None else 0,
97
+ )
98
+ im = Image.frombytes(
99
+ "RGB",
100
+ size,
101
+ data,
102
+ # RGB, 32-bit line padding, origin lower left corner
103
+ "raw",
104
+ "BGR",
105
+ (size[0] * 3 + 3) & -4,
106
+ -1,
107
+ )
108
+ if bbox:
109
+ x0, y0 = offset
110
+ left, top, right, bottom = bbox
111
+ im = im.crop((left - x0, top - y0, right - x0, bottom - y0))
112
+ return im
113
+ # Cast to Optional[str] needed for Windows and macOS.
114
+ display_name: str | None = xdisplay
115
+ try:
116
+ if not Image.core.HAVE_XCB:
117
+ msg = "Pillow was built without XCB support"
118
+ raise OSError(msg)
119
+ size, data = Image.core.grabscreen_x11(display_name)
120
+ except OSError:
121
+ if display_name is None and sys.platform not in ("darwin", "win32"):
122
+ if shutil.which("gnome-screenshot"):
123
+ args = ["gnome-screenshot", "-f"]
124
+ elif shutil.which("grim"):
125
+ args = ["grim"]
126
+ elif shutil.which("spectacle"):
127
+ args = ["spectacle", "-n", "-b", "-f", "-o"]
128
+ else:
129
+ raise
130
+ fh, filepath = tempfile.mkstemp(".png")
131
+ os.close(fh)
132
+ args.append(filepath)
133
+ retcode = subprocess.call(args)
134
+ if retcode:
135
+ raise subprocess.CalledProcessError(retcode, args)
136
+ im = Image.open(filepath)
137
+ im.load()
138
+ os.unlink(filepath)
139
+ if bbox:
140
+ im_cropped = im.crop(bbox)
141
+ im.close()
142
+ return im_cropped
143
+ return im
144
+ else:
145
+ raise
146
+ else:
147
+ im = Image.frombytes("RGB", size, data, "raw", "BGRX", size[0] * 4, 1)
148
+ if bbox:
149
+ im = im.crop(bbox)
150
+ return im
151
+
152
+
153
+ def grabclipboard() -> Image.Image | list[str] | None:
154
+ if sys.platform == "darwin":
155
+ p = subprocess.run(
156
+ ["osascript", "-e", "get the clipboard as «class PNGf»"],
157
+ capture_output=True,
158
+ )
159
+ if p.returncode != 0:
160
+ return None
161
+
162
+ import binascii
163
+
164
+ data = io.BytesIO(binascii.unhexlify(p.stdout[11:-3]))
165
+ return Image.open(data)
166
+ elif sys.platform == "win32":
167
+ fmt, data = Image.core.grabclipboard_win32()
168
+ if fmt == "file": # CF_HDROP
169
+ import struct
170
+
171
+ o = struct.unpack_from("I", data)[0]
172
+ if data[16] == 0:
173
+ files = data[o:].decode("mbcs").split("\0")
174
+ else:
175
+ files = data[o:].decode("utf-16le").split("\0")
176
+ return files[: files.index("")]
177
+ if isinstance(data, bytes):
178
+ data = io.BytesIO(data)
179
+ if fmt == "png":
180
+ from . import PngImagePlugin
181
+
182
+ return PngImagePlugin.PngImageFile(data)
183
+ elif fmt == "DIB":
184
+ from . import BmpImagePlugin
185
+
186
+ return BmpImagePlugin.DibImageFile(data)
187
+ return None
188
+ else:
189
+ if os.getenv("WAYLAND_DISPLAY"):
190
+ session_type = "wayland"
191
+ elif os.getenv("DISPLAY"):
192
+ session_type = "x11"
193
+ else: # Session type check failed
194
+ session_type = None
195
+
196
+ if shutil.which("wl-paste") and session_type in ("wayland", None):
197
+ args = ["wl-paste", "-t", "image"]
198
+ elif shutil.which("xclip") and session_type in ("x11", None):
199
+ args = ["xclip", "-selection", "clipboard", "-t", "image/png", "-o"]
200
+ else:
201
+ msg = "wl-paste or xclip is required for ImageGrab.grabclipboard() on Linux"
202
+ raise NotImplementedError(msg)
203
+
204
+ p = subprocess.run(args, capture_output=True)
205
+ if p.returncode != 0:
206
+ err = p.stderr
207
+ for silent_error in [
208
+ # wl-paste, when the clipboard is empty
209
+ b"Nothing is copied",
210
+ # Ubuntu/Debian wl-paste, when the clipboard is empty
211
+ b"No selection",
212
+ # Ubuntu/Debian wl-paste, when an image isn't available
213
+ b"No suitable type of content copied",
214
+ # wl-paste or Ubuntu/Debian xclip, when an image isn't available
215
+ b" not available",
216
+ # xclip, when an image isn't available
217
+ b"cannot convert ",
218
+ # xclip, when the clipboard isn't initialized
219
+ b"xclip: Error: There is no owner for the ",
220
+ ]:
221
+ if silent_error in err:
222
+ return None
223
+ msg = f"{args[0]} error"
224
+ if err:
225
+ msg += f": {err.strip().decode()}"
226
+ raise ChildProcessError(msg)
227
+
228
+ data = io.BytesIO(p.stdout)
229
+ im = Image.open(data)
230
+ im.load()
231
+ return im
.venv/Lib/site-packages/PIL/ImageMath.py ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
21
+ from . import Image, _imagingmath
22
+
23
+ TYPE_CHECKING = False
24
+ if TYPE_CHECKING:
25
+ from collections.abc import Callable
26
+ from types import CodeType
27
+ from typing import Any
28
+
29
+
30
+ class _Operand:
31
+ """Wraps an image operand, providing standard operators"""
32
+
33
+ def __init__(self, im: Image.Image):
34
+ self.im = im
35
+
36
+ def __fixup(self, im1: _Operand | float) -> Image.Image:
37
+ # convert image to suitable mode
38
+ if isinstance(im1, _Operand):
39
+ # argument was an image.
40
+ if im1.im.mode in ("1", "L"):
41
+ return im1.im.convert("I")
42
+ elif im1.im.mode in ("I", "F"):
43
+ return im1.im
44
+ else:
45
+ msg = f"unsupported mode: {im1.im.mode}"
46
+ raise ValueError(msg)
47
+ else:
48
+ # argument was a constant
49
+ if isinstance(im1, (int, float)) and self.im.mode in ("1", "L", "I"):
50
+ return Image.new("I", self.im.size, im1)
51
+ else:
52
+ return Image.new("F", self.im.size, im1)
53
+
54
+ def apply(
55
+ self,
56
+ op: str,
57
+ im1: _Operand | float,
58
+ im2: _Operand | float | None = None,
59
+ mode: str | None = None,
60
+ ) -> _Operand:
61
+ im_1 = self.__fixup(im1)
62
+ if im2 is None:
63
+ # unary operation
64
+ out = Image.new(mode or im_1.mode, im_1.size, None)
65
+ try:
66
+ op = getattr(_imagingmath, f"{op}_{im_1.mode}")
67
+ except AttributeError as e:
68
+ msg = f"bad operand type for '{op}'"
69
+ raise TypeError(msg) from e
70
+ _imagingmath.unop(op, out.getim(), im_1.getim())
71
+ else:
72
+ # binary operation
73
+ im_2 = self.__fixup(im2)
74
+ if im_1.mode != im_2.mode:
75
+ # convert both arguments to floating point
76
+ if im_1.mode != "F":
77
+ im_1 = im_1.convert("F")
78
+ if im_2.mode != "F":
79
+ im_2 = im_2.convert("F")
80
+ if im_1.size != im_2.size:
81
+ # crop both arguments to a common size
82
+ size = (
83
+ min(im_1.size[0], im_2.size[0]),
84
+ min(im_1.size[1], im_2.size[1]),
85
+ )
86
+ if im_1.size != size:
87
+ im_1 = im_1.crop((0, 0) + size)
88
+ if im_2.size != size:
89
+ im_2 = im_2.crop((0, 0) + size)
90
+ out = Image.new(mode or im_1.mode, im_1.size, None)
91
+ try:
92
+ op = getattr(_imagingmath, f"{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.getim(), im_1.getim(), im_2.getim())
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: _Operand | float) -> _Operand: # type: ignore[override]
180
+ return self.apply("eq", self, other)
181
+
182
+ def __ne__(self, other: _Operand | float) -> _Operand: # type: ignore[override]
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(expression: Callable[[dict[str, Any]], Any], **kw: Any) -> Any:
240
+ """
241
+ Returns the result of an image function.
242
+
243
+ :py:mod:`~PIL.ImageMath` only supports single-layer images. To process multi-band
244
+ images, use the :py:meth:`~PIL.Image.Image.split` method or
245
+ :py:func:`~PIL.Image.merge` function.
246
+
247
+ :param expression: A function that receives a dictionary.
248
+ :param **kw: Values to add to the function's dictionary.
249
+ :return: The expression result. This is usually an image object, but can
250
+ also be an integer, a floating point value, or a pixel tuple,
251
+ depending on the expression.
252
+ """
253
+
254
+ args: dict[str, Any] = ops.copy()
255
+ args.update(kw)
256
+ for k, v in args.items():
257
+ if isinstance(v, Image.Image):
258
+ args[k] = _Operand(v)
259
+
260
+ out = expression(args)
261
+ try:
262
+ return out.im
263
+ except AttributeError:
264
+ return out
265
+
266
+
267
+ def unsafe_eval(expression: str, **kw: Any) -> Any:
268
+ """
269
+ Evaluates an image expression. This uses Python's ``eval()`` function to process
270
+ the expression string, and carries the security risks of doing so. It is not
271
+ recommended to process expressions without considering this.
272
+ :py:meth:`~lambda_eval` is a more secure alternative.
273
+
274
+ :py:mod:`~PIL.ImageMath` only supports single-layer images. To process multi-band
275
+ images, use the :py:meth:`~PIL.Image.Image.split` method or
276
+ :py:func:`~PIL.Image.merge` function.
277
+
278
+ :param expression: A string containing a Python-style expression.
279
+ :param **kw: Values to add to the evaluation context.
280
+ :return: The evaluated expression. This is usually an image object, but can
281
+ also be an integer, a floating point value, or a pixel tuple,
282
+ depending on the expression.
283
+ """
284
+
285
+ # build execution namespace
286
+ args: dict[str, Any] = ops.copy()
287
+ for k in kw:
288
+ if "__" in k or hasattr(builtins, k):
289
+ msg = f"'{k}' not allowed"
290
+ raise ValueError(msg)
291
+
292
+ args.update(kw)
293
+ for k, v in args.items():
294
+ if isinstance(v, Image.Image):
295
+ args[k] = _Operand(v)
296
+
297
+ compiled_code = compile(expression, "<string>", "eval")
298
+
299
+ def scan(code: CodeType) -> None:
300
+ for const in code.co_consts:
301
+ if type(const) is type(compiled_code):
302
+ scan(const)
303
+
304
+ for name in code.co_names:
305
+ if name not in args and name != "abs":
306
+ msg = f"'{name}' not allowed"
307
+ raise ValueError(msg)
308
+
309
+ scan(compiled_code)
310
+ out = builtins.eval(expression, {"__builtins": {"abs": abs}}, args)
311
+ try:
312
+ return out.im
313
+ except AttributeError:
314
+ return out