ZTWHHH commited on
Commit
d55d1f9
·
verified ·
1 Parent(s): 3df9050

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. phi4/lib/python3.10/site-packages/PIL/BmpImagePlugin.py +511 -0
  2. phi4/lib/python3.10/site-packages/PIL/BufrStubImagePlugin.py +76 -0
  3. phi4/lib/python3.10/site-packages/PIL/CurImagePlugin.py +75 -0
  4. phi4/lib/python3.10/site-packages/PIL/FliImagePlugin.py +175 -0
  5. phi4/lib/python3.10/site-packages/PIL/FontFile.py +134 -0
  6. phi4/lib/python3.10/site-packages/PIL/GribStubImagePlugin.py +76 -0
  7. phi4/lib/python3.10/site-packages/PIL/IcoImagePlugin.py +381 -0
  8. phi4/lib/python3.10/site-packages/PIL/ImImagePlugin.py +386 -0
  9. phi4/lib/python3.10/site-packages/PIL/ImageCms.py +1125 -0
  10. phi4/lib/python3.10/site-packages/PIL/ImageFilter.py +605 -0
  11. phi4/lib/python3.10/site-packages/PIL/ImageMode.py +92 -0
  12. phi4/lib/python3.10/site-packages/PIL/ImagePath.py +20 -0
  13. phi4/lib/python3.10/site-packages/PIL/ImageShow.py +360 -0
  14. phi4/lib/python3.10/site-packages/PIL/ImageTk.py +290 -0
  15. phi4/lib/python3.10/site-packages/PIL/ImageTransform.py +136 -0
  16. phi4/lib/python3.10/site-packages/PIL/ImageWin.py +247 -0
  17. phi4/lib/python3.10/site-packages/PIL/ImtImagePlugin.py +103 -0
  18. phi4/lib/python3.10/site-packages/PIL/JpegPresets.py +242 -0
  19. phi4/lib/python3.10/site-packages/PIL/MicImagePlugin.py +107 -0
  20. phi4/lib/python3.10/site-packages/PIL/PngImagePlugin.py +1544 -0
  21. phi4/lib/python3.10/site-packages/PIL/SgiImagePlugin.py +247 -0
  22. phi4/lib/python3.10/site-packages/PIL/SpiderImagePlugin.py +326 -0
  23. phi4/lib/python3.10/site-packages/PIL/TgaImagePlugin.py +264 -0
  24. phi4/lib/python3.10/site-packages/PIL/TiffTags.py +562 -0
  25. phi4/lib/python3.10/site-packages/PIL/WalImageFile.py +127 -0
  26. phi4/lib/python3.10/site-packages/PIL/_binary.py +112 -0
  27. phi4/lib/python3.10/site-packages/PIL/_imaging.pyi +31 -0
  28. phi4/lib/python3.10/site-packages/PIL/_imagingft.pyi +69 -0
  29. phi4/lib/python3.10/site-packages/flash_attn/__pycache__/__init__.cpython-310.pyc +0 -0
  30. phi4/lib/python3.10/site-packages/flash_attn/__pycache__/bert_padding.cpython-310.pyc +0 -0
  31. phi4/lib/python3.10/site-packages/flash_attn/__pycache__/flash_attn_interface.cpython-310.pyc +0 -0
  32. phi4/lib/python3.10/site-packages/flash_attn/__pycache__/flash_attn_triton.cpython-310.pyc +0 -0
  33. phi4/lib/python3.10/site-packages/flash_attn/__pycache__/flash_attn_triton_og.cpython-310.pyc +0 -0
  34. phi4/lib/python3.10/site-packages/flash_attn/__pycache__/flash_blocksparse_attention.cpython-310.pyc +0 -0
  35. phi4/lib/python3.10/site-packages/flash_attn/__pycache__/flash_blocksparse_attn_interface.cpython-310.pyc +0 -0
  36. phi4/lib/python3.10/site-packages/flash_attn/__pycache__/fused_softmax.cpython-310.pyc +0 -0
  37. phi4/lib/python3.10/site-packages/flash_attn/losses/__init__.py +0 -0
  38. phi4/lib/python3.10/site-packages/flash_attn/losses/__pycache__/__init__.cpython-310.pyc +0 -0
  39. phi4/lib/python3.10/site-packages/flash_attn/losses/__pycache__/cross_entropy.cpython-310.pyc +0 -0
  40. phi4/lib/python3.10/site-packages/flash_attn/losses/cross_entropy.py +85 -0
  41. phi4/lib/python3.10/site-packages/flash_attn/models/__pycache__/__init__.cpython-310.pyc +0 -0
  42. phi4/lib/python3.10/site-packages/flash_attn/models/__pycache__/baichuan.cpython-310.pyc +0 -0
  43. phi4/lib/python3.10/site-packages/flash_attn/models/__pycache__/bert.cpython-310.pyc +0 -0
  44. phi4/lib/python3.10/site-packages/flash_attn/models/__pycache__/bigcode.cpython-310.pyc +0 -0
  45. phi4/lib/python3.10/site-packages/flash_attn/models/__pycache__/btlm.cpython-310.pyc +0 -0
  46. phi4/lib/python3.10/site-packages/flash_attn/models/__pycache__/falcon.cpython-310.pyc +0 -0
  47. phi4/lib/python3.10/site-packages/flash_attn/models/__pycache__/gpt.cpython-310.pyc +0 -0
  48. phi4/lib/python3.10/site-packages/flash_attn/models/__pycache__/gpt_neox.cpython-310.pyc +0 -0
  49. phi4/lib/python3.10/site-packages/flash_attn/models/__pycache__/gptj.cpython-310.pyc +0 -0
  50. phi4/lib/python3.10/site-packages/flash_attn/models/__pycache__/llama.cpython-310.pyc +0 -0
phi4/lib/python3.10/site-packages/PIL/BmpImagePlugin.py ADDED
@@ -0,0 +1,511 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
52
+ def _accept(prefix: bytes) -> bool:
53
+ return prefix[:2] == b"BM"
54
+
55
+
56
+ def _dib_accept(prefix: bytes) -> bool:
57
+ return i32(prefix) in [12, 40, 52, 56, 64, 108, 124]
58
+
59
+
60
+ # =============================================================================
61
+ # Image plugin for the Windows BMP format.
62
+ # =============================================================================
63
+ class BmpImageFile(ImageFile.ImageFile):
64
+ """Image plugin for the Windows Bitmap format (BMP)"""
65
+
66
+ # ------------------------------------------------------------- Description
67
+ format_description = "Windows Bitmap"
68
+ format = "BMP"
69
+
70
+ # -------------------------------------------------- BMP Compression values
71
+ COMPRESSIONS = {"RAW": 0, "RLE8": 1, "RLE4": 2, "BITFIELDS": 3, "JPEG": 4, "PNG": 5}
72
+ for k, v in COMPRESSIONS.items():
73
+ vars()[k] = v
74
+
75
+ def _bitmap(self, header: int = 0, offset: int = 0) -> None:
76
+ """Read relevant info about the BMP"""
77
+ read, seek = self.fp.read, self.fp.seek
78
+ if header:
79
+ seek(header)
80
+ # read bmp header size @offset 14 (this is part of the header size)
81
+ file_info: dict[str, bool | int | tuple[int, ...]] = {
82
+ "header_size": i32(read(4)),
83
+ "direction": -1,
84
+ }
85
+
86
+ # -------------------- If requested, read header at a specific position
87
+ # read the rest of the bmp header, without its size
88
+ assert isinstance(file_info["header_size"], int)
89
+ header_data = ImageFile._safe_read(self.fp, file_info["header_size"] - 4)
90
+
91
+ # ------------------------------- Windows Bitmap v2, IBM OS/2 Bitmap v1
92
+ # ----- This format has different offsets because of width/height types
93
+ # 12: BITMAPCOREHEADER/OS21XBITMAPHEADER
94
+ if file_info["header_size"] == 12:
95
+ file_info["width"] = i16(header_data, 0)
96
+ file_info["height"] = i16(header_data, 2)
97
+ file_info["planes"] = i16(header_data, 4)
98
+ file_info["bits"] = i16(header_data, 6)
99
+ file_info["compression"] = self.COMPRESSIONS["RAW"]
100
+ file_info["palette_padding"] = 3
101
+
102
+ # --------------------------------------------- Windows Bitmap v3 to v5
103
+ # 40: BITMAPINFOHEADER
104
+ # 52: BITMAPV2HEADER
105
+ # 56: BITMAPV3HEADER
106
+ # 64: BITMAPCOREHEADER2/OS22XBITMAPHEADER
107
+ # 108: BITMAPV4HEADER
108
+ # 124: BITMAPV5HEADER
109
+ elif file_info["header_size"] in (40, 52, 56, 64, 108, 124):
110
+ file_info["y_flip"] = header_data[7] == 0xFF
111
+ file_info["direction"] = 1 if file_info["y_flip"] else -1
112
+ file_info["width"] = i32(header_data, 0)
113
+ file_info["height"] = (
114
+ i32(header_data, 4)
115
+ if not file_info["y_flip"]
116
+ else 2**32 - i32(header_data, 4)
117
+ )
118
+ file_info["planes"] = i16(header_data, 8)
119
+ file_info["bits"] = i16(header_data, 10)
120
+ file_info["compression"] = i32(header_data, 12)
121
+ # byte size of pixel data
122
+ file_info["data_size"] = i32(header_data, 16)
123
+ file_info["pixels_per_meter"] = (
124
+ i32(header_data, 20),
125
+ i32(header_data, 24),
126
+ )
127
+ file_info["colors"] = i32(header_data, 28)
128
+ file_info["palette_padding"] = 4
129
+ assert isinstance(file_info["pixels_per_meter"], tuple)
130
+ self.info["dpi"] = tuple(x / 39.3701 for x in file_info["pixels_per_meter"])
131
+ if file_info["compression"] == self.COMPRESSIONS["BITFIELDS"]:
132
+ masks = ["r_mask", "g_mask", "b_mask"]
133
+ if len(header_data) >= 48:
134
+ if len(header_data) >= 52:
135
+ masks.append("a_mask")
136
+ else:
137
+ file_info["a_mask"] = 0x0
138
+ for idx, mask in enumerate(masks):
139
+ file_info[mask] = i32(header_data, 36 + idx * 4)
140
+ else:
141
+ # 40 byte headers only have the three components in the
142
+ # bitfields masks, ref:
143
+ # https://msdn.microsoft.com/en-us/library/windows/desktop/dd183376(v=vs.85).aspx
144
+ # See also
145
+ # https://github.com/python-pillow/Pillow/issues/1293
146
+ # There is a 4th component in the RGBQuad, in the alpha
147
+ # location, but it is listed as a reserved component,
148
+ # and it is not generally an alpha channel
149
+ file_info["a_mask"] = 0x0
150
+ for mask in masks:
151
+ file_info[mask] = i32(read(4))
152
+ assert isinstance(file_info["r_mask"], int)
153
+ assert isinstance(file_info["g_mask"], int)
154
+ assert isinstance(file_info["b_mask"], int)
155
+ assert isinstance(file_info["a_mask"], int)
156
+ file_info["rgb_mask"] = (
157
+ file_info["r_mask"],
158
+ file_info["g_mask"],
159
+ file_info["b_mask"],
160
+ )
161
+ file_info["rgba_mask"] = (
162
+ file_info["r_mask"],
163
+ file_info["g_mask"],
164
+ file_info["b_mask"],
165
+ file_info["a_mask"],
166
+ )
167
+ else:
168
+ msg = f"Unsupported BMP header type ({file_info['header_size']})"
169
+ raise OSError(msg)
170
+
171
+ # ------------------ Special case : header is reported 40, which
172
+ # ---------------------- is shorter than real size for bpp >= 16
173
+ assert isinstance(file_info["width"], int)
174
+ assert isinstance(file_info["height"], int)
175
+ self._size = file_info["width"], file_info["height"]
176
+
177
+ # ------- If color count was not found in the header, compute from bits
178
+ assert isinstance(file_info["bits"], int)
179
+ file_info["colors"] = (
180
+ file_info["colors"]
181
+ if file_info.get("colors", 0)
182
+ else (1 << file_info["bits"])
183
+ )
184
+ assert isinstance(file_info["colors"], int)
185
+ if offset == 14 + file_info["header_size"] and file_info["bits"] <= 8:
186
+ offset += 4 * file_info["colors"]
187
+
188
+ # ---------------------- Check bit depth for unusual unsupported values
189
+ self._mode, raw_mode = BIT2MODE.get(file_info["bits"], ("", ""))
190
+ if not self.mode:
191
+ msg = f"Unsupported BMP pixel depth ({file_info['bits']})"
192
+ raise OSError(msg)
193
+
194
+ # ---------------- Process BMP with Bitfields compression (not palette)
195
+ decoder_name = "raw"
196
+ if file_info["compression"] == self.COMPRESSIONS["BITFIELDS"]:
197
+ SUPPORTED: dict[int, list[tuple[int, ...]]] = {
198
+ 32: [
199
+ (0xFF0000, 0xFF00, 0xFF, 0x0),
200
+ (0xFF000000, 0xFF0000, 0xFF00, 0x0),
201
+ (0xFF000000, 0xFF00, 0xFF, 0x0),
202
+ (0xFF000000, 0xFF0000, 0xFF00, 0xFF),
203
+ (0xFF, 0xFF00, 0xFF0000, 0xFF000000),
204
+ (0xFF0000, 0xFF00, 0xFF, 0xFF000000),
205
+ (0xFF000000, 0xFF00, 0xFF, 0xFF0000),
206
+ (0x0, 0x0, 0x0, 0x0),
207
+ ],
208
+ 24: [(0xFF0000, 0xFF00, 0xFF)],
209
+ 16: [(0xF800, 0x7E0, 0x1F), (0x7C00, 0x3E0, 0x1F)],
210
+ }
211
+ MASK_MODES = {
212
+ (32, (0xFF0000, 0xFF00, 0xFF, 0x0)): "BGRX",
213
+ (32, (0xFF000000, 0xFF0000, 0xFF00, 0x0)): "XBGR",
214
+ (32, (0xFF000000, 0xFF00, 0xFF, 0x0)): "BGXR",
215
+ (32, (0xFF000000, 0xFF0000, 0xFF00, 0xFF)): "ABGR",
216
+ (32, (0xFF, 0xFF00, 0xFF0000, 0xFF000000)): "RGBA",
217
+ (32, (0xFF0000, 0xFF00, 0xFF, 0xFF000000)): "BGRA",
218
+ (32, (0xFF000000, 0xFF00, 0xFF, 0xFF0000)): "BGAR",
219
+ (32, (0x0, 0x0, 0x0, 0x0)): "BGRA",
220
+ (24, (0xFF0000, 0xFF00, 0xFF)): "BGR",
221
+ (16, (0xF800, 0x7E0, 0x1F)): "BGR;16",
222
+ (16, (0x7C00, 0x3E0, 0x1F)): "BGR;15",
223
+ }
224
+ if file_info["bits"] in SUPPORTED:
225
+ if (
226
+ file_info["bits"] == 32
227
+ and file_info["rgba_mask"] in SUPPORTED[file_info["bits"]]
228
+ ):
229
+ assert isinstance(file_info["rgba_mask"], tuple)
230
+ raw_mode = MASK_MODES[(file_info["bits"], file_info["rgba_mask"])]
231
+ self._mode = "RGBA" if "A" in raw_mode else self.mode
232
+ elif (
233
+ file_info["bits"] in (24, 16)
234
+ and file_info["rgb_mask"] in SUPPORTED[file_info["bits"]]
235
+ ):
236
+ assert isinstance(file_info["rgb_mask"], tuple)
237
+ raw_mode = MASK_MODES[(file_info["bits"], file_info["rgb_mask"])]
238
+ else:
239
+ msg = "Unsupported BMP bitfields layout"
240
+ raise OSError(msg)
241
+ else:
242
+ msg = "Unsupported BMP bitfields layout"
243
+ raise OSError(msg)
244
+ elif file_info["compression"] == self.COMPRESSIONS["RAW"]:
245
+ if file_info["bits"] == 32 and header == 22: # 32-bit .cur offset
246
+ raw_mode, self._mode = "BGRA", "RGBA"
247
+ elif file_info["compression"] in (
248
+ self.COMPRESSIONS["RLE8"],
249
+ self.COMPRESSIONS["RLE4"],
250
+ ):
251
+ decoder_name = "bmp_rle"
252
+ else:
253
+ msg = f"Unsupported BMP compression ({file_info['compression']})"
254
+ raise OSError(msg)
255
+
256
+ # --------------- Once the header is processed, process the palette/LUT
257
+ if self.mode == "P": # Paletted for 1, 4 and 8 bit images
258
+ # ---------------------------------------------------- 1-bit images
259
+ if not (0 < file_info["colors"] <= 65536):
260
+ msg = f"Unsupported BMP Palette size ({file_info['colors']})"
261
+ raise OSError(msg)
262
+ else:
263
+ assert isinstance(file_info["palette_padding"], int)
264
+ padding = file_info["palette_padding"]
265
+ palette = read(padding * file_info["colors"])
266
+ grayscale = True
267
+ indices = (
268
+ (0, 255)
269
+ if file_info["colors"] == 2
270
+ else list(range(file_info["colors"]))
271
+ )
272
+
273
+ # ----------------- Check if grayscale and ignore palette if so
274
+ for ind, val in enumerate(indices):
275
+ rgb = palette[ind * padding : ind * padding + 3]
276
+ if rgb != o8(val) * 3:
277
+ grayscale = False
278
+
279
+ # ------- If all colors are gray, white or black, ditch palette
280
+ if grayscale:
281
+ self._mode = "1" if file_info["colors"] == 2 else "L"
282
+ raw_mode = self.mode
283
+ else:
284
+ self._mode = "P"
285
+ self.palette = ImagePalette.raw(
286
+ "BGRX" if padding == 4 else "BGR", palette
287
+ )
288
+
289
+ # ---------------------------- Finally set the tile data for the plugin
290
+ self.info["compression"] = file_info["compression"]
291
+ args: list[Any] = [raw_mode]
292
+ if decoder_name == "bmp_rle":
293
+ args.append(file_info["compression"] == self.COMPRESSIONS["RLE4"])
294
+ else:
295
+ assert isinstance(file_info["width"], int)
296
+ args.append(((file_info["width"] * file_info["bits"] + 31) >> 3) & (~3))
297
+ args.append(file_info["direction"])
298
+ self.tile = [
299
+ ImageFile._Tile(
300
+ decoder_name,
301
+ (0, 0, file_info["width"], file_info["height"]),
302
+ offset or self.fp.tell(),
303
+ tuple(args),
304
+ )
305
+ ]
306
+
307
+ def _open(self) -> None:
308
+ """Open file, check magic number and read header"""
309
+ # read 14 bytes: magic number, filesize, reserved, header final offset
310
+ head_data = self.fp.read(14)
311
+ # choke if the file does not have the required magic bytes
312
+ if not _accept(head_data):
313
+ msg = "Not a BMP file"
314
+ raise SyntaxError(msg)
315
+ # read the start position of the BMP image data (u32)
316
+ offset = i32(head_data, 10)
317
+ # load bitmap information (offset=raster info)
318
+ self._bitmap(offset=offset)
319
+
320
+
321
+ class BmpRleDecoder(ImageFile.PyDecoder):
322
+ _pulls_fd = True
323
+
324
+ def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:
325
+ assert self.fd is not None
326
+ rle4 = self.args[1]
327
+ data = bytearray()
328
+ x = 0
329
+ dest_length = self.state.xsize * self.state.ysize
330
+ while len(data) < dest_length:
331
+ pixels = self.fd.read(1)
332
+ byte = self.fd.read(1)
333
+ if not pixels or not byte:
334
+ break
335
+ num_pixels = pixels[0]
336
+ if num_pixels:
337
+ # encoded mode
338
+ if x + num_pixels > self.state.xsize:
339
+ # Too much data for row
340
+ num_pixels = max(0, self.state.xsize - x)
341
+ if rle4:
342
+ first_pixel = o8(byte[0] >> 4)
343
+ second_pixel = o8(byte[0] & 0x0F)
344
+ for index in range(num_pixels):
345
+ if index % 2 == 0:
346
+ data += first_pixel
347
+ else:
348
+ data += second_pixel
349
+ else:
350
+ data += byte * num_pixels
351
+ x += num_pixels
352
+ else:
353
+ if byte[0] == 0:
354
+ # end of line
355
+ while len(data) % self.state.xsize != 0:
356
+ data += b"\x00"
357
+ x = 0
358
+ elif byte[0] == 1:
359
+ # end of bitmap
360
+ break
361
+ elif byte[0] == 2:
362
+ # delta
363
+ bytes_read = self.fd.read(2)
364
+ if len(bytes_read) < 2:
365
+ break
366
+ right, up = self.fd.read(2)
367
+ data += b"\x00" * (right + up * self.state.xsize)
368
+ x = len(data) % self.state.xsize
369
+ else:
370
+ # absolute mode
371
+ if rle4:
372
+ # 2 pixels per byte
373
+ byte_count = byte[0] // 2
374
+ bytes_read = self.fd.read(byte_count)
375
+ for byte_read in bytes_read:
376
+ data += o8(byte_read >> 4)
377
+ data += o8(byte_read & 0x0F)
378
+ else:
379
+ byte_count = byte[0]
380
+ bytes_read = self.fd.read(byte_count)
381
+ data += bytes_read
382
+ if len(bytes_read) < byte_count:
383
+ break
384
+ x += byte[0]
385
+
386
+ # align to 16-bit word boundary
387
+ if self.fd.tell() % 2 != 0:
388
+ self.fd.seek(1, os.SEEK_CUR)
389
+ rawmode = "L" if self.mode == "L" else "P"
390
+ self.set_as_raw(bytes(data), rawmode, (0, self.args[-1]))
391
+ return -1, 0
392
+
393
+
394
+ # =============================================================================
395
+ # Image plugin for the DIB format (BMP alias)
396
+ # =============================================================================
397
+ class DibImageFile(BmpImageFile):
398
+ format = "DIB"
399
+ format_description = "Windows Bitmap"
400
+
401
+ def _open(self) -> None:
402
+ self._bitmap()
403
+
404
+
405
+ #
406
+ # --------------------------------------------------------------------
407
+ # Write BMP file
408
+
409
+
410
+ SAVE = {
411
+ "1": ("1", 1, 2),
412
+ "L": ("L", 8, 256),
413
+ "P": ("P", 8, 256),
414
+ "RGB": ("BGR", 24, 0),
415
+ "RGBA": ("BGRA", 32, 0),
416
+ }
417
+
418
+
419
+ def _dib_save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
420
+ _save(im, fp, filename, False)
421
+
422
+
423
+ def _save(
424
+ im: Image.Image, fp: IO[bytes], filename: str | bytes, bitmap_header: bool = True
425
+ ) -> None:
426
+ try:
427
+ rawmode, bits, colors = SAVE[im.mode]
428
+ except KeyError as e:
429
+ msg = f"cannot write mode {im.mode} as BMP"
430
+ raise OSError(msg) from e
431
+
432
+ info = im.encoderinfo
433
+
434
+ dpi = info.get("dpi", (96, 96))
435
+
436
+ # 1 meter == 39.3701 inches
437
+ ppm = tuple(int(x * 39.3701 + 0.5) for x in dpi)
438
+
439
+ stride = ((im.size[0] * bits + 7) // 8 + 3) & (~3)
440
+ header = 40 # or 64 for OS/2 version 2
441
+ image = stride * im.size[1]
442
+
443
+ if im.mode == "1":
444
+ palette = b"".join(o8(i) * 4 for i in (0, 255))
445
+ elif im.mode == "L":
446
+ palette = b"".join(o8(i) * 4 for i in range(256))
447
+ elif im.mode == "P":
448
+ palette = im.im.getpalette("RGB", "BGRX")
449
+ colors = len(palette) // 4
450
+ else:
451
+ palette = None
452
+
453
+ # bitmap header
454
+ if bitmap_header:
455
+ offset = 14 + header + colors * 4
456
+ file_size = offset + image
457
+ if file_size > 2**32 - 1:
458
+ msg = "File size is too large for the BMP format"
459
+ raise ValueError(msg)
460
+ fp.write(
461
+ b"BM" # file type (magic)
462
+ + o32(file_size) # file size
463
+ + o32(0) # reserved
464
+ + o32(offset) # image data offset
465
+ )
466
+
467
+ # bitmap info header
468
+ fp.write(
469
+ o32(header) # info header size
470
+ + o32(im.size[0]) # width
471
+ + o32(im.size[1]) # height
472
+ + o16(1) # planes
473
+ + o16(bits) # depth
474
+ + o32(0) # compression (0=uncompressed)
475
+ + o32(image) # size of bitmap
476
+ + o32(ppm[0]) # resolution
477
+ + o32(ppm[1]) # resolution
478
+ + o32(colors) # colors used
479
+ + o32(colors) # colors important
480
+ )
481
+
482
+ fp.write(b"\0" * (header - 40)) # padding (for OS/2 format)
483
+
484
+ if palette:
485
+ fp.write(palette)
486
+
487
+ ImageFile._save(
488
+ im, fp, [ImageFile._Tile("raw", (0, 0) + im.size, 0, (rawmode, stride, -1))]
489
+ )
490
+
491
+
492
+ #
493
+ # --------------------------------------------------------------------
494
+ # Registry
495
+
496
+
497
+ Image.register_open(BmpImageFile.format, BmpImageFile, _accept)
498
+ Image.register_save(BmpImageFile.format, _save)
499
+
500
+ Image.register_extension(BmpImageFile.format, ".bmp")
501
+
502
+ Image.register_mime(BmpImageFile.format, "image/bmp")
503
+
504
+ Image.register_decoder("bmp_rle", BmpRleDecoder)
505
+
506
+ Image.register_open(DibImageFile.format, DibImageFile, _dib_accept)
507
+ Image.register_save(DibImageFile.format, _dib_save)
508
+
509
+ Image.register_extension(DibImageFile.format, ".dib")
510
+
511
+ Image.register_mime(DibImageFile.format, "image/bmp")
phi4/lib/python3.10/site-packages/PIL/BufrStubImagePlugin.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library
3
+ # $Id$
4
+ #
5
+ # BUFR stub adapter
6
+ #
7
+ # Copyright (c) 1996-2003 by Fredrik Lundh
8
+ #
9
+ # See the README file for information on usage and redistribution.
10
+ #
11
+ from __future__ import annotations
12
+
13
+ from typing import IO
14
+
15
+ from . import Image, ImageFile
16
+
17
+ _handler = None
18
+
19
+
20
+ def register_handler(handler: ImageFile.StubHandler | None) -> None:
21
+ """
22
+ Install application-specific BUFR image handler.
23
+
24
+ :param handler: Handler object.
25
+ """
26
+ global _handler
27
+ _handler = handler
28
+
29
+
30
+ # --------------------------------------------------------------------
31
+ # Image adapter
32
+
33
+
34
+ def _accept(prefix: bytes) -> bool:
35
+ return prefix[:4] == b"BUFR" or prefix[:4] == b"ZCZC"
36
+
37
+
38
+ class BufrStubImageFile(ImageFile.StubImageFile):
39
+ format = "BUFR"
40
+ format_description = "BUFR"
41
+
42
+ def _open(self) -> None:
43
+ offset = self.fp.tell()
44
+
45
+ if not _accept(self.fp.read(4)):
46
+ msg = "Not a BUFR file"
47
+ raise SyntaxError(msg)
48
+
49
+ self.fp.seek(offset)
50
+
51
+ # make something up
52
+ self._mode = "F"
53
+ self._size = 1, 1
54
+
55
+ loader = self._load()
56
+ if loader:
57
+ loader.open(self)
58
+
59
+ def _load(self) -> ImageFile.StubHandler | None:
60
+ return _handler
61
+
62
+
63
+ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
64
+ if _handler is None or not hasattr(_handler, "save"):
65
+ msg = "BUFR save handler not installed"
66
+ raise OSError(msg)
67
+ _handler.save(im, fp, filename)
68
+
69
+
70
+ # --------------------------------------------------------------------
71
+ # Registry
72
+
73
+ Image.register_open(BufrStubImageFile.format, BufrStubImageFile, _accept)
74
+ Image.register_save(BufrStubImageFile.format, _save)
75
+
76
+ Image.register_extension(BufrStubImageFile.format, ".bufr")
phi4/lib/python3.10/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, ImageFile
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[:4] == b"\0\0\2\0"
30
+
31
+
32
+ ##
33
+ # Image plugin for Windows Cursor files.
34
+
35
+
36
+ class CurImageFile(BmpImagePlugin.BmpImageFile):
37
+ format = "CUR"
38
+ format_description = "Windows Cursor"
39
+
40
+ def _open(self) -> None:
41
+ offset = self.fp.tell()
42
+
43
+ # check magic
44
+ s = self.fp.read(6)
45
+ if not _accept(s):
46
+ msg = "not a CUR file"
47
+ raise SyntaxError(msg)
48
+
49
+ # pick the largest cursor in the file
50
+ m = b""
51
+ for i in range(i16(s, 4)):
52
+ s = self.fp.read(16)
53
+ if not m:
54
+ m = s
55
+ elif s[0] > m[0] and s[1] > m[1]:
56
+ m = s
57
+ if not m:
58
+ msg = "No cursors were found"
59
+ raise TypeError(msg)
60
+
61
+ # load as bitmap
62
+ self._bitmap(i32(m, 12) + offset)
63
+
64
+ # patch up the bitmap height
65
+ self._size = self.size[0], self.size[1] // 2
66
+ d, e, o, a = self.tile[0]
67
+ self.tile[0] = ImageFile._Tile(d, (0, 0) + self.size, o, a)
68
+
69
+
70
+ #
71
+ # --------------------------------------------------------------------
72
+
73
+ Image.register_open(CurImageFile.format, CurImageFile, _accept)
74
+
75
+ Image.register_extension(CurImageFile.format, ".cur")
phi4/lib/python3.10/site-packages/PIL/FliImagePlugin.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # FLI/FLC file handling.
6
+ #
7
+ # History:
8
+ # 95-09-01 fl Created
9
+ # 97-01-03 fl Fixed parser, setup decoder tile
10
+ # 98-07-15 fl Renamed offset attribute to avoid name clash
11
+ #
12
+ # Copyright (c) Secret Labs AB 1997-98.
13
+ # Copyright (c) Fredrik Lundh 1995-97.
14
+ #
15
+ # See the README file for information on usage and redistribution.
16
+ #
17
+ from __future__ import annotations
18
+
19
+ import os
20
+
21
+ from . import Image, ImageFile, ImagePalette
22
+ from ._binary import i16le as i16
23
+ from ._binary import i32le as i32
24
+ from ._binary import o8
25
+
26
+ #
27
+ # decoder
28
+
29
+
30
+ def _accept(prefix: bytes) -> bool:
31
+ return (
32
+ len(prefix) >= 6
33
+ and i16(prefix, 4) in [0xAF11, 0xAF12]
34
+ and i16(prefix, 14) in [0, 3] # flags
35
+ )
36
+
37
+
38
+ ##
39
+ # Image plugin for the FLI/FLC animation format. Use the <b>seek</b>
40
+ # method to load individual frames.
41
+
42
+
43
+ class FliImageFile(ImageFile.ImageFile):
44
+ format = "FLI"
45
+ format_description = "Autodesk FLI/FLC Animation"
46
+ _close_exclusive_fp_after_loading = False
47
+
48
+ def _open(self) -> None:
49
+ # HEAD
50
+ s = self.fp.read(128)
51
+ if not (_accept(s) and s[20:22] == b"\x00\x00"):
52
+ msg = "not an FLI/FLC file"
53
+ raise SyntaxError(msg)
54
+
55
+ # frames
56
+ self.n_frames = i16(s, 6)
57
+ self.is_animated = self.n_frames > 1
58
+
59
+ # image characteristics
60
+ self._mode = "P"
61
+ self._size = i16(s, 8), i16(s, 10)
62
+
63
+ # animation speed
64
+ duration = i32(s, 16)
65
+ magic = i16(s, 4)
66
+ if magic == 0xAF11:
67
+ duration = (duration * 1000) // 70
68
+ self.info["duration"] = duration
69
+
70
+ # look for palette
71
+ palette = [(a, a, a) for a in range(256)]
72
+
73
+ s = self.fp.read(16)
74
+
75
+ self.__offset = 128
76
+
77
+ if i16(s, 4) == 0xF100:
78
+ # prefix chunk; ignore it
79
+ self.__offset = self.__offset + i32(s)
80
+ self.fp.seek(self.__offset)
81
+ s = self.fp.read(16)
82
+
83
+ if i16(s, 4) == 0xF1FA:
84
+ # look for palette chunk
85
+ number_of_subchunks = i16(s, 6)
86
+ chunk_size: int | None = None
87
+ for _ in range(number_of_subchunks):
88
+ if chunk_size is not None:
89
+ self.fp.seek(chunk_size - 6, os.SEEK_CUR)
90
+ s = self.fp.read(6)
91
+ chunk_type = i16(s, 4)
92
+ if chunk_type in (4, 11):
93
+ self._palette(palette, 2 if chunk_type == 11 else 0)
94
+ break
95
+ chunk_size = i32(s)
96
+ if not chunk_size:
97
+ break
98
+
99
+ self.palette = ImagePalette.raw(
100
+ "RGB", b"".join(o8(r) + o8(g) + o8(b) for (r, g, b) in palette)
101
+ )
102
+
103
+ # set things up to decode first frame
104
+ self.__frame = -1
105
+ self._fp = self.fp
106
+ self.__rewind = self.fp.tell()
107
+ self.seek(0)
108
+
109
+ def _palette(self, palette: list[tuple[int, int, int]], shift: int) -> None:
110
+ # load palette
111
+
112
+ i = 0
113
+ for e in range(i16(self.fp.read(2))):
114
+ s = self.fp.read(2)
115
+ i = i + s[0]
116
+ n = s[1]
117
+ if n == 0:
118
+ n = 256
119
+ s = self.fp.read(n * 3)
120
+ for n in range(0, len(s), 3):
121
+ r = s[n] << shift
122
+ g = s[n + 1] << shift
123
+ b = s[n + 2] << shift
124
+ palette[i] = (r, g, b)
125
+ i += 1
126
+
127
+ def seek(self, frame: int) -> None:
128
+ if not self._seek_check(frame):
129
+ return
130
+ if frame < self.__frame:
131
+ self._seek(0)
132
+
133
+ for f in range(self.__frame + 1, frame + 1):
134
+ self._seek(f)
135
+
136
+ def _seek(self, frame: int) -> None:
137
+ if frame == 0:
138
+ self.__frame = -1
139
+ self._fp.seek(self.__rewind)
140
+ self.__offset = 128
141
+ else:
142
+ # ensure that the previous frame was loaded
143
+ self.load()
144
+
145
+ if frame != self.__frame + 1:
146
+ msg = f"cannot seek to frame {frame}"
147
+ raise ValueError(msg)
148
+ self.__frame = frame
149
+
150
+ # move to next frame
151
+ self.fp = self._fp
152
+ self.fp.seek(self.__offset)
153
+
154
+ s = self.fp.read(4)
155
+ if not s:
156
+ msg = "missing frame size"
157
+ raise EOFError(msg)
158
+
159
+ framesize = i32(s)
160
+
161
+ self.decodermaxblock = framesize
162
+ self.tile = [ImageFile._Tile("fli", (0, 0) + self.size, self.__offset)]
163
+
164
+ self.__offset += framesize
165
+
166
+ def tell(self) -> int:
167
+ return self.__frame
168
+
169
+
170
+ #
171
+ # registry
172
+
173
+ Image.register_open(FliImageFile.format, FliImageFile, _accept)
174
+
175
+ Image.register_extensions(FliImageFile.format, [".fli", ".flc"])
phi4/lib/python3.10/site-packages/PIL/FontFile.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library
3
+ # $Id$
4
+ #
5
+ # base class for raster font file parsers
6
+ #
7
+ # history:
8
+ # 1997-06-05 fl created
9
+ # 1997-08-19 fl restrict image width
10
+ #
11
+ # Copyright (c) 1997-1998 by Secret Labs AB
12
+ # Copyright (c) 1997-1998 by Fredrik Lundh
13
+ #
14
+ # See the README file for information on usage and redistribution.
15
+ #
16
+ from __future__ import annotations
17
+
18
+ import os
19
+ from typing import BinaryIO
20
+
21
+ from . import Image, _binary
22
+
23
+ WIDTH = 800
24
+
25
+
26
+ def puti16(
27
+ fp: BinaryIO, values: tuple[int, int, int, int, int, int, int, int, int, int]
28
+ ) -> None:
29
+ """Write network order (big-endian) 16-bit sequence"""
30
+ for v in values:
31
+ if v < 0:
32
+ v += 65536
33
+ fp.write(_binary.o16be(v))
34
+
35
+
36
+ class FontFile:
37
+ """Base class for raster font file handlers."""
38
+
39
+ bitmap: Image.Image | None = None
40
+
41
+ def __init__(self) -> None:
42
+ self.info: dict[bytes, bytes | int] = {}
43
+ self.glyph: list[
44
+ tuple[
45
+ tuple[int, int],
46
+ tuple[int, int, int, int],
47
+ tuple[int, int, int, int],
48
+ Image.Image,
49
+ ]
50
+ | None
51
+ ] = [None] * 256
52
+
53
+ def __getitem__(self, ix: int) -> (
54
+ tuple[
55
+ tuple[int, int],
56
+ tuple[int, int, int, int],
57
+ tuple[int, int, int, int],
58
+ Image.Image,
59
+ ]
60
+ | None
61
+ ):
62
+ return self.glyph[ix]
63
+
64
+ def compile(self) -> None:
65
+ """Create metrics and bitmap"""
66
+
67
+ if self.bitmap:
68
+ return
69
+
70
+ # create bitmap large enough to hold all data
71
+ h = w = maxwidth = 0
72
+ lines = 1
73
+ for glyph in self.glyph:
74
+ if glyph:
75
+ d, dst, src, im = glyph
76
+ h = max(h, src[3] - src[1])
77
+ w = w + (src[2] - src[0])
78
+ if w > WIDTH:
79
+ lines += 1
80
+ w = src[2] - src[0]
81
+ maxwidth = max(maxwidth, w)
82
+
83
+ xsize = maxwidth
84
+ ysize = lines * h
85
+
86
+ if xsize == 0 and ysize == 0:
87
+ return
88
+
89
+ self.ysize = h
90
+
91
+ # paste glyphs into bitmap
92
+ self.bitmap = Image.new("1", (xsize, ysize))
93
+ self.metrics: list[
94
+ tuple[tuple[int, int], tuple[int, int, int, int], tuple[int, int, int, int]]
95
+ | None
96
+ ] = [None] * 256
97
+ x = y = 0
98
+ for i in range(256):
99
+ glyph = self[i]
100
+ if glyph:
101
+ d, dst, src, im = glyph
102
+ xx = src[2] - src[0]
103
+ x0, y0 = x, y
104
+ x = x + xx
105
+ if x > WIDTH:
106
+ x, y = 0, y + h
107
+ x0, y0 = x, y
108
+ x = xx
109
+ s = src[0] + x0, src[1] + y0, src[2] + x0, src[3] + y0
110
+ self.bitmap.paste(im.crop(src), s)
111
+ self.metrics[i] = d, dst, s
112
+
113
+ def save(self, filename: str) -> None:
114
+ """Save font"""
115
+
116
+ self.compile()
117
+
118
+ # font data
119
+ if not self.bitmap:
120
+ msg = "No bitmap created"
121
+ raise ValueError(msg)
122
+ self.bitmap.save(os.path.splitext(filename)[0] + ".pbm", "PNG")
123
+
124
+ # font metrics
125
+ with open(os.path.splitext(filename)[0] + ".pil", "wb") as fp:
126
+ fp.write(b"PILfont\n")
127
+ fp.write(f";;;;;;{self.ysize};\n".encode("ascii")) # HACK!!!
128
+ fp.write(b"DATA\n")
129
+ for id in range(256):
130
+ m = self.metrics[id]
131
+ if not m:
132
+ puti16(fp, (0,) * 10)
133
+ else:
134
+ puti16(fp, m[0] + m[1] + m[2])
phi4/lib/python3.10/site-packages/PIL/GribStubImagePlugin.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library
3
+ # $Id$
4
+ #
5
+ # GRIB stub adapter
6
+ #
7
+ # Copyright (c) 1996-2003 by Fredrik Lundh
8
+ #
9
+ # See the README file for information on usage and redistribution.
10
+ #
11
+ from __future__ import annotations
12
+
13
+ from typing import IO
14
+
15
+ from . import Image, ImageFile
16
+
17
+ _handler = None
18
+
19
+
20
+ def register_handler(handler: ImageFile.StubHandler | None) -> None:
21
+ """
22
+ Install application-specific GRIB image handler.
23
+
24
+ :param handler: Handler object.
25
+ """
26
+ global _handler
27
+ _handler = handler
28
+
29
+
30
+ # --------------------------------------------------------------------
31
+ # Image adapter
32
+
33
+
34
+ def _accept(prefix: bytes) -> bool:
35
+ return prefix[:4] == b"GRIB" and prefix[7] == 1
36
+
37
+
38
+ class GribStubImageFile(ImageFile.StubImageFile):
39
+ format = "GRIB"
40
+ format_description = "GRIB"
41
+
42
+ def _open(self) -> None:
43
+ offset = self.fp.tell()
44
+
45
+ if not _accept(self.fp.read(8)):
46
+ msg = "Not a GRIB file"
47
+ raise SyntaxError(msg)
48
+
49
+ self.fp.seek(offset)
50
+
51
+ # make something up
52
+ self._mode = "F"
53
+ self._size = 1, 1
54
+
55
+ loader = self._load()
56
+ if loader:
57
+ loader.open(self)
58
+
59
+ def _load(self) -> ImageFile.StubHandler | None:
60
+ return _handler
61
+
62
+
63
+ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
64
+ if _handler is None or not hasattr(_handler, "save"):
65
+ msg = "GRIB save handler not installed"
66
+ raise OSError(msg)
67
+ _handler.save(im, fp, filename)
68
+
69
+
70
+ # --------------------------------------------------------------------
71
+ # Registry
72
+
73
+ Image.register_open(GribStubImageFile.format, GribStubImageFile, _accept)
74
+ Image.register_save(GribStubImageFile.format, _save)
75
+
76
+ Image.register_extension(GribStubImageFile.format, ".grib")
phi4/lib/python3.10/site-packages/PIL/IcoImagePlugin.py ADDED
@@ -0,0 +1,381 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # Windows Icon support for PIL
6
+ #
7
+ # History:
8
+ # 96-05-27 fl Created
9
+ #
10
+ # Copyright (c) Secret Labs AB 1997.
11
+ # Copyright (c) Fredrik Lundh 1996.
12
+ #
13
+ # See the README file for information on usage and redistribution.
14
+ #
15
+
16
+ # This plugin is a refactored version of Win32IconImagePlugin by Bryan Davis
17
+ # <casadebender@gmail.com>.
18
+ # https://code.google.com/archive/p/casadebender/wikis/Win32IconImagePlugin.wiki
19
+ #
20
+ # Icon format references:
21
+ # * https://en.wikipedia.org/wiki/ICO_(file_format)
22
+ # * https://msdn.microsoft.com/en-us/library/ms997538.aspx
23
+ from __future__ import annotations
24
+
25
+ import warnings
26
+ from io import BytesIO
27
+ from math import ceil, log
28
+ from typing import IO, NamedTuple
29
+
30
+ from . import BmpImagePlugin, Image, ImageFile, PngImagePlugin
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
+
40
+ _MAGIC = b"\0\0\1\0"
41
+
42
+
43
+ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
44
+ fp.write(_MAGIC) # (2+2)
45
+ bmp = im.encoderinfo.get("bitmap_format") == "bmp"
46
+ sizes = im.encoderinfo.get(
47
+ "sizes",
48
+ [(16, 16), (24, 24), (32, 32), (48, 48), (64, 64), (128, 128), (256, 256)],
49
+ )
50
+ frames = []
51
+ provided_ims = [im] + im.encoderinfo.get("append_images", [])
52
+ width, height = im.size
53
+ for size in sorted(set(sizes)):
54
+ if size[0] > width or size[1] > height or size[0] > 256 or size[1] > 256:
55
+ continue
56
+
57
+ for provided_im in provided_ims:
58
+ if provided_im.size != size:
59
+ continue
60
+ frames.append(provided_im)
61
+ if bmp:
62
+ bits = BmpImagePlugin.SAVE[provided_im.mode][1]
63
+ bits_used = [bits]
64
+ for other_im in provided_ims:
65
+ if other_im.size != size:
66
+ continue
67
+ bits = BmpImagePlugin.SAVE[other_im.mode][1]
68
+ if bits not in bits_used:
69
+ # Another image has been supplied for this size
70
+ # with a different bit depth
71
+ frames.append(other_im)
72
+ bits_used.append(bits)
73
+ break
74
+ else:
75
+ # TODO: invent a more convenient method for proportional scalings
76
+ frame = provided_im.copy()
77
+ frame.thumbnail(size, Image.Resampling.LANCZOS, reducing_gap=None)
78
+ frames.append(frame)
79
+ fp.write(o16(len(frames))) # idCount(2)
80
+ offset = fp.tell() + len(frames) * 16
81
+ for frame in frames:
82
+ width, height = frame.size
83
+ # 0 means 256
84
+ fp.write(o8(width if width < 256 else 0)) # bWidth(1)
85
+ fp.write(o8(height if height < 256 else 0)) # bHeight(1)
86
+
87
+ bits, colors = BmpImagePlugin.SAVE[frame.mode][1:] if bmp else (32, 0)
88
+ fp.write(o8(colors)) # bColorCount(1)
89
+ fp.write(b"\0") # bReserved(1)
90
+ fp.write(b"\0\0") # wPlanes(2)
91
+ fp.write(o16(bits)) # wBitCount(2)
92
+
93
+ image_io = BytesIO()
94
+ if bmp:
95
+ frame.save(image_io, "dib")
96
+
97
+ if bits != 32:
98
+ and_mask = Image.new("1", size)
99
+ ImageFile._save(
100
+ and_mask,
101
+ image_io,
102
+ [ImageFile._Tile("raw", (0, 0) + size, 0, ("1", 0, -1))],
103
+ )
104
+ else:
105
+ frame.save(image_io, "png")
106
+ image_io.seek(0)
107
+ image_bytes = image_io.read()
108
+ if bmp:
109
+ image_bytes = image_bytes[:8] + o32(height * 2) + image_bytes[12:]
110
+ bytes_len = len(image_bytes)
111
+ fp.write(o32(bytes_len)) # dwBytesInRes(4)
112
+ fp.write(o32(offset)) # dwImageOffset(4)
113
+ current = fp.tell()
114
+ fp.seek(offset)
115
+ fp.write(image_bytes)
116
+ offset = offset + bytes_len
117
+ fp.seek(current)
118
+
119
+
120
+ def _accept(prefix: bytes) -> bool:
121
+ return prefix[:4] == _MAGIC
122
+
123
+
124
+ class IconHeader(NamedTuple):
125
+ width: int
126
+ height: int
127
+ nb_color: int
128
+ reserved: int
129
+ planes: int
130
+ bpp: int
131
+ size: int
132
+ offset: int
133
+ dim: tuple[int, int]
134
+ square: int
135
+ color_depth: int
136
+
137
+
138
+ class IcoFile:
139
+ def __init__(self, buf: IO[bytes]) -> None:
140
+ """
141
+ Parse image from file-like object containing ico file data
142
+ """
143
+
144
+ # check magic
145
+ s = buf.read(6)
146
+ if not _accept(s):
147
+ msg = "not an ICO file"
148
+ raise SyntaxError(msg)
149
+
150
+ self.buf = buf
151
+ self.entry = []
152
+
153
+ # Number of items in file
154
+ self.nb_items = i16(s, 4)
155
+
156
+ # Get headers for each item
157
+ for i in range(self.nb_items):
158
+ s = buf.read(16)
159
+
160
+ # See Wikipedia
161
+ width = s[0] or 256
162
+ height = s[1] or 256
163
+
164
+ # No. of colors in image (0 if >=8bpp)
165
+ nb_color = s[2]
166
+ bpp = i16(s, 6)
167
+ icon_header = IconHeader(
168
+ width=width,
169
+ height=height,
170
+ nb_color=nb_color,
171
+ reserved=s[3],
172
+ planes=i16(s, 4),
173
+ bpp=i16(s, 6),
174
+ size=i32(s, 8),
175
+ offset=i32(s, 12),
176
+ dim=(width, height),
177
+ square=width * height,
178
+ # See Wikipedia notes about color depth.
179
+ # We need this just to differ images with equal sizes
180
+ color_depth=bpp or (nb_color != 0 and ceil(log(nb_color, 2))) or 256,
181
+ )
182
+
183
+ self.entry.append(icon_header)
184
+
185
+ self.entry = sorted(self.entry, key=lambda x: x.color_depth)
186
+ # ICO images are usually squares
187
+ self.entry = sorted(self.entry, key=lambda x: x.square, reverse=True)
188
+
189
+ def sizes(self) -> set[tuple[int, int]]:
190
+ """
191
+ Get a set of all available icon sizes and color depths.
192
+ """
193
+ return {(h.width, h.height) for h in self.entry}
194
+
195
+ def getentryindex(self, size: tuple[int, int], bpp: int | bool = False) -> int:
196
+ for i, h in enumerate(self.entry):
197
+ if size == h.dim and (bpp is False or bpp == h.color_depth):
198
+ return i
199
+ return 0
200
+
201
+ def getimage(self, size: tuple[int, int], bpp: int | bool = False) -> Image.Image:
202
+ """
203
+ Get an image from the icon
204
+ """
205
+ return self.frame(self.getentryindex(size, bpp))
206
+
207
+ def frame(self, idx: int) -> Image.Image:
208
+ """
209
+ Get an image from frame idx
210
+ """
211
+
212
+ header = self.entry[idx]
213
+
214
+ self.buf.seek(header.offset)
215
+ data = self.buf.read(8)
216
+ self.buf.seek(header.offset)
217
+
218
+ im: Image.Image
219
+ if data[:8] == PngImagePlugin._MAGIC:
220
+ # png frame
221
+ im = PngImagePlugin.PngImageFile(self.buf)
222
+ Image._decompression_bomb_check(im.size)
223
+ else:
224
+ # XOR + AND mask bmp frame
225
+ im = BmpImagePlugin.DibImageFile(self.buf)
226
+ Image._decompression_bomb_check(im.size)
227
+
228
+ # change tile dimension to only encompass XOR image
229
+ im._size = (im.size[0], int(im.size[1] / 2))
230
+ d, e, o, a = im.tile[0]
231
+ im.tile[0] = ImageFile._Tile(d, (0, 0) + im.size, o, a)
232
+
233
+ # figure out where AND mask image starts
234
+ if header.bpp == 32:
235
+ # 32-bit color depth icon image allows semitransparent areas
236
+ # PIL's DIB format ignores transparency bits, recover them.
237
+ # The DIB is packed in BGRX byte order where X is the alpha
238
+ # channel.
239
+
240
+ # Back up to start of bmp data
241
+ self.buf.seek(o)
242
+ # extract every 4th byte (eg. 3,7,11,15,...)
243
+ alpha_bytes = self.buf.read(im.size[0] * im.size[1] * 4)[3::4]
244
+
245
+ # convert to an 8bpp grayscale image
246
+ try:
247
+ mask = Image.frombuffer(
248
+ "L", # 8bpp
249
+ im.size, # (w, h)
250
+ alpha_bytes, # source chars
251
+ "raw", # raw decoder
252
+ ("L", 0, -1), # 8bpp inverted, unpadded, reversed
253
+ )
254
+ except ValueError:
255
+ if ImageFile.LOAD_TRUNCATED_IMAGES:
256
+ mask = None
257
+ else:
258
+ raise
259
+ else:
260
+ # get AND image from end of bitmap
261
+ w = im.size[0]
262
+ if (w % 32) > 0:
263
+ # bitmap row data is aligned to word boundaries
264
+ w += 32 - (im.size[0] % 32)
265
+
266
+ # the total mask data is
267
+ # padded row size * height / bits per char
268
+
269
+ total_bytes = int((w * im.size[1]) / 8)
270
+ and_mask_offset = header.offset + header.size - total_bytes
271
+
272
+ self.buf.seek(and_mask_offset)
273
+ mask_data = self.buf.read(total_bytes)
274
+
275
+ # convert raw data to image
276
+ try:
277
+ mask = Image.frombuffer(
278
+ "1", # 1 bpp
279
+ im.size, # (w, h)
280
+ mask_data, # source chars
281
+ "raw", # raw decoder
282
+ ("1;I", int(w / 8), -1), # 1bpp inverted, padded, reversed
283
+ )
284
+ except ValueError:
285
+ if ImageFile.LOAD_TRUNCATED_IMAGES:
286
+ mask = None
287
+ else:
288
+ raise
289
+
290
+ # now we have two images, im is XOR image and mask is AND image
291
+
292
+ # apply mask image as alpha channel
293
+ if mask:
294
+ im = im.convert("RGBA")
295
+ im.putalpha(mask)
296
+
297
+ return im
298
+
299
+
300
+ ##
301
+ # Image plugin for Windows Icon files.
302
+
303
+
304
+ class IcoImageFile(ImageFile.ImageFile):
305
+ """
306
+ PIL read-only image support for Microsoft Windows .ico files.
307
+
308
+ By default the largest resolution image in the file will be loaded. This
309
+ can be changed by altering the 'size' attribute before calling 'load'.
310
+
311
+ The info dictionary has a key 'sizes' that is a list of the sizes available
312
+ in the icon file.
313
+
314
+ Handles classic, XP and Vista icon formats.
315
+
316
+ When saving, PNG compression is used. Support for this was only added in
317
+ Windows Vista. If you are unable to view the icon in Windows, convert the
318
+ image to "RGBA" mode before saving.
319
+
320
+ This plugin is a refactored version of Win32IconImagePlugin by Bryan Davis
321
+ <casadebender@gmail.com>.
322
+ https://code.google.com/archive/p/casadebender/wikis/Win32IconImagePlugin.wiki
323
+ """
324
+
325
+ format = "ICO"
326
+ format_description = "Windows Icon"
327
+
328
+ def _open(self) -> None:
329
+ self.ico = IcoFile(self.fp)
330
+ self.info["sizes"] = self.ico.sizes()
331
+ self.size = self.ico.entry[0].dim
332
+ self.load()
333
+
334
+ @property
335
+ def size(self) -> tuple[int, int]:
336
+ return self._size
337
+
338
+ @size.setter
339
+ def size(self, value: tuple[int, int]) -> None:
340
+ if value not in self.info["sizes"]:
341
+ msg = "This is not one of the allowed sizes of this image"
342
+ raise ValueError(msg)
343
+ self._size = value
344
+
345
+ def load(self) -> Image.core.PixelAccess | None:
346
+ if self._im is not None and self.im.size == self.size:
347
+ # Already loaded
348
+ return Image.Image.load(self)
349
+ im = self.ico.getimage(self.size)
350
+ # if tile is PNG, it won't really be loaded yet
351
+ im.load()
352
+ self.im = im.im
353
+ self._mode = im.mode
354
+ if im.palette:
355
+ self.palette = im.palette
356
+ if im.size != self.size:
357
+ warnings.warn("Image was not the expected size")
358
+
359
+ index = self.ico.getentryindex(self.size)
360
+ sizes = list(self.info["sizes"])
361
+ sizes[index] = im.size
362
+ self.info["sizes"] = set(sizes)
363
+
364
+ self.size = im.size
365
+ return None
366
+
367
+ def load_seek(self, pos: int) -> None:
368
+ # Flag the ImageFile.Parser so that it
369
+ # just does all the decode at the end.
370
+ pass
371
+
372
+
373
+ #
374
+ # --------------------------------------------------------------------
375
+
376
+
377
+ Image.register_open(IcoImageFile.format, IcoImageFile, _accept)
378
+ Image.register_save(IcoImageFile.format, _save)
379
+ Image.register_extension(IcoImageFile.format, ".ico")
380
+
381
+ Image.register_mime(IcoImageFile.format, "image/x-icon")
phi4/lib/python3.10/site-packages/PIL/ImImagePlugin.py ADDED
@@ -0,0 +1,386 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
35
+ # --------------------------------------------------------------------
36
+ # Standard tags
37
+
38
+ COMMENT = "Comment"
39
+ DATE = "Date"
40
+ EQUIPMENT = "Digitalization equipment"
41
+ FRAMES = "File size (no of images)"
42
+ LUT = "Lut"
43
+ NAME = "Name"
44
+ SCALE = "Scale (x,y)"
45
+ SIZE = "Image size (x*y)"
46
+ MODE = "Image type"
47
+
48
+ TAGS = {
49
+ COMMENT: 0,
50
+ DATE: 0,
51
+ EQUIPMENT: 0,
52
+ FRAMES: 0,
53
+ LUT: 0,
54
+ NAME: 0,
55
+ SCALE: 0,
56
+ SIZE: 0,
57
+ MODE: 0,
58
+ }
59
+
60
+ OPEN = {
61
+ # ifunc93/p3cfunc formats
62
+ "0 1 image": ("1", "1"),
63
+ "L 1 image": ("1", "1"),
64
+ "Greyscale image": ("L", "L"),
65
+ "Grayscale image": ("L", "L"),
66
+ "RGB image": ("RGB", "RGB;L"),
67
+ "RLB image": ("RGB", "RLB"),
68
+ "RYB image": ("RGB", "RLB"),
69
+ "B1 image": ("1", "1"),
70
+ "B2 image": ("P", "P;2"),
71
+ "B4 image": ("P", "P;4"),
72
+ "X 24 image": ("RGB", "RGB"),
73
+ "L 32 S image": ("I", "I;32"),
74
+ "L 32 F image": ("F", "F;32"),
75
+ # old p3cfunc formats
76
+ "RGB3 image": ("RGB", "RGB;T"),
77
+ "RYB3 image": ("RGB", "RYB;T"),
78
+ # extensions
79
+ "LA image": ("LA", "LA;L"),
80
+ "PA image": ("LA", "PA;L"),
81
+ "RGBA image": ("RGBA", "RGBA;L"),
82
+ "RGBX image": ("RGB", "RGBX;L"),
83
+ "CMYK image": ("CMYK", "CMYK;L"),
84
+ "YCC image": ("YCbCr", "YCbCr;L"),
85
+ }
86
+
87
+ # ifunc95 extensions
88
+ for i in ["8", "8S", "16", "16S", "32", "32F"]:
89
+ OPEN[f"L {i} image"] = ("F", f"F;{i}")
90
+ OPEN[f"L*{i} image"] = ("F", f"F;{i}")
91
+ for i in ["16", "16L", "16B"]:
92
+ OPEN[f"L {i} image"] = (f"I;{i}", f"I;{i}")
93
+ OPEN[f"L*{i} image"] = (f"I;{i}", f"I;{i}")
94
+ for i in ["32S"]:
95
+ OPEN[f"L {i} image"] = ("I", f"I;{i}")
96
+ OPEN[f"L*{i} image"] = ("I", f"I;{i}")
97
+ for j in range(2, 33):
98
+ OPEN[f"L*{j} image"] = ("F", f"F;{j}")
99
+
100
+
101
+ # --------------------------------------------------------------------
102
+ # Read IM directory
103
+
104
+ split = re.compile(rb"^([A-Za-z][^:]*):[ \t]*(.*)[ \t]*$")
105
+
106
+
107
+ def number(s: Any) -> float:
108
+ try:
109
+ return int(s)
110
+ except ValueError:
111
+ return float(s)
112
+
113
+
114
+ ##
115
+ # Image plugin for the IFUNC IM file format.
116
+
117
+
118
+ class ImImageFile(ImageFile.ImageFile):
119
+ format = "IM"
120
+ format_description = "IFUNC Image Memory"
121
+ _close_exclusive_fp_after_loading = False
122
+
123
+ def _open(self) -> None:
124
+ # Quick rejection: if there's not an LF among the first
125
+ # 100 bytes, this is (probably) not a text header.
126
+
127
+ if b"\n" not in self.fp.read(100):
128
+ msg = "not an IM file"
129
+ raise SyntaxError(msg)
130
+ self.fp.seek(0)
131
+
132
+ n = 0
133
+
134
+ # Default values
135
+ self.info[MODE] = "L"
136
+ self.info[SIZE] = (512, 512)
137
+ self.info[FRAMES] = 1
138
+
139
+ self.rawmode = "L"
140
+
141
+ while True:
142
+ s = self.fp.read(1)
143
+
144
+ # Some versions of IFUNC uses \n\r instead of \r\n...
145
+ if s == b"\r":
146
+ continue
147
+
148
+ if not s or s == b"\0" or s == b"\x1A":
149
+ break
150
+
151
+ # FIXME: this may read whole file if not a text file
152
+ s = s + self.fp.readline()
153
+
154
+ if len(s) > 100:
155
+ msg = "not an IM file"
156
+ raise SyntaxError(msg)
157
+
158
+ if s[-2:] == b"\r\n":
159
+ s = s[:-2]
160
+ elif s[-1:] == b"\n":
161
+ s = s[:-1]
162
+
163
+ try:
164
+ m = split.match(s)
165
+ except re.error as e:
166
+ msg = "not an IM file"
167
+ raise SyntaxError(msg) from e
168
+
169
+ if m:
170
+ k, v = m.group(1, 2)
171
+
172
+ # Don't know if this is the correct encoding,
173
+ # but a decent guess (I guess)
174
+ k = k.decode("latin-1", "replace")
175
+ v = v.decode("latin-1", "replace")
176
+
177
+ # Convert value as appropriate
178
+ if k in [FRAMES, SCALE, SIZE]:
179
+ v = v.replace("*", ",")
180
+ v = tuple(map(number, v.split(",")))
181
+ if len(v) == 1:
182
+ v = v[0]
183
+ elif k == MODE and v in OPEN:
184
+ v, self.rawmode = OPEN[v]
185
+
186
+ # Add to dictionary. Note that COMMENT tags are
187
+ # combined into a list of strings.
188
+ if k == COMMENT:
189
+ if k in self.info:
190
+ self.info[k].append(v)
191
+ else:
192
+ self.info[k] = [v]
193
+ else:
194
+ self.info[k] = v
195
+
196
+ if k in TAGS:
197
+ n += 1
198
+
199
+ else:
200
+ msg = f"Syntax error in IM header: {s.decode('ascii', 'replace')}"
201
+ raise SyntaxError(msg)
202
+
203
+ if not n:
204
+ msg = "Not an IM file"
205
+ raise SyntaxError(msg)
206
+
207
+ # Basic attributes
208
+ self._size = self.info[SIZE]
209
+ self._mode = self.info[MODE]
210
+
211
+ # Skip forward to start of image data
212
+ while s and s[:1] != b"\x1A":
213
+ s = self.fp.read(1)
214
+ if not s:
215
+ msg = "File truncated"
216
+ raise SyntaxError(msg)
217
+
218
+ if LUT in self.info:
219
+ # convert lookup table to palette or lut attribute
220
+ palette = self.fp.read(768)
221
+ greyscale = 1 # greyscale palette
222
+ linear = 1 # linear greyscale palette
223
+ for i in range(256):
224
+ if palette[i] == palette[i + 256] == palette[i + 512]:
225
+ if palette[i] != i:
226
+ linear = 0
227
+ else:
228
+ greyscale = 0
229
+ if self.mode in ["L", "LA", "P", "PA"]:
230
+ if greyscale:
231
+ if not linear:
232
+ self.lut = list(palette[:256])
233
+ else:
234
+ if self.mode in ["L", "P"]:
235
+ self._mode = self.rawmode = "P"
236
+ elif self.mode in ["LA", "PA"]:
237
+ self._mode = "PA"
238
+ self.rawmode = "PA;L"
239
+ self.palette = ImagePalette.raw("RGB;L", palette)
240
+ elif self.mode == "RGB":
241
+ if not greyscale or not linear:
242
+ self.lut = list(palette)
243
+
244
+ self.frame = 0
245
+
246
+ self.__offset = offs = self.fp.tell()
247
+
248
+ self._fp = self.fp # FIXME: hack
249
+
250
+ if self.rawmode[:2] == "F;":
251
+ # ifunc95 formats
252
+ try:
253
+ # use bit decoder (if necessary)
254
+ bits = int(self.rawmode[2:])
255
+ if bits not in [8, 16, 32]:
256
+ self.tile = [
257
+ ImageFile._Tile(
258
+ "bit", (0, 0) + self.size, offs, (bits, 8, 3, 0, -1)
259
+ )
260
+ ]
261
+ return
262
+ except ValueError:
263
+ pass
264
+
265
+ if self.rawmode in ["RGB;T", "RYB;T"]:
266
+ # Old LabEye/3PC files. Would be very surprised if anyone
267
+ # ever stumbled upon such a file ;-)
268
+ size = self.size[0] * self.size[1]
269
+ self.tile = [
270
+ ImageFile._Tile("raw", (0, 0) + self.size, offs, ("G", 0, -1)),
271
+ ImageFile._Tile("raw", (0, 0) + self.size, offs + size, ("R", 0, -1)),
272
+ ImageFile._Tile(
273
+ "raw", (0, 0) + self.size, offs + 2 * size, ("B", 0, -1)
274
+ ),
275
+ ]
276
+ else:
277
+ # LabEye/IFUNC files
278
+ self.tile = [
279
+ ImageFile._Tile("raw", (0, 0) + self.size, offs, (self.rawmode, 0, -1))
280
+ ]
281
+
282
+ @property
283
+ def n_frames(self) -> int:
284
+ return self.info[FRAMES]
285
+
286
+ @property
287
+ def is_animated(self) -> bool:
288
+ return self.info[FRAMES] > 1
289
+
290
+ def seek(self, frame: int) -> None:
291
+ if not self._seek_check(frame):
292
+ return
293
+
294
+ self.frame = frame
295
+
296
+ if self.mode == "1":
297
+ bits = 1
298
+ else:
299
+ bits = 8 * len(self.mode)
300
+
301
+ size = ((self.size[0] * bits + 7) // 8) * self.size[1]
302
+ offs = self.__offset + frame * size
303
+
304
+ self.fp = self._fp
305
+
306
+ self.tile = [
307
+ ImageFile._Tile("raw", (0, 0) + self.size, offs, (self.rawmode, 0, -1))
308
+ ]
309
+
310
+ def tell(self) -> int:
311
+ return self.frame
312
+
313
+
314
+ #
315
+ # --------------------------------------------------------------------
316
+ # Save IM files
317
+
318
+
319
+ SAVE = {
320
+ # mode: (im type, raw mode)
321
+ "1": ("0 1", "1"),
322
+ "L": ("Greyscale", "L"),
323
+ "LA": ("LA", "LA;L"),
324
+ "P": ("Greyscale", "P"),
325
+ "PA": ("LA", "PA;L"),
326
+ "I": ("L 32S", "I;32S"),
327
+ "I;16": ("L 16", "I;16"),
328
+ "I;16L": ("L 16L", "I;16L"),
329
+ "I;16B": ("L 16B", "I;16B"),
330
+ "F": ("L 32F", "F;32F"),
331
+ "RGB": ("RGB", "RGB;L"),
332
+ "RGBA": ("RGBA", "RGBA;L"),
333
+ "RGBX": ("RGBX", "RGBX;L"),
334
+ "CMYK": ("CMYK", "CMYK;L"),
335
+ "YCbCr": ("YCC", "YCbCr;L"),
336
+ }
337
+
338
+
339
+ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
340
+ try:
341
+ image_type, rawmode = SAVE[im.mode]
342
+ except KeyError as e:
343
+ msg = f"Cannot save {im.mode} images as IM"
344
+ raise ValueError(msg) from e
345
+
346
+ frames = im.encoderinfo.get("frames", 1)
347
+
348
+ fp.write(f"Image type: {image_type} image\r\n".encode("ascii"))
349
+ if filename:
350
+ # Each line must be 100 characters or less,
351
+ # or: SyntaxError("not an IM file")
352
+ # 8 characters are used for "Name: " and "\r\n"
353
+ # Keep just the filename, ditch the potentially overlong path
354
+ if isinstance(filename, bytes):
355
+ filename = filename.decode("ascii")
356
+ name, ext = os.path.splitext(os.path.basename(filename))
357
+ name = "".join([name[: 92 - len(ext)], ext])
358
+
359
+ fp.write(f"Name: {name}\r\n".encode("ascii"))
360
+ fp.write(f"Image size (x*y): {im.size[0]}*{im.size[1]}\r\n".encode("ascii"))
361
+ fp.write(f"File size (no of images): {frames}\r\n".encode("ascii"))
362
+ if im.mode in ["P", "PA"]:
363
+ fp.write(b"Lut: 1\r\n")
364
+ fp.write(b"\000" * (511 - fp.tell()) + b"\032")
365
+ if im.mode in ["P", "PA"]:
366
+ im_palette = im.im.getpalette("RGB", "RGB;L")
367
+ colors = len(im_palette) // 3
368
+ palette = b""
369
+ for i in range(3):
370
+ palette += im_palette[colors * i : colors * (i + 1)]
371
+ palette += b"\x00" * (256 - colors)
372
+ fp.write(palette) # 768 bytes
373
+ ImageFile._save(
374
+ im, fp, [ImageFile._Tile("raw", (0, 0) + im.size, 0, (rawmode, 0, -1))]
375
+ )
376
+
377
+
378
+ #
379
+ # --------------------------------------------------------------------
380
+ # Registry
381
+
382
+
383
+ Image.register_open(ImImageFile.format, ImImageFile)
384
+ Image.register_save(ImImageFile.format, _save)
385
+
386
+ Image.register_extension(ImImageFile.format, ".im")
phi4/lib/python3.10/site-packages/PIL/ImageCms.py ADDED
@@ -0,0 +1,1125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # The Python Imaging Library.
2
+ # $Id$
3
+
4
+ # Optional color management support, based on Kevin Cazabon's PyCMS
5
+ # library.
6
+
7
+ # Originally released under LGPL. Graciously donated to PIL in
8
+ # March 2009, for distribution under the standard PIL license
9
+
10
+ # History:
11
+
12
+ # 2009-03-08 fl Added to PIL.
13
+
14
+ # Copyright (C) 2002-2003 Kevin Cazabon
15
+ # Copyright (c) 2009 by Fredrik Lundh
16
+ # Copyright (c) 2013 by Eric Soroos
17
+
18
+ # See the README file for information on usage and redistribution. See
19
+ # below for the original description.
20
+ from __future__ import annotations
21
+
22
+ import operator
23
+ import sys
24
+ from enum import IntEnum, IntFlag
25
+ from functools import reduce
26
+ from typing import Any, Literal, SupportsFloat, SupportsInt, Union
27
+
28
+ from . import Image, __version__
29
+ from ._deprecate import deprecate
30
+ from ._typing import SupportsRead
31
+
32
+ try:
33
+ from . import _imagingcms as core
34
+
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
+ def __getattr__(name: str) -> Any:
112
+ if name == "DESCRIPTION":
113
+ deprecate("PIL.ImageCms.DESCRIPTION", 12)
114
+ return _DESCRIPTION
115
+ elif name == "VERSION":
116
+ deprecate("PIL.ImageCms.VERSION", 12)
117
+ return _VERSION
118
+ elif name == "FLAGS":
119
+ deprecate("PIL.ImageCms.FLAGS", 12, "PIL.ImageCms.Flags")
120
+ return _FLAGS
121
+ msg = f"module '{__name__}' has no attribute '{name}'"
122
+ raise AttributeError(msg)
123
+
124
+
125
+ # --------------------------------------------------------------------.
126
+
127
+
128
+ #
129
+ # intent/direction values
130
+
131
+
132
+ class Intent(IntEnum):
133
+ PERCEPTUAL = 0
134
+ RELATIVE_COLORIMETRIC = 1
135
+ SATURATION = 2
136
+ ABSOLUTE_COLORIMETRIC = 3
137
+
138
+
139
+ class Direction(IntEnum):
140
+ INPUT = 0
141
+ OUTPUT = 1
142
+ PROOF = 2
143
+
144
+
145
+ #
146
+ # flags
147
+
148
+
149
+ class Flags(IntFlag):
150
+ """Flags and documentation are taken from ``lcms2.h``."""
151
+
152
+ NONE = 0
153
+ NOCACHE = 0x0040
154
+ """Inhibit 1-pixel cache"""
155
+ NOOPTIMIZE = 0x0100
156
+ """Inhibit optimizations"""
157
+ NULLTRANSFORM = 0x0200
158
+ """Don't transform anyway"""
159
+ GAMUTCHECK = 0x1000
160
+ """Out of Gamut alarm"""
161
+ SOFTPROOFING = 0x4000
162
+ """Do softproofing"""
163
+ BLACKPOINTCOMPENSATION = 0x2000
164
+ NOWHITEONWHITEFIXUP = 0x0004
165
+ """Don't fix scum dot"""
166
+ HIGHRESPRECALC = 0x0400
167
+ """Use more memory to give better accuracy"""
168
+ LOWRESPRECALC = 0x0800
169
+ """Use less memory to minimize resources"""
170
+ # this should be 8BITS_DEVICELINK, but that is not a valid name in Python:
171
+ USE_8BITS_DEVICELINK = 0x0008
172
+ """Create 8 bits devicelinks"""
173
+ GUESSDEVICECLASS = 0x0020
174
+ """Guess device class (for ``transform2devicelink``)"""
175
+ KEEP_SEQUENCE = 0x0080
176
+ """Keep profile sequence for devicelink creation"""
177
+ FORCE_CLUT = 0x0002
178
+ """Force CLUT optimization"""
179
+ CLUT_POST_LINEARIZATION = 0x0001
180
+ """create postlinearization tables if possible"""
181
+ CLUT_PRE_LINEARIZATION = 0x0010
182
+ """create prelinearization tables if possible"""
183
+ NONEGATIVES = 0x8000
184
+ """Prevent negative numbers in floating point transforms"""
185
+ COPY_ALPHA = 0x04000000
186
+ """Alpha channels are copied on ``cmsDoTransform()``"""
187
+ NODEFAULTRESOURCEDEF = 0x01000000
188
+
189
+ _GRIDPOINTS_1 = 1 << 16
190
+ _GRIDPOINTS_2 = 2 << 16
191
+ _GRIDPOINTS_4 = 4 << 16
192
+ _GRIDPOINTS_8 = 8 << 16
193
+ _GRIDPOINTS_16 = 16 << 16
194
+ _GRIDPOINTS_32 = 32 << 16
195
+ _GRIDPOINTS_64 = 64 << 16
196
+ _GRIDPOINTS_128 = 128 << 16
197
+
198
+ @staticmethod
199
+ def GRIDPOINTS(n: int) -> Flags:
200
+ """
201
+ Fine-tune control over number of gridpoints
202
+
203
+ :param n: :py:class:`int` in range ``0 <= n <= 255``
204
+ """
205
+ return Flags.NONE | ((n & 0xFF) << 16)
206
+
207
+
208
+ _MAX_FLAG = reduce(operator.or_, Flags)
209
+
210
+
211
+ _FLAGS = {
212
+ "MATRIXINPUT": 1,
213
+ "MATRIXOUTPUT": 2,
214
+ "MATRIXONLY": (1 | 2),
215
+ "NOWHITEONWHITEFIXUP": 4, # Don't hot fix scum dot
216
+ # Don't create prelinearization tables on precalculated transforms
217
+ # (internal use):
218
+ "NOPRELINEARIZATION": 16,
219
+ "GUESSDEVICECLASS": 32, # Guess device class (for transform2devicelink)
220
+ "NOTCACHE": 64, # Inhibit 1-pixel cache
221
+ "NOTPRECALC": 256,
222
+ "NULLTRANSFORM": 512, # Don't transform anyway
223
+ "HIGHRESPRECALC": 1024, # Use more memory to give better accuracy
224
+ "LOWRESPRECALC": 2048, # Use less memory to minimize resources
225
+ "WHITEBLACKCOMPENSATION": 8192,
226
+ "BLACKPOINTCOMPENSATION": 8192,
227
+ "GAMUTCHECK": 4096, # Out of Gamut alarm
228
+ "SOFTPROOFING": 16384, # Do softproofing
229
+ "PRESERVEBLACK": 32768, # Black preservation
230
+ "NODEFAULTRESOURCEDEF": 16777216, # CRD special
231
+ "GRIDPOINTS": lambda n: (n & 0xFF) << 16, # Gridpoints
232
+ }
233
+
234
+
235
+ # --------------------------------------------------------------------.
236
+ # Experimental PIL-level API
237
+ # --------------------------------------------------------------------.
238
+
239
+ ##
240
+ # Profile.
241
+
242
+
243
+ class ImageCmsProfile:
244
+ def __init__(self, profile: str | SupportsRead[bytes] | core.CmsProfile) -> None:
245
+ """
246
+ :param profile: Either a string representing a filename,
247
+ a file like object containing a profile or a
248
+ low-level profile object
249
+
250
+ """
251
+
252
+ if isinstance(profile, str):
253
+ if sys.platform == "win32":
254
+ profile_bytes_path = profile.encode()
255
+ try:
256
+ profile_bytes_path.decode("ascii")
257
+ except UnicodeDecodeError:
258
+ with open(profile, "rb") as f:
259
+ self._set(core.profile_frombytes(f.read()))
260
+ return
261
+ self._set(core.profile_open(profile), profile)
262
+ elif hasattr(profile, "read"):
263
+ self._set(core.profile_frombytes(profile.read()))
264
+ elif isinstance(profile, core.CmsProfile):
265
+ self._set(profile)
266
+ else:
267
+ msg = "Invalid type for Profile" # type: ignore[unreachable]
268
+ raise TypeError(msg)
269
+
270
+ def _set(self, profile: core.CmsProfile, filename: str | None = None) -> None:
271
+ self.profile = profile
272
+ self.filename = filename
273
+ self.product_name = None # profile.product_name
274
+ self.product_info = None # profile.product_info
275
+
276
+ def tobytes(self) -> bytes:
277
+ """
278
+ Returns the profile in a format suitable for embedding in
279
+ saved images.
280
+
281
+ :returns: a bytes object containing the ICC profile.
282
+ """
283
+
284
+ return core.profile_tobytes(self.profile)
285
+
286
+
287
+ class ImageCmsTransform(Image.ImagePointHandler):
288
+ """
289
+ Transform. This can be used with the procedural API, or with the standard
290
+ :py:func:`~PIL.Image.Image.point` method.
291
+
292
+ Will return the output profile in the ``output.info['icc_profile']``.
293
+ """
294
+
295
+ def __init__(
296
+ self,
297
+ input: ImageCmsProfile,
298
+ output: ImageCmsProfile,
299
+ input_mode: str,
300
+ output_mode: str,
301
+ intent: Intent = Intent.PERCEPTUAL,
302
+ proof: ImageCmsProfile | None = None,
303
+ proof_intent: Intent = Intent.ABSOLUTE_COLORIMETRIC,
304
+ flags: Flags = Flags.NONE,
305
+ ):
306
+ supported_modes = (
307
+ "RGB",
308
+ "RGBA",
309
+ "RGBX",
310
+ "CMYK",
311
+ "I;16",
312
+ "I;16L",
313
+ "I;16B",
314
+ "YCbCr",
315
+ "LAB",
316
+ "L",
317
+ "1",
318
+ )
319
+ for mode in (input_mode, output_mode):
320
+ if mode not in supported_modes:
321
+ deprecate(
322
+ mode,
323
+ 12,
324
+ {
325
+ "L;16": "I;16 or I;16L",
326
+ "L:16B": "I;16B",
327
+ "YCCA": "YCbCr",
328
+ "YCC": "YCbCr",
329
+ }.get(mode),
330
+ )
331
+ if proof is None:
332
+ self.transform = core.buildTransform(
333
+ input.profile, output.profile, input_mode, output_mode, intent, flags
334
+ )
335
+ else:
336
+ self.transform = core.buildProofTransform(
337
+ input.profile,
338
+ output.profile,
339
+ proof.profile,
340
+ input_mode,
341
+ output_mode,
342
+ intent,
343
+ proof_intent,
344
+ flags,
345
+ )
346
+ # Note: inputMode and outputMode are for pyCMS compatibility only
347
+ self.input_mode = self.inputMode = input_mode
348
+ self.output_mode = self.outputMode = output_mode
349
+
350
+ self.output_profile = output
351
+
352
+ def point(self, im: Image.Image) -> Image.Image:
353
+ return self.apply(im)
354
+
355
+ def apply(self, im: Image.Image, imOut: Image.Image | None = None) -> Image.Image:
356
+ if imOut is None:
357
+ imOut = Image.new(self.output_mode, im.size, None)
358
+ self.transform.apply(im.getim(), imOut.getim())
359
+ imOut.info["icc_profile"] = self.output_profile.tobytes()
360
+ return imOut
361
+
362
+ def apply_in_place(self, im: Image.Image) -> Image.Image:
363
+ if im.mode != self.output_mode:
364
+ msg = "mode mismatch"
365
+ raise ValueError(msg) # wrong output mode
366
+ self.transform.apply(im.getim(), im.getim())
367
+ im.info["icc_profile"] = self.output_profile.tobytes()
368
+ return im
369
+
370
+
371
+ def get_display_profile(handle: SupportsInt | None = None) -> ImageCmsProfile | None:
372
+ """
373
+ (experimental) Fetches the profile for the current display device.
374
+
375
+ :returns: ``None`` if the profile is not known.
376
+ """
377
+
378
+ if sys.platform != "win32":
379
+ return None
380
+
381
+ from . import ImageWin # type: ignore[unused-ignore, unreachable]
382
+
383
+ if isinstance(handle, ImageWin.HDC):
384
+ profile = core.get_display_profile_win32(int(handle), 1)
385
+ else:
386
+ profile = core.get_display_profile_win32(int(handle or 0))
387
+ if profile is None:
388
+ return None
389
+ return ImageCmsProfile(profile)
390
+
391
+
392
+ # --------------------------------------------------------------------.
393
+ # pyCMS compatible layer
394
+ # --------------------------------------------------------------------.
395
+
396
+
397
+ class PyCMSError(Exception):
398
+ """(pyCMS) Exception class.
399
+ This is used for all errors in the pyCMS API."""
400
+
401
+ pass
402
+
403
+
404
+ def profileToProfile(
405
+ im: Image.Image,
406
+ inputProfile: _CmsProfileCompatible,
407
+ outputProfile: _CmsProfileCompatible,
408
+ renderingIntent: Intent = Intent.PERCEPTUAL,
409
+ outputMode: str | None = None,
410
+ inPlace: bool = False,
411
+ flags: Flags = Flags.NONE,
412
+ ) -> Image.Image | None:
413
+ """
414
+ (pyCMS) Applies an ICC transformation to a given image, mapping from
415
+ ``inputProfile`` to ``outputProfile``.
416
+
417
+ If the input or output profiles specified are not valid filenames, a
418
+ :exc:`PyCMSError` will be raised. If ``inPlace`` is ``True`` and
419
+ ``outputMode != im.mode``, a :exc:`PyCMSError` will be raised.
420
+ If an error occurs during application of the profiles,
421
+ a :exc:`PyCMSError` will be raised.
422
+ If ``outputMode`` is not a mode supported by the ``outputProfile`` (or by pyCMS),
423
+ a :exc:`PyCMSError` will be raised.
424
+
425
+ This function applies an ICC transformation to im from ``inputProfile``'s
426
+ color space to ``outputProfile``'s color space using the specified rendering
427
+ intent to decide how to handle out-of-gamut colors.
428
+
429
+ ``outputMode`` can be used to specify that a color mode conversion is to
430
+ be done using these profiles, but the specified profiles must be able
431
+ to handle that mode. I.e., if converting im from RGB to CMYK using
432
+ profiles, the input profile must handle RGB data, and the output
433
+ profile must handle CMYK data.
434
+
435
+ :param im: An open :py:class:`~PIL.Image.Image` object (i.e. Image.new(...)
436
+ or Image.open(...), etc.)
437
+ :param inputProfile: String, as a valid filename path to the ICC input
438
+ profile you wish to use for this image, or a profile object
439
+ :param outputProfile: String, as a valid filename path to the ICC output
440
+ profile you wish to use for this image, or a profile object
441
+ :param renderingIntent: Integer (0-3) specifying the rendering intent you
442
+ wish to use for the transform
443
+
444
+ ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
445
+ ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
446
+ ImageCms.Intent.SATURATION = 2
447
+ ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
448
+
449
+ see the pyCMS documentation for details on rendering intents and what
450
+ they do.
451
+ :param outputMode: A valid PIL mode for the output image (i.e. "RGB",
452
+ "CMYK", etc.). Note: if rendering the image "inPlace", outputMode
453
+ MUST be the same mode as the input, or omitted completely. If
454
+ omitted, the outputMode will be the same as the mode of the input
455
+ image (im.mode)
456
+ :param inPlace: Boolean. If ``True``, the original image is modified in-place,
457
+ and ``None`` is returned. If ``False`` (default), a new
458
+ :py:class:`~PIL.Image.Image` object is returned with the transform applied.
459
+ :param flags: Integer (0-...) specifying additional flags
460
+ :returns: Either None or a new :py:class:`~PIL.Image.Image` object, depending on
461
+ the value of ``inPlace``
462
+ :exception PyCMSError:
463
+ """
464
+
465
+ if outputMode is None:
466
+ outputMode = im.mode
467
+
468
+ if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3):
469
+ msg = "renderingIntent must be an integer between 0 and 3"
470
+ raise PyCMSError(msg)
471
+
472
+ if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
473
+ msg = f"flags must be an integer between 0 and {_MAX_FLAG}"
474
+ raise PyCMSError(msg)
475
+
476
+ try:
477
+ if not isinstance(inputProfile, ImageCmsProfile):
478
+ inputProfile = ImageCmsProfile(inputProfile)
479
+ if not isinstance(outputProfile, ImageCmsProfile):
480
+ outputProfile = ImageCmsProfile(outputProfile)
481
+ transform = ImageCmsTransform(
482
+ inputProfile,
483
+ outputProfile,
484
+ im.mode,
485
+ outputMode,
486
+ renderingIntent,
487
+ flags=flags,
488
+ )
489
+ if inPlace:
490
+ transform.apply_in_place(im)
491
+ imOut = None
492
+ else:
493
+ imOut = transform.apply(im)
494
+ except (OSError, TypeError, ValueError) as v:
495
+ raise PyCMSError(v) from v
496
+
497
+ return imOut
498
+
499
+
500
+ def getOpenProfile(
501
+ profileFilename: str | SupportsRead[bytes] | core.CmsProfile,
502
+ ) -> ImageCmsProfile:
503
+ """
504
+ (pyCMS) Opens an ICC profile file.
505
+
506
+ The PyCMSProfile object can be passed back into pyCMS for use in creating
507
+ transforms and such (as in ImageCms.buildTransformFromOpenProfiles()).
508
+
509
+ If ``profileFilename`` is not a valid filename for an ICC profile,
510
+ a :exc:`PyCMSError` will be raised.
511
+
512
+ :param profileFilename: String, as a valid filename path to the ICC profile
513
+ you wish to open, or a file-like object.
514
+ :returns: A CmsProfile class object.
515
+ :exception PyCMSError:
516
+ """
517
+
518
+ try:
519
+ return ImageCmsProfile(profileFilename)
520
+ except (OSError, TypeError, ValueError) as v:
521
+ raise PyCMSError(v) from v
522
+
523
+
524
+ def buildTransform(
525
+ inputProfile: _CmsProfileCompatible,
526
+ outputProfile: _CmsProfileCompatible,
527
+ inMode: str,
528
+ outMode: str,
529
+ renderingIntent: Intent = Intent.PERCEPTUAL,
530
+ flags: Flags = Flags.NONE,
531
+ ) -> ImageCmsTransform:
532
+ """
533
+ (pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the
534
+ ``outputProfile``. Use applyTransform to apply the transform to a given
535
+ image.
536
+
537
+ If the input or output profiles specified are not valid filenames, a
538
+ :exc:`PyCMSError` will be raised. If an error occurs during creation
539
+ of the transform, a :exc:`PyCMSError` will be raised.
540
+
541
+ If ``inMode`` or ``outMode`` are not a mode supported by the ``outputProfile``
542
+ (or by pyCMS), a :exc:`PyCMSError` will be raised.
543
+
544
+ This function builds and returns an ICC transform from the ``inputProfile``
545
+ to the ``outputProfile`` using the ``renderingIntent`` to determine what to do
546
+ with out-of-gamut colors. It will ONLY work for converting images that
547
+ are in ``inMode`` to images that are in ``outMode`` color format (PIL mode,
548
+ i.e. "RGB", "RGBA", "CMYK", etc.).
549
+
550
+ Building the transform is a fair part of the overhead in
551
+ ImageCms.profileToProfile(), so if you're planning on converting multiple
552
+ images using the same input/output settings, this can save you time.
553
+ Once you have a transform object, it can be used with
554
+ ImageCms.applyProfile() to convert images without the need to re-compute
555
+ the lookup table for the transform.
556
+
557
+ The reason pyCMS returns a class object rather than a handle directly
558
+ to the transform is that it needs to keep track of the PIL input/output
559
+ modes that the transform is meant for. These attributes are stored in
560
+ the ``inMode`` and ``outMode`` attributes of the object (which can be
561
+ manually overridden if you really want to, but I don't know of any
562
+ time that would be of use, or would even work).
563
+
564
+ :param inputProfile: String, as a valid filename path to the ICC input
565
+ profile you wish to use for this transform, or a profile object
566
+ :param outputProfile: String, as a valid filename path to the ICC output
567
+ profile you wish to use for this transform, or a profile object
568
+ :param inMode: String, as a valid PIL mode that the appropriate profile
569
+ also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
570
+ :param outMode: String, as a valid PIL mode that the appropriate profile
571
+ also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
572
+ :param renderingIntent: Integer (0-3) specifying the rendering intent you
573
+ wish to use for the transform
574
+
575
+ ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
576
+ ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
577
+ ImageCms.Intent.SATURATION = 2
578
+ ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
579
+
580
+ see the pyCMS documentation for details on rendering intents and what
581
+ they do.
582
+ :param flags: Integer (0-...) specifying additional flags
583
+ :returns: A CmsTransform class object.
584
+ :exception PyCMSError:
585
+ """
586
+
587
+ if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3):
588
+ msg = "renderingIntent must be an integer between 0 and 3"
589
+ raise PyCMSError(msg)
590
+
591
+ if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
592
+ msg = f"flags must be an integer between 0 and {_MAX_FLAG}"
593
+ raise PyCMSError(msg)
594
+
595
+ try:
596
+ if not isinstance(inputProfile, ImageCmsProfile):
597
+ inputProfile = ImageCmsProfile(inputProfile)
598
+ if not isinstance(outputProfile, ImageCmsProfile):
599
+ outputProfile = ImageCmsProfile(outputProfile)
600
+ return ImageCmsTransform(
601
+ inputProfile, outputProfile, inMode, outMode, renderingIntent, flags=flags
602
+ )
603
+ except (OSError, TypeError, ValueError) as v:
604
+ raise PyCMSError(v) from v
605
+
606
+
607
+ def buildProofTransform(
608
+ inputProfile: _CmsProfileCompatible,
609
+ outputProfile: _CmsProfileCompatible,
610
+ proofProfile: _CmsProfileCompatible,
611
+ inMode: str,
612
+ outMode: str,
613
+ renderingIntent: Intent = Intent.PERCEPTUAL,
614
+ proofRenderingIntent: Intent = Intent.ABSOLUTE_COLORIMETRIC,
615
+ flags: Flags = Flags.SOFTPROOFING,
616
+ ) -> ImageCmsTransform:
617
+ """
618
+ (pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the
619
+ ``outputProfile``, but tries to simulate the result that would be
620
+ obtained on the ``proofProfile`` device.
621
+
622
+ If the input, output, or proof profiles specified are not valid
623
+ filenames, a :exc:`PyCMSError` will be raised.
624
+
625
+ If an error occurs during creation of the transform,
626
+ a :exc:`PyCMSError` will be raised.
627
+
628
+ If ``inMode`` or ``outMode`` are not a mode supported by the ``outputProfile``
629
+ (or by pyCMS), a :exc:`PyCMSError` will be raised.
630
+
631
+ This function builds and returns an ICC transform from the ``inputProfile``
632
+ to the ``outputProfile``, but tries to simulate the result that would be
633
+ obtained on the ``proofProfile`` device using ``renderingIntent`` and
634
+ ``proofRenderingIntent`` to determine what to do with out-of-gamut
635
+ colors. This is known as "soft-proofing". It will ONLY work for
636
+ converting images that are in ``inMode`` to images that are in outMode
637
+ color format (PIL mode, i.e. "RGB", "RGBA", "CMYK", etc.).
638
+
639
+ Usage of the resulting transform object is exactly the same as with
640
+ ImageCms.buildTransform().
641
+
642
+ Proof profiling is generally used when using an output device to get a
643
+ good idea of what the final printed/displayed image would look like on
644
+ the ``proofProfile`` device when it's quicker and easier to use the
645
+ output device for judging color. Generally, this means that the
646
+ output device is a monitor, or a dye-sub printer (etc.), and the simulated
647
+ device is something more expensive, complicated, or time consuming
648
+ (making it difficult to make a real print for color judgement purposes).
649
+
650
+ Soft-proofing basically functions by adjusting the colors on the
651
+ output device to match the colors of the device being simulated. However,
652
+ when the simulated device has a much wider gamut than the output
653
+ device, you may obtain marginal results.
654
+
655
+ :param inputProfile: String, as a valid filename path to the ICC input
656
+ profile you wish to use for this transform, or a profile object
657
+ :param outputProfile: String, as a valid filename path to the ICC output
658
+ (monitor, usually) profile you wish to use for this transform, or a
659
+ profile object
660
+ :param proofProfile: String, as a valid filename path to the ICC proof
661
+ profile you wish to use for this transform, or a profile object
662
+ :param inMode: String, as a valid PIL mode that the appropriate profile
663
+ also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
664
+ :param outMode: String, as a valid PIL mode that the appropriate profile
665
+ also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
666
+ :param renderingIntent: Integer (0-3) specifying the rendering intent you
667
+ wish to use for the input->proof (simulated) transform
668
+
669
+ ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
670
+ ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
671
+ ImageCms.Intent.SATURATION = 2
672
+ ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
673
+
674
+ see the pyCMS documentation for details on rendering intents and what
675
+ they do.
676
+ :param proofRenderingIntent: Integer (0-3) specifying the rendering intent
677
+ you wish to use for proof->output transform
678
+
679
+ ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
680
+ ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
681
+ ImageCms.Intent.SATURATION = 2
682
+ ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
683
+
684
+ see the pyCMS documentation for details on rendering intents and what
685
+ they do.
686
+ :param flags: Integer (0-...) specifying additional flags
687
+ :returns: A CmsTransform class object.
688
+ :exception PyCMSError:
689
+ """
690
+
691
+ if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3):
692
+ msg = "renderingIntent must be an integer between 0 and 3"
693
+ raise PyCMSError(msg)
694
+
695
+ if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
696
+ msg = f"flags must be an integer between 0 and {_MAX_FLAG}"
697
+ raise PyCMSError(msg)
698
+
699
+ try:
700
+ if not isinstance(inputProfile, ImageCmsProfile):
701
+ inputProfile = ImageCmsProfile(inputProfile)
702
+ if not isinstance(outputProfile, ImageCmsProfile):
703
+ outputProfile = ImageCmsProfile(outputProfile)
704
+ if not isinstance(proofProfile, ImageCmsProfile):
705
+ proofProfile = ImageCmsProfile(proofProfile)
706
+ return ImageCmsTransform(
707
+ inputProfile,
708
+ outputProfile,
709
+ inMode,
710
+ outMode,
711
+ renderingIntent,
712
+ proofProfile,
713
+ proofRenderingIntent,
714
+ flags,
715
+ )
716
+ except (OSError, TypeError, ValueError) as v:
717
+ raise PyCMSError(v) from v
718
+
719
+
720
+ buildTransformFromOpenProfiles = buildTransform
721
+ buildProofTransformFromOpenProfiles = buildProofTransform
722
+
723
+
724
+ def applyTransform(
725
+ im: Image.Image, transform: ImageCmsTransform, inPlace: bool = False
726
+ ) -> Image.Image | None:
727
+ """
728
+ (pyCMS) Applies a transform to a given image.
729
+
730
+ If ``im.mode != transform.input_mode``, a :exc:`PyCMSError` is raised.
731
+
732
+ If ``inPlace`` is ``True`` and ``transform.input_mode != transform.output_mode``, a
733
+ :exc:`PyCMSError` is raised.
734
+
735
+ If ``im.mode``, ``transform.input_mode`` or ``transform.output_mode`` is not
736
+ supported by pyCMSdll or the profiles you used for the transform, a
737
+ :exc:`PyCMSError` is raised.
738
+
739
+ If an error occurs while the transform is being applied,
740
+ a :exc:`PyCMSError` is raised.
741
+
742
+ This function applies a pre-calculated transform (from
743
+ ImageCms.buildTransform() or ImageCms.buildTransformFromOpenProfiles())
744
+ to an image. The transform can be used for multiple images, saving
745
+ considerable calculation time if doing the same conversion multiple times.
746
+
747
+ If you want to modify im in-place instead of receiving a new image as
748
+ the return value, set ``inPlace`` to ``True``. This can only be done if
749
+ ``transform.input_mode`` and ``transform.output_mode`` are the same, because we
750
+ can't change the mode in-place (the buffer sizes for some modes are
751
+ different). The default behavior is to return a new :py:class:`~PIL.Image.Image`
752
+ object of the same dimensions in mode ``transform.output_mode``.
753
+
754
+ :param im: An :py:class:`~PIL.Image.Image` object, and ``im.mode`` must be the same
755
+ as the ``input_mode`` supported by the transform.
756
+ :param transform: A valid CmsTransform class object
757
+ :param inPlace: Bool. If ``True``, ``im`` is modified in place and ``None`` is
758
+ returned, if ``False``, a new :py:class:`~PIL.Image.Image` object with the
759
+ transform applied is returned (and ``im`` is not changed). The default is
760
+ ``False``.
761
+ :returns: Either ``None``, or a new :py:class:`~PIL.Image.Image` object,
762
+ depending on the value of ``inPlace``. The profile will be returned in
763
+ the image's ``info['icc_profile']``.
764
+ :exception PyCMSError:
765
+ """
766
+
767
+ try:
768
+ if inPlace:
769
+ transform.apply_in_place(im)
770
+ imOut = None
771
+ else:
772
+ imOut = transform.apply(im)
773
+ except (TypeError, ValueError) as v:
774
+ raise PyCMSError(v) from v
775
+
776
+ return imOut
777
+
778
+
779
+ def createProfile(
780
+ colorSpace: Literal["LAB", "XYZ", "sRGB"], colorTemp: SupportsFloat = 0
781
+ ) -> core.CmsProfile:
782
+ """
783
+ (pyCMS) Creates a profile.
784
+
785
+ If colorSpace not in ``["LAB", "XYZ", "sRGB"]``,
786
+ a :exc:`PyCMSError` is raised.
787
+
788
+ If using LAB and ``colorTemp`` is not a positive integer,
789
+ a :exc:`PyCMSError` is raised.
790
+
791
+ If an error occurs while creating the profile,
792
+ a :exc:`PyCMSError` is raised.
793
+
794
+ Use this function to create common profiles on-the-fly instead of
795
+ having to supply a profile on disk and knowing the path to it. It
796
+ returns a normal CmsProfile object that can be passed to
797
+ ImageCms.buildTransformFromOpenProfiles() to create a transform to apply
798
+ to images.
799
+
800
+ :param colorSpace: String, the color space of the profile you wish to
801
+ create.
802
+ Currently only "LAB", "XYZ", and "sRGB" are supported.
803
+ :param colorTemp: Positive number for the white point for the profile, in
804
+ degrees Kelvin (i.e. 5000, 6500, 9600, etc.). The default is for D50
805
+ illuminant if omitted (5000k). colorTemp is ONLY applied to LAB
806
+ profiles, and is ignored for XYZ and sRGB.
807
+ :returns: A CmsProfile class object
808
+ :exception PyCMSError:
809
+ """
810
+
811
+ if colorSpace not in ["LAB", "XYZ", "sRGB"]:
812
+ msg = (
813
+ f"Color space not supported for on-the-fly profile creation ({colorSpace})"
814
+ )
815
+ raise PyCMSError(msg)
816
+
817
+ if colorSpace == "LAB":
818
+ try:
819
+ colorTemp = float(colorTemp)
820
+ except (TypeError, ValueError) as e:
821
+ msg = f'Color temperature must be numeric, "{colorTemp}" not valid'
822
+ raise PyCMSError(msg) from e
823
+
824
+ try:
825
+ return core.createProfile(colorSpace, colorTemp)
826
+ except (TypeError, ValueError) as v:
827
+ raise PyCMSError(v) from v
828
+
829
+
830
+ def getProfileName(profile: _CmsProfileCompatible) -> str:
831
+ """
832
+
833
+ (pyCMS) Gets the internal product name for the given profile.
834
+
835
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile,
836
+ a :exc:`PyCMSError` is raised If an error occurs while trying
837
+ to obtain the name tag, a :exc:`PyCMSError` is raised.
838
+
839
+ Use this function to obtain the INTERNAL name of the profile (stored
840
+ in an ICC tag in the profile itself), usually the one used when the
841
+ profile was originally created. Sometimes this tag also contains
842
+ additional information supplied by the creator.
843
+
844
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
845
+ filename of an ICC profile.
846
+ :returns: A string containing the internal name of the profile as stored
847
+ in an ICC tag.
848
+ :exception PyCMSError:
849
+ """
850
+
851
+ try:
852
+ # add an extra newline to preserve pyCMS compatibility
853
+ if not isinstance(profile, ImageCmsProfile):
854
+ profile = ImageCmsProfile(profile)
855
+ # do it in python, not c.
856
+ # // name was "%s - %s" (model, manufacturer) || Description ,
857
+ # // but if the Model and Manufacturer were the same or the model
858
+ # // was long, Just the model, in 1.x
859
+ model = profile.profile.model
860
+ manufacturer = profile.profile.manufacturer
861
+
862
+ if not (model or manufacturer):
863
+ return (profile.profile.profile_description or "") + "\n"
864
+ if not manufacturer or (model and len(model) > 30):
865
+ return f"{model}\n"
866
+ return f"{model} - {manufacturer}\n"
867
+
868
+ except (AttributeError, OSError, TypeError, ValueError) as v:
869
+ raise PyCMSError(v) from v
870
+
871
+
872
+ def getProfileInfo(profile: _CmsProfileCompatible) -> str:
873
+ """
874
+ (pyCMS) Gets the internal product information for the given profile.
875
+
876
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile,
877
+ a :exc:`PyCMSError` is raised.
878
+
879
+ If an error occurs while trying to obtain the info tag,
880
+ a :exc:`PyCMSError` is raised.
881
+
882
+ Use this function to obtain the information stored in the profile's
883
+ info tag. This often contains details about the profile, and how it
884
+ was created, as supplied by the creator.
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
+
893
+ try:
894
+ if not isinstance(profile, ImageCmsProfile):
895
+ profile = ImageCmsProfile(profile)
896
+ # add an extra newline to preserve pyCMS compatibility
897
+ # Python, not C. the white point bits weren't working well,
898
+ # so skipping.
899
+ # info was description \r\n\r\n copyright \r\n\r\n K007 tag \r\n\r\n whitepoint
900
+ description = profile.profile.profile_description
901
+ cpright = profile.profile.copyright
902
+ elements = [element for element in (description, cpright) if element]
903
+ return "\r\n\r\n".join(elements) + "\r\n\r\n"
904
+
905
+ except (AttributeError, OSError, TypeError, ValueError) as v:
906
+ raise PyCMSError(v) from v
907
+
908
+
909
+ def getProfileCopyright(profile: _CmsProfileCompatible) -> str:
910
+ """
911
+ (pyCMS) Gets the copyright for the given profile.
912
+
913
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
914
+ :exc:`PyCMSError` is raised.
915
+
916
+ If an error occurs while trying to obtain the copyright tag,
917
+ a :exc:`PyCMSError` is raised.
918
+
919
+ Use this function to obtain the information stored in the profile's
920
+ copyright tag.
921
+
922
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
923
+ filename of an ICC profile.
924
+ :returns: A string containing the internal profile information stored in
925
+ an ICC tag.
926
+ :exception PyCMSError:
927
+ """
928
+ try:
929
+ # add an extra newline to preserve pyCMS compatibility
930
+ if not isinstance(profile, ImageCmsProfile):
931
+ profile = ImageCmsProfile(profile)
932
+ return (profile.profile.copyright or "") + "\n"
933
+ except (AttributeError, OSError, TypeError, ValueError) as v:
934
+ raise PyCMSError(v) from v
935
+
936
+
937
+ def getProfileManufacturer(profile: _CmsProfileCompatible) -> str:
938
+ """
939
+ (pyCMS) Gets the manufacturer for the given profile.
940
+
941
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
942
+ :exc:`PyCMSError` is raised.
943
+
944
+ If an error occurs while trying to obtain the manufacturer tag, a
945
+ :exc:`PyCMSError` is raised.
946
+
947
+ Use this function to obtain the information stored in the profile's
948
+ manufacturer tag.
949
+
950
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
951
+ filename of an ICC profile.
952
+ :returns: A string containing the internal profile information stored in
953
+ an ICC tag.
954
+ :exception PyCMSError:
955
+ """
956
+ try:
957
+ # add an extra newline to preserve pyCMS compatibility
958
+ if not isinstance(profile, ImageCmsProfile):
959
+ profile = ImageCmsProfile(profile)
960
+ return (profile.profile.manufacturer or "") + "\n"
961
+ except (AttributeError, OSError, TypeError, ValueError) as v:
962
+ raise PyCMSError(v) from v
963
+
964
+
965
+ def getProfileModel(profile: _CmsProfileCompatible) -> str:
966
+ """
967
+ (pyCMS) Gets the model for the given profile.
968
+
969
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
970
+ :exc:`PyCMSError` is raised.
971
+
972
+ If an error occurs while trying to obtain the model tag,
973
+ a :exc:`PyCMSError` is raised.
974
+
975
+ Use this function to obtain the information stored in the profile's
976
+ model tag.
977
+
978
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
979
+ filename of an ICC profile.
980
+ :returns: A string containing the internal profile information stored in
981
+ an ICC tag.
982
+ :exception PyCMSError:
983
+ """
984
+
985
+ try:
986
+ # add an extra newline to preserve pyCMS compatibility
987
+ if not isinstance(profile, ImageCmsProfile):
988
+ profile = ImageCmsProfile(profile)
989
+ return (profile.profile.model or "") + "\n"
990
+ except (AttributeError, OSError, TypeError, ValueError) as v:
991
+ raise PyCMSError(v) from v
992
+
993
+
994
+ def getProfileDescription(profile: _CmsProfileCompatible) -> str:
995
+ """
996
+ (pyCMS) Gets the description for the given profile.
997
+
998
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
999
+ :exc:`PyCMSError` is raised.
1000
+
1001
+ If an error occurs while trying to obtain the description tag,
1002
+ a :exc:`PyCMSError` is raised.
1003
+
1004
+ Use this function to obtain the information stored in the profile's
1005
+ description tag.
1006
+
1007
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
1008
+ filename of an ICC profile.
1009
+ :returns: A string containing the internal profile information stored in an
1010
+ ICC tag.
1011
+ :exception PyCMSError:
1012
+ """
1013
+
1014
+ try:
1015
+ # add an extra newline to preserve pyCMS compatibility
1016
+ if not isinstance(profile, ImageCmsProfile):
1017
+ profile = ImageCmsProfile(profile)
1018
+ return (profile.profile.profile_description or "") + "\n"
1019
+ except (AttributeError, OSError, TypeError, ValueError) as v:
1020
+ raise PyCMSError(v) from v
1021
+
1022
+
1023
+ def getDefaultIntent(profile: _CmsProfileCompatible) -> int:
1024
+ """
1025
+ (pyCMS) Gets the default intent name for the given profile.
1026
+
1027
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
1028
+ :exc:`PyCMSError` is raised.
1029
+
1030
+ If an error occurs while trying to obtain the default intent, a
1031
+ :exc:`PyCMSError` is raised.
1032
+
1033
+ Use this function to determine the default (and usually best optimized)
1034
+ rendering intent for this profile. Most profiles support multiple
1035
+ rendering intents, but are intended mostly for one type of conversion.
1036
+ If you wish to use a different intent than returned, use
1037
+ ImageCms.isIntentSupported() to verify it will work first.
1038
+
1039
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
1040
+ filename of an ICC profile.
1041
+ :returns: Integer 0-3 specifying the default rendering intent for this
1042
+ profile.
1043
+
1044
+ ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
1045
+ ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
1046
+ ImageCms.Intent.SATURATION = 2
1047
+ ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
1048
+
1049
+ see the pyCMS documentation for details on rendering intents and what
1050
+ they do.
1051
+ :exception PyCMSError:
1052
+ """
1053
+
1054
+ try:
1055
+ if not isinstance(profile, ImageCmsProfile):
1056
+ profile = ImageCmsProfile(profile)
1057
+ return profile.profile.rendering_intent
1058
+ except (AttributeError, OSError, TypeError, ValueError) as v:
1059
+ raise PyCMSError(v) from v
1060
+
1061
+
1062
+ def isIntentSupported(
1063
+ profile: _CmsProfileCompatible, intent: Intent, direction: Direction
1064
+ ) -> Literal[-1, 1]:
1065
+ """
1066
+ (pyCMS) Checks if a given intent is supported.
1067
+
1068
+ Use this function to verify that you can use your desired
1069
+ ``intent`` with ``profile``, and that ``profile`` can be used for the
1070
+ input/output/proof profile as you desire.
1071
+
1072
+ Some profiles are created specifically for one "direction", can cannot
1073
+ be used for others. Some profiles can only be used for certain
1074
+ rendering intents, so it's best to either verify this before trying
1075
+ to create a transform with them (using this function), or catch the
1076
+ potential :exc:`PyCMSError` that will occur if they don't
1077
+ support the modes you select.
1078
+
1079
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
1080
+ filename of an ICC profile.
1081
+ :param intent: Integer (0-3) specifying the rendering intent you wish to
1082
+ use with this profile
1083
+
1084
+ ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
1085
+ ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
1086
+ ImageCms.Intent.SATURATION = 2
1087
+ ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
1088
+
1089
+ see the pyCMS documentation for details on rendering intents and what
1090
+ they do.
1091
+ :param direction: Integer specifying if the profile is to be used for
1092
+ input, output, or proof
1093
+
1094
+ INPUT = 0 (or use ImageCms.Direction.INPUT)
1095
+ OUTPUT = 1 (or use ImageCms.Direction.OUTPUT)
1096
+ PROOF = 2 (or use ImageCms.Direction.PROOF)
1097
+
1098
+ :returns: 1 if the intent/direction are supported, -1 if they are not.
1099
+ :exception PyCMSError:
1100
+ """
1101
+
1102
+ try:
1103
+ if not isinstance(profile, ImageCmsProfile):
1104
+ profile = ImageCmsProfile(profile)
1105
+ # FIXME: I get different results for the same data w. different
1106
+ # compilers. Bug in LittleCMS or in the binding?
1107
+ if profile.profile.is_intent_supported(intent, direction):
1108
+ return 1
1109
+ else:
1110
+ return -1
1111
+ except (AttributeError, OSError, TypeError, ValueError) as v:
1112
+ raise PyCMSError(v) from v
1113
+
1114
+
1115
+ def versions() -> tuple[str, str | None, str, str]:
1116
+ """
1117
+ (pyCMS) Fetches versions.
1118
+ """
1119
+
1120
+ deprecate(
1121
+ "PIL.ImageCms.versions()",
1122
+ 12,
1123
+ '(PIL.features.version("littlecms2"), sys.version, PIL.__version__)',
1124
+ )
1125
+ return _VERSION, core.littlecms_version, sys.version.split()[0], __version__
phi4/lib/python3.10/site-packages/PIL/ImageFilter.py ADDED
@@ -0,0 +1,605 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # standard filters
6
+ #
7
+ # History:
8
+ # 1995-11-27 fl Created
9
+ # 2002-06-08 fl Added rank and mode filters
10
+ # 2003-09-15 fl Fixed rank calculation in rank filter; added expand call
11
+ #
12
+ # Copyright (c) 1997-2003 by Secret Labs AB.
13
+ # Copyright (c) 1995-2002 by Fredrik Lundh.
14
+ #
15
+ # See the README file for information on usage and redistribution.
16
+ #
17
+ from __future__ import annotations
18
+
19
+ import abc
20
+ import functools
21
+ from collections.abc import Sequence
22
+ from types import ModuleType
23
+ from typing import TYPE_CHECKING, Any, Callable, cast
24
+
25
+ if TYPE_CHECKING:
26
+ from . import _imaging
27
+ from ._typing import NumpyArray
28
+
29
+
30
+ class Filter:
31
+ @abc.abstractmethod
32
+ def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
33
+ pass
34
+
35
+
36
+ class MultibandFilter(Filter):
37
+ pass
38
+
39
+
40
+ class BuiltinFilter(MultibandFilter):
41
+ filterargs: tuple[Any, ...]
42
+
43
+ def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
44
+ if image.mode == "P":
45
+ msg = "cannot filter palette images"
46
+ raise ValueError(msg)
47
+ return image.filter(*self.filterargs)
48
+
49
+
50
+ class Kernel(BuiltinFilter):
51
+ """
52
+ Create a convolution kernel. This only supports 3x3 and 5x5 integer and floating
53
+ point kernels.
54
+
55
+ Kernels can only be applied to "L" and "RGB" images.
56
+
57
+ :param size: Kernel size, given as (width, height). This must be (3,3) or (5,5).
58
+ :param kernel: A sequence containing kernel weights. The kernel will be flipped
59
+ vertically before being applied to the image.
60
+ :param scale: Scale factor. If given, the result for each pixel is divided by this
61
+ value. The default is the sum of the kernel weights.
62
+ :param offset: Offset. If given, this value is added to the result, after it has
63
+ been divided by the scale factor.
64
+ """
65
+
66
+ name = "Kernel"
67
+
68
+ def __init__(
69
+ self,
70
+ size: tuple[int, int],
71
+ kernel: Sequence[float],
72
+ scale: float | None = None,
73
+ offset: float = 0,
74
+ ) -> None:
75
+ if scale is None:
76
+ # default scale is sum of kernel
77
+ scale = functools.reduce(lambda a, b: a + b, kernel)
78
+ if size[0] * size[1] != len(kernel):
79
+ msg = "not enough coefficients in kernel"
80
+ raise ValueError(msg)
81
+ self.filterargs = size, scale, offset, kernel
82
+
83
+
84
+ class RankFilter(Filter):
85
+ """
86
+ Create a rank filter. The rank filter sorts all pixels in
87
+ a window of the given size, and returns the ``rank``'th value.
88
+
89
+ :param size: The kernel size, in pixels.
90
+ :param rank: What pixel value to pick. Use 0 for a min filter,
91
+ ``size * size / 2`` for a median filter, ``size * size - 1``
92
+ for a max filter, etc.
93
+ """
94
+
95
+ name = "Rank"
96
+
97
+ def __init__(self, size: int, rank: int) -> None:
98
+ self.size = size
99
+ self.rank = rank
100
+
101
+ def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
102
+ if image.mode == "P":
103
+ msg = "cannot filter palette images"
104
+ raise ValueError(msg)
105
+ image = image.expand(self.size // 2, self.size // 2)
106
+ return image.rankfilter(self.size, self.rank)
107
+
108
+
109
+ class MedianFilter(RankFilter):
110
+ """
111
+ Create a median filter. Picks the median pixel value in a window with the
112
+ given size.
113
+
114
+ :param size: The kernel size, in pixels.
115
+ """
116
+
117
+ name = "Median"
118
+
119
+ def __init__(self, size: int = 3) -> None:
120
+ self.size = size
121
+ self.rank = size * size // 2
122
+
123
+
124
+ class MinFilter(RankFilter):
125
+ """
126
+ Create a min filter. Picks the lowest pixel value in a window with the
127
+ given size.
128
+
129
+ :param size: The kernel size, in pixels.
130
+ """
131
+
132
+ name = "Min"
133
+
134
+ def __init__(self, size: int = 3) -> None:
135
+ self.size = size
136
+ self.rank = 0
137
+
138
+
139
+ class MaxFilter(RankFilter):
140
+ """
141
+ Create a max filter. Picks the largest pixel value in a window with the
142
+ given size.
143
+
144
+ :param size: The kernel size, in pixels.
145
+ """
146
+
147
+ name = "Max"
148
+
149
+ def __init__(self, size: int = 3) -> None:
150
+ self.size = size
151
+ self.rank = size * size - 1
152
+
153
+
154
+ class ModeFilter(Filter):
155
+ """
156
+ Create a mode filter. Picks the most frequent pixel value in a box with the
157
+ given size. Pixel values that occur only once or twice are ignored; if no
158
+ pixel value occurs more than twice, the original pixel value is preserved.
159
+
160
+ :param size: The kernel size, in pixels.
161
+ """
162
+
163
+ name = "Mode"
164
+
165
+ def __init__(self, size: int = 3) -> None:
166
+ self.size = size
167
+
168
+ def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
169
+ return image.modefilter(self.size)
170
+
171
+
172
+ class GaussianBlur(MultibandFilter):
173
+ """Blurs the image with a sequence of extended box filters, which
174
+ approximates a Gaussian kernel. For details on accuracy see
175
+ <https://www.mia.uni-saarland.de/Publications/gwosdek-ssvm11.pdf>
176
+
177
+ :param radius: Standard deviation of the Gaussian kernel. Either a sequence of two
178
+ numbers for x and y, or a single number for both.
179
+ """
180
+
181
+ name = "GaussianBlur"
182
+
183
+ def __init__(self, radius: float | Sequence[float] = 2) -> None:
184
+ self.radius = radius
185
+
186
+ def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
187
+ xy = self.radius
188
+ if isinstance(xy, (int, float)):
189
+ xy = (xy, xy)
190
+ if xy == (0, 0):
191
+ return image.copy()
192
+ return image.gaussian_blur(xy)
193
+
194
+
195
+ class BoxBlur(MultibandFilter):
196
+ """Blurs the image by setting each pixel to the average value of the pixels
197
+ in a square box extending radius pixels in each direction.
198
+ Supports float radius of arbitrary size. Uses an optimized implementation
199
+ which runs in linear time relative to the size of the image
200
+ for any radius value.
201
+
202
+ :param radius: Size of the box in a direction. Either a sequence of two numbers for
203
+ x and y, or a single number for both.
204
+
205
+ Radius 0 does not blur, returns an identical image.
206
+ Radius 1 takes 1 pixel in each direction, i.e. 9 pixels in total.
207
+ """
208
+
209
+ name = "BoxBlur"
210
+
211
+ def __init__(self, radius: float | Sequence[float]) -> None:
212
+ xy = radius if isinstance(radius, (tuple, list)) else (radius, radius)
213
+ if xy[0] < 0 or xy[1] < 0:
214
+ msg = "radius must be >= 0"
215
+ raise ValueError(msg)
216
+ self.radius = radius
217
+
218
+ def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
219
+ xy = self.radius
220
+ if isinstance(xy, (int, float)):
221
+ xy = (xy, xy)
222
+ if xy == (0, 0):
223
+ return image.copy()
224
+ return image.box_blur(xy)
225
+
226
+
227
+ class UnsharpMask(MultibandFilter):
228
+ """Unsharp mask filter.
229
+
230
+ See Wikipedia's entry on `digital unsharp masking`_ for an explanation of
231
+ the parameters.
232
+
233
+ :param radius: Blur Radius
234
+ :param percent: Unsharp strength, in percent
235
+ :param threshold: Threshold controls the minimum brightness change that
236
+ will be sharpened
237
+
238
+ .. _digital unsharp masking: https://en.wikipedia.org/wiki/Unsharp_masking#Digital_unsharp_masking
239
+
240
+ """
241
+
242
+ name = "UnsharpMask"
243
+
244
+ def __init__(
245
+ self, radius: float = 2, percent: int = 150, threshold: int = 3
246
+ ) -> None:
247
+ self.radius = radius
248
+ self.percent = percent
249
+ self.threshold = threshold
250
+
251
+ def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
252
+ return image.unsharp_mask(self.radius, self.percent, self.threshold)
253
+
254
+
255
+ class BLUR(BuiltinFilter):
256
+ name = "Blur"
257
+ # fmt: off
258
+ filterargs = (5, 5), 16, 0, (
259
+ 1, 1, 1, 1, 1,
260
+ 1, 0, 0, 0, 1,
261
+ 1, 0, 0, 0, 1,
262
+ 1, 0, 0, 0, 1,
263
+ 1, 1, 1, 1, 1,
264
+ )
265
+ # fmt: on
266
+
267
+
268
+ class CONTOUR(BuiltinFilter):
269
+ name = "Contour"
270
+ # fmt: off
271
+ filterargs = (3, 3), 1, 255, (
272
+ -1, -1, -1,
273
+ -1, 8, -1,
274
+ -1, -1, -1,
275
+ )
276
+ # fmt: on
277
+
278
+
279
+ class DETAIL(BuiltinFilter):
280
+ name = "Detail"
281
+ # fmt: off
282
+ filterargs = (3, 3), 6, 0, (
283
+ 0, -1, 0,
284
+ -1, 10, -1,
285
+ 0, -1, 0,
286
+ )
287
+ # fmt: on
288
+
289
+
290
+ class EDGE_ENHANCE(BuiltinFilter):
291
+ name = "Edge-enhance"
292
+ # fmt: off
293
+ filterargs = (3, 3), 2, 0, (
294
+ -1, -1, -1,
295
+ -1, 10, -1,
296
+ -1, -1, -1,
297
+ )
298
+ # fmt: on
299
+
300
+
301
+ class EDGE_ENHANCE_MORE(BuiltinFilter):
302
+ name = "Edge-enhance More"
303
+ # fmt: off
304
+ filterargs = (3, 3), 1, 0, (
305
+ -1, -1, -1,
306
+ -1, 9, -1,
307
+ -1, -1, -1,
308
+ )
309
+ # fmt: on
310
+
311
+
312
+ class EMBOSS(BuiltinFilter):
313
+ name = "Emboss"
314
+ # fmt: off
315
+ filterargs = (3, 3), 1, 128, (
316
+ -1, 0, 0,
317
+ 0, 1, 0,
318
+ 0, 0, 0,
319
+ )
320
+ # fmt: on
321
+
322
+
323
+ class FIND_EDGES(BuiltinFilter):
324
+ name = "Find Edges"
325
+ # fmt: off
326
+ filterargs = (3, 3), 1, 0, (
327
+ -1, -1, -1,
328
+ -1, 8, -1,
329
+ -1, -1, -1,
330
+ )
331
+ # fmt: on
332
+
333
+
334
+ class SHARPEN(BuiltinFilter):
335
+ name = "Sharpen"
336
+ # fmt: off
337
+ filterargs = (3, 3), 16, 0, (
338
+ -2, -2, -2,
339
+ -2, 32, -2,
340
+ -2, -2, -2,
341
+ )
342
+ # fmt: on
343
+
344
+
345
+ class SMOOTH(BuiltinFilter):
346
+ name = "Smooth"
347
+ # fmt: off
348
+ filterargs = (3, 3), 13, 0, (
349
+ 1, 1, 1,
350
+ 1, 5, 1,
351
+ 1, 1, 1,
352
+ )
353
+ # fmt: on
354
+
355
+
356
+ class SMOOTH_MORE(BuiltinFilter):
357
+ name = "Smooth More"
358
+ # fmt: off
359
+ filterargs = (5, 5), 100, 0, (
360
+ 1, 1, 1, 1, 1,
361
+ 1, 5, 5, 5, 1,
362
+ 1, 5, 44, 5, 1,
363
+ 1, 5, 5, 5, 1,
364
+ 1, 1, 1, 1, 1,
365
+ )
366
+ # fmt: on
367
+
368
+
369
+ class Color3DLUT(MultibandFilter):
370
+ """Three-dimensional color lookup table.
371
+
372
+ Transforms 3-channel pixels using the values of the channels as coordinates
373
+ in the 3D lookup table and interpolating the nearest elements.
374
+
375
+ This method allows you to apply almost any color transformation
376
+ in constant time by using pre-calculated decimated tables.
377
+
378
+ .. versionadded:: 5.2.0
379
+
380
+ :param size: Size of the table. One int or tuple of (int, int, int).
381
+ Minimal size in any dimension is 2, maximum is 65.
382
+ :param table: Flat lookup table. A list of ``channels * size**3``
383
+ float elements or a list of ``size**3`` channels-sized
384
+ tuples with floats. Channels are changed first,
385
+ then first dimension, then second, then third.
386
+ Value 0.0 corresponds lowest value of output, 1.0 highest.
387
+ :param channels: Number of channels in the table. Could be 3 or 4.
388
+ Default is 3.
389
+ :param target_mode: A mode for the result image. Should have not less
390
+ than ``channels`` channels. Default is ``None``,
391
+ which means that mode wouldn't be changed.
392
+ """
393
+
394
+ name = "Color 3D LUT"
395
+
396
+ def __init__(
397
+ self,
398
+ size: int | tuple[int, int, int],
399
+ table: Sequence[float] | Sequence[Sequence[int]] | NumpyArray,
400
+ channels: int = 3,
401
+ target_mode: str | None = None,
402
+ **kwargs: bool,
403
+ ) -> None:
404
+ if channels not in (3, 4):
405
+ msg = "Only 3 or 4 output channels are supported"
406
+ raise ValueError(msg)
407
+ self.size = size = self._check_size(size)
408
+ self.channels = channels
409
+ self.mode = target_mode
410
+
411
+ # Hidden flag `_copy_table=False` could be used to avoid extra copying
412
+ # of the table if the table is specially made for the constructor.
413
+ copy_table = kwargs.get("_copy_table", True)
414
+ items = size[0] * size[1] * size[2]
415
+ wrong_size = False
416
+
417
+ numpy: ModuleType | None = None
418
+ if hasattr(table, "shape"):
419
+ try:
420
+ import numpy
421
+ except ImportError:
422
+ pass
423
+
424
+ if numpy and isinstance(table, numpy.ndarray):
425
+ numpy_table: NumpyArray = table
426
+ if copy_table:
427
+ numpy_table = numpy_table.copy()
428
+
429
+ if numpy_table.shape in [
430
+ (items * channels,),
431
+ (items, channels),
432
+ (size[2], size[1], size[0], channels),
433
+ ]:
434
+ table = numpy_table.reshape(items * channels)
435
+ else:
436
+ wrong_size = True
437
+
438
+ else:
439
+ if copy_table:
440
+ table = list(table)
441
+
442
+ # Convert to a flat list
443
+ if table and isinstance(table[0], (list, tuple)):
444
+ raw_table = cast(Sequence[Sequence[int]], table)
445
+ flat_table: list[int] = []
446
+ for pixel in raw_table:
447
+ if len(pixel) != channels:
448
+ msg = (
449
+ "The elements of the table should "
450
+ f"have a length of {channels}."
451
+ )
452
+ raise ValueError(msg)
453
+ flat_table.extend(pixel)
454
+ table = flat_table
455
+
456
+ if wrong_size or len(table) != items * channels:
457
+ msg = (
458
+ "The table should have either channels * size**3 float items "
459
+ "or size**3 items of channels-sized tuples with floats. "
460
+ f"Table should be: {channels}x{size[0]}x{size[1]}x{size[2]}. "
461
+ f"Actual length: {len(table)}"
462
+ )
463
+ raise ValueError(msg)
464
+ self.table = table
465
+
466
+ @staticmethod
467
+ def _check_size(size: Any) -> tuple[int, int, int]:
468
+ try:
469
+ _, _, _ = size
470
+ except ValueError as e:
471
+ msg = "Size should be either an integer or a tuple of three integers."
472
+ raise ValueError(msg) from e
473
+ except TypeError:
474
+ size = (size, size, size)
475
+ size = tuple(int(x) for x in size)
476
+ for size_1d in size:
477
+ if not 2 <= size_1d <= 65:
478
+ msg = "Size should be in [2, 65] range."
479
+ raise ValueError(msg)
480
+ return size
481
+
482
+ @classmethod
483
+ def generate(
484
+ cls,
485
+ size: int | tuple[int, int, int],
486
+ callback: Callable[[float, float, float], tuple[float, ...]],
487
+ channels: int = 3,
488
+ target_mode: str | None = None,
489
+ ) -> Color3DLUT:
490
+ """Generates new LUT using provided callback.
491
+
492
+ :param size: Size of the table. Passed to the constructor.
493
+ :param callback: Function with three parameters which correspond
494
+ three color channels. Will be called ``size**3``
495
+ times with values from 0.0 to 1.0 and should return
496
+ a tuple with ``channels`` elements.
497
+ :param channels: The number of channels which should return callback.
498
+ :param target_mode: Passed to the constructor of the resulting
499
+ lookup table.
500
+ """
501
+ size_1d, size_2d, size_3d = cls._check_size(size)
502
+ if channels not in (3, 4):
503
+ msg = "Only 3 or 4 output channels are supported"
504
+ raise ValueError(msg)
505
+
506
+ table: list[float] = [0] * (size_1d * size_2d * size_3d * channels)
507
+ idx_out = 0
508
+ for b in range(size_3d):
509
+ for g in range(size_2d):
510
+ for r in range(size_1d):
511
+ table[idx_out : idx_out + channels] = callback(
512
+ r / (size_1d - 1), g / (size_2d - 1), b / (size_3d - 1)
513
+ )
514
+ idx_out += channels
515
+
516
+ return cls(
517
+ (size_1d, size_2d, size_3d),
518
+ table,
519
+ channels=channels,
520
+ target_mode=target_mode,
521
+ _copy_table=False,
522
+ )
523
+
524
+ def transform(
525
+ self,
526
+ callback: Callable[..., tuple[float, ...]],
527
+ with_normals: bool = False,
528
+ channels: int | None = None,
529
+ target_mode: str | None = None,
530
+ ) -> Color3DLUT:
531
+ """Transforms the table values using provided callback and returns
532
+ a new LUT with altered values.
533
+
534
+ :param callback: A function which takes old lookup table values
535
+ and returns a new set of values. The number
536
+ of arguments which function should take is
537
+ ``self.channels`` or ``3 + self.channels``
538
+ if ``with_normals`` flag is set.
539
+ Should return a tuple of ``self.channels`` or
540
+ ``channels`` elements if it is set.
541
+ :param with_normals: If true, ``callback`` will be called with
542
+ coordinates in the color cube as the first
543
+ three arguments. Otherwise, ``callback``
544
+ will be called only with actual color values.
545
+ :param channels: The number of channels in the resulting lookup table.
546
+ :param target_mode: Passed to the constructor of the resulting
547
+ lookup table.
548
+ """
549
+ if channels not in (None, 3, 4):
550
+ msg = "Only 3 or 4 output channels are supported"
551
+ raise ValueError(msg)
552
+ ch_in = self.channels
553
+ ch_out = channels or ch_in
554
+ size_1d, size_2d, size_3d = self.size
555
+
556
+ table: list[float] = [0] * (size_1d * size_2d * size_3d * ch_out)
557
+ idx_in = 0
558
+ idx_out = 0
559
+ for b in range(size_3d):
560
+ for g in range(size_2d):
561
+ for r in range(size_1d):
562
+ values = self.table[idx_in : idx_in + ch_in]
563
+ if with_normals:
564
+ values = callback(
565
+ r / (size_1d - 1),
566
+ g / (size_2d - 1),
567
+ b / (size_3d - 1),
568
+ *values,
569
+ )
570
+ else:
571
+ values = callback(*values)
572
+ table[idx_out : idx_out + ch_out] = values
573
+ idx_in += ch_in
574
+ idx_out += ch_out
575
+
576
+ return type(self)(
577
+ self.size,
578
+ table,
579
+ channels=ch_out,
580
+ target_mode=target_mode or self.mode,
581
+ _copy_table=False,
582
+ )
583
+
584
+ def __repr__(self) -> str:
585
+ r = [
586
+ f"{self.__class__.__name__} from {self.table.__class__.__name__}",
587
+ "size={:d}x{:d}x{:d}".format(*self.size),
588
+ f"channels={self.channels:d}",
589
+ ]
590
+ if self.mode:
591
+ r.append(f"target_mode={self.mode}")
592
+ return "<{}>".format(" ".join(r))
593
+
594
+ def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
595
+ from . import Image
596
+
597
+ return image.color_lut_3d(
598
+ self.mode or image.mode,
599
+ Image.Resampling.BILINEAR,
600
+ self.channels,
601
+ self.size[0],
602
+ self.size[1],
603
+ self.size[2],
604
+ self.table,
605
+ )
phi4/lib/python3.10/site-packages/PIL/ImageMode.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # standard mode descriptors
6
+ #
7
+ # History:
8
+ # 2006-03-20 fl Added
9
+ #
10
+ # Copyright (c) 2006 by Secret Labs AB.
11
+ # Copyright (c) 2006 by Fredrik Lundh.
12
+ #
13
+ # See the README file for information on usage and redistribution.
14
+ #
15
+ from __future__ import annotations
16
+
17
+ import sys
18
+ from functools import lru_cache
19
+ from typing import NamedTuple
20
+
21
+ from ._deprecate import deprecate
22
+
23
+
24
+ class ModeDescriptor(NamedTuple):
25
+ """Wrapper for mode strings."""
26
+
27
+ mode: str
28
+ bands: tuple[str, ...]
29
+ basemode: str
30
+ basetype: str
31
+ typestr: str
32
+
33
+ def __str__(self) -> str:
34
+ return self.mode
35
+
36
+
37
+ @lru_cache
38
+ def getmode(mode: str) -> ModeDescriptor:
39
+ """Gets a mode descriptor for the given mode."""
40
+ endian = "<" if sys.byteorder == "little" else ">"
41
+
42
+ modes = {
43
+ # core modes
44
+ # Bits need to be extended to bytes
45
+ "1": ("L", "L", ("1",), "|b1"),
46
+ "L": ("L", "L", ("L",), "|u1"),
47
+ "I": ("L", "I", ("I",), f"{endian}i4"),
48
+ "F": ("L", "F", ("F",), f"{endian}f4"),
49
+ "P": ("P", "L", ("P",), "|u1"),
50
+ "RGB": ("RGB", "L", ("R", "G", "B"), "|u1"),
51
+ "RGBX": ("RGB", "L", ("R", "G", "B", "X"), "|u1"),
52
+ "RGBA": ("RGB", "L", ("R", "G", "B", "A"), "|u1"),
53
+ "CMYK": ("RGB", "L", ("C", "M", "Y", "K"), "|u1"),
54
+ "YCbCr": ("RGB", "L", ("Y", "Cb", "Cr"), "|u1"),
55
+ # UNDONE - unsigned |u1i1i1
56
+ "LAB": ("RGB", "L", ("L", "A", "B"), "|u1"),
57
+ "HSV": ("RGB", "L", ("H", "S", "V"), "|u1"),
58
+ # extra experimental modes
59
+ "RGBa": ("RGB", "L", ("R", "G", "B", "a"), "|u1"),
60
+ "BGR;15": ("RGB", "L", ("B", "G", "R"), "|u1"),
61
+ "BGR;16": ("RGB", "L", ("B", "G", "R"), "|u1"),
62
+ "BGR;24": ("RGB", "L", ("B", "G", "R"), "|u1"),
63
+ "LA": ("L", "L", ("L", "A"), "|u1"),
64
+ "La": ("L", "L", ("L", "a"), "|u1"),
65
+ "PA": ("RGB", "L", ("P", "A"), "|u1"),
66
+ }
67
+ if mode in modes:
68
+ if mode in ("BGR;15", "BGR;16", "BGR;24"):
69
+ deprecate(mode, 12)
70
+ base_mode, base_type, bands, type_str = modes[mode]
71
+ return ModeDescriptor(mode, bands, base_mode, base_type, type_str)
72
+
73
+ mapping_modes = {
74
+ # I;16 == I;16L, and I;32 == I;32L
75
+ "I;16": "<u2",
76
+ "I;16S": "<i2",
77
+ "I;16L": "<u2",
78
+ "I;16LS": "<i2",
79
+ "I;16B": ">u2",
80
+ "I;16BS": ">i2",
81
+ "I;16N": f"{endian}u2",
82
+ "I;16NS": f"{endian}i2",
83
+ "I;32": "<u4",
84
+ "I;32B": ">u4",
85
+ "I;32L": "<u4",
86
+ "I;32S": "<i4",
87
+ "I;32BS": ">i4",
88
+ "I;32LS": "<i4",
89
+ }
90
+
91
+ type_str = mapping_modes[mode]
92
+ return ModeDescriptor(mode, ("I",), "L", "L", type_str)
phi4/lib/python3.10/site-packages/PIL/ImagePath.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library
3
+ # $Id$
4
+ #
5
+ # path interface
6
+ #
7
+ # History:
8
+ # 1996-11-04 fl Created
9
+ # 2002-04-14 fl Added documentation stub class
10
+ #
11
+ # Copyright (c) Secret Labs AB 1997.
12
+ # Copyright (c) Fredrik Lundh 1996.
13
+ #
14
+ # See the README file for information on usage and redistribution.
15
+ #
16
+ from __future__ import annotations
17
+
18
+ from . import Image
19
+
20
+ Path = Image.core.path
phi4/lib/python3.10/site-packages/PIL/ImageShow.py ADDED
@@ -0,0 +1,360 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # im.show() drivers
6
+ #
7
+ # History:
8
+ # 2008-04-06 fl Created
9
+ #
10
+ # Copyright (c) Secret Labs AB 2008.
11
+ #
12
+ # See the README file for information on usage and redistribution.
13
+ #
14
+ from __future__ import annotations
15
+
16
+ import abc
17
+ import os
18
+ import shutil
19
+ import subprocess
20
+ import sys
21
+ from shlex import quote
22
+ from typing import Any
23
+
24
+ from . import Image
25
+
26
+ _viewers = []
27
+
28
+
29
+ def register(viewer: type[Viewer] | Viewer, order: int = 1) -> None:
30
+ """
31
+ The :py:func:`register` function is used to register additional viewers::
32
+
33
+ from PIL import ImageShow
34
+ ImageShow.register(MyViewer()) # MyViewer will be used as a last resort
35
+ ImageShow.register(MySecondViewer(), 0) # MySecondViewer will be prioritised
36
+ ImageShow.register(ImageShow.XVViewer(), 0) # XVViewer will be prioritised
37
+
38
+ :param viewer: The viewer to be registered.
39
+ :param order:
40
+ Zero or a negative integer to prepend this viewer to the list,
41
+ a positive integer to append it.
42
+ """
43
+ if isinstance(viewer, type) and issubclass(viewer, Viewer):
44
+ viewer = viewer()
45
+ if order > 0:
46
+ _viewers.append(viewer)
47
+ else:
48
+ _viewers.insert(0, viewer)
49
+
50
+
51
+ def show(image: Image.Image, title: str | None = None, **options: Any) -> bool:
52
+ r"""
53
+ Display a given image.
54
+
55
+ :param image: An image object.
56
+ :param title: Optional title. Not all viewers can display the title.
57
+ :param \**options: Additional viewer options.
58
+ :returns: ``True`` if a suitable viewer was found, ``False`` otherwise.
59
+ """
60
+ for viewer in _viewers:
61
+ if viewer.show(image, title=title, **options):
62
+ return True
63
+ return False
64
+
65
+
66
+ class Viewer:
67
+ """Base class for viewers."""
68
+
69
+ # main api
70
+
71
+ def show(self, image: Image.Image, **options: Any) -> int:
72
+ """
73
+ The main function for displaying an image.
74
+ Converts the given image to the target format and displays it.
75
+ """
76
+
77
+ if not (
78
+ image.mode in ("1", "RGBA")
79
+ or (self.format == "PNG" and image.mode in ("I;16", "LA"))
80
+ ):
81
+ base = Image.getmodebase(image.mode)
82
+ if image.mode != base:
83
+ image = image.convert(base)
84
+
85
+ return self.show_image(image, **options)
86
+
87
+ # hook methods
88
+
89
+ format: str | None = None
90
+ """The format to convert the image into."""
91
+ options: dict[str, Any] = {}
92
+ """Additional options used to convert the image."""
93
+
94
+ def get_format(self, image: Image.Image) -> str | None:
95
+ """Return format name, or ``None`` to save as PGM/PPM."""
96
+ return self.format
97
+
98
+ def get_command(self, file: str, **options: Any) -> str:
99
+ """
100
+ Returns the command used to display the file.
101
+ Not implemented in the base class.
102
+ """
103
+ msg = "unavailable in base viewer"
104
+ raise NotImplementedError(msg)
105
+
106
+ def save_image(self, image: Image.Image) -> str:
107
+ """Save to temporary file and return filename."""
108
+ return image._dump(format=self.get_format(image), **self.options)
109
+
110
+ def show_image(self, image: Image.Image, **options: Any) -> int:
111
+ """Display the given image."""
112
+ return self.show_file(self.save_image(image), **options)
113
+
114
+ def show_file(self, path: str, **options: Any) -> int:
115
+ """
116
+ Display given file.
117
+ """
118
+ if not os.path.exists(path):
119
+ raise FileNotFoundError
120
+ os.system(self.get_command(path, **options)) # nosec
121
+ return 1
122
+
123
+
124
+ # --------------------------------------------------------------------
125
+
126
+
127
+ class WindowsViewer(Viewer):
128
+ """The default viewer on Windows is the default system application for PNG files."""
129
+
130
+ format = "PNG"
131
+ options = {"compress_level": 1, "save_all": True}
132
+
133
+ def get_command(self, file: str, **options: Any) -> str:
134
+ return (
135
+ f'start "Pillow" /WAIT "{file}" '
136
+ "&& ping -n 4 127.0.0.1 >NUL "
137
+ f'&& del /f "{file}"'
138
+ )
139
+
140
+ def show_file(self, path: str, **options: Any) -> int:
141
+ """
142
+ Display given file.
143
+ """
144
+ if not os.path.exists(path):
145
+ raise FileNotFoundError
146
+ subprocess.Popen(
147
+ self.get_command(path, **options),
148
+ shell=True,
149
+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW"),
150
+ ) # nosec
151
+ return 1
152
+
153
+
154
+ if sys.platform == "win32":
155
+ register(WindowsViewer)
156
+
157
+
158
+ class MacViewer(Viewer):
159
+ """The default viewer on macOS using ``Preview.app``."""
160
+
161
+ format = "PNG"
162
+ options = {"compress_level": 1, "save_all": True}
163
+
164
+ def get_command(self, file: str, **options: Any) -> str:
165
+ # on darwin open returns immediately resulting in the temp
166
+ # file removal while app is opening
167
+ command = "open -a Preview.app"
168
+ command = f"({command} {quote(file)}; sleep 20; rm -f {quote(file)})&"
169
+ return command
170
+
171
+ def show_file(self, path: str, **options: Any) -> int:
172
+ """
173
+ Display given file.
174
+ """
175
+ if not os.path.exists(path):
176
+ raise FileNotFoundError
177
+ subprocess.call(["open", "-a", "Preview.app", path])
178
+ executable = sys.executable or shutil.which("python3")
179
+ if executable:
180
+ subprocess.Popen(
181
+ [
182
+ executable,
183
+ "-c",
184
+ "import os, sys, time; time.sleep(20); os.remove(sys.argv[1])",
185
+ path,
186
+ ]
187
+ )
188
+ return 1
189
+
190
+
191
+ if sys.platform == "darwin":
192
+ register(MacViewer)
193
+
194
+
195
+ class UnixViewer(Viewer):
196
+ format = "PNG"
197
+ options = {"compress_level": 1, "save_all": True}
198
+
199
+ @abc.abstractmethod
200
+ def get_command_ex(self, file: str, **options: Any) -> tuple[str, str]:
201
+ pass
202
+
203
+ def get_command(self, file: str, **options: Any) -> str:
204
+ command = self.get_command_ex(file, **options)[0]
205
+ return f"{command} {quote(file)}"
206
+
207
+
208
+ class XDGViewer(UnixViewer):
209
+ """
210
+ The freedesktop.org ``xdg-open`` command.
211
+ """
212
+
213
+ def get_command_ex(self, file: str, **options: Any) -> tuple[str, str]:
214
+ command = executable = "xdg-open"
215
+ return command, executable
216
+
217
+ def show_file(self, path: str, **options: Any) -> int:
218
+ """
219
+ Display given file.
220
+ """
221
+ if not os.path.exists(path):
222
+ raise FileNotFoundError
223
+ subprocess.Popen(["xdg-open", path])
224
+ return 1
225
+
226
+
227
+ class DisplayViewer(UnixViewer):
228
+ """
229
+ The ImageMagick ``display`` command.
230
+ This viewer supports the ``title`` parameter.
231
+ """
232
+
233
+ def get_command_ex(
234
+ self, file: str, title: str | None = None, **options: Any
235
+ ) -> tuple[str, str]:
236
+ command = executable = "display"
237
+ if title:
238
+ command += f" -title {quote(title)}"
239
+ return command, executable
240
+
241
+ def show_file(self, path: str, **options: Any) -> int:
242
+ """
243
+ Display given file.
244
+ """
245
+ if not os.path.exists(path):
246
+ raise FileNotFoundError
247
+ args = ["display"]
248
+ title = options.get("title")
249
+ if title:
250
+ args += ["-title", title]
251
+ args.append(path)
252
+
253
+ subprocess.Popen(args)
254
+ return 1
255
+
256
+
257
+ class GmDisplayViewer(UnixViewer):
258
+ """The GraphicsMagick ``gm display`` command."""
259
+
260
+ def get_command_ex(self, file: str, **options: Any) -> tuple[str, str]:
261
+ executable = "gm"
262
+ command = "gm display"
263
+ return command, executable
264
+
265
+ def show_file(self, path: str, **options: Any) -> int:
266
+ """
267
+ Display given file.
268
+ """
269
+ if not os.path.exists(path):
270
+ raise FileNotFoundError
271
+ subprocess.Popen(["gm", "display", path])
272
+ return 1
273
+
274
+
275
+ class EogViewer(UnixViewer):
276
+ """The GNOME Image Viewer ``eog`` command."""
277
+
278
+ def get_command_ex(self, file: str, **options: Any) -> tuple[str, str]:
279
+ executable = "eog"
280
+ command = "eog -n"
281
+ return command, executable
282
+
283
+ def show_file(self, path: str, **options: Any) -> int:
284
+ """
285
+ Display given file.
286
+ """
287
+ if not os.path.exists(path):
288
+ raise FileNotFoundError
289
+ subprocess.Popen(["eog", "-n", path])
290
+ return 1
291
+
292
+
293
+ class XVViewer(UnixViewer):
294
+ """
295
+ The X Viewer ``xv`` command.
296
+ This viewer supports the ``title`` parameter.
297
+ """
298
+
299
+ def get_command_ex(
300
+ self, file: str, title: str | None = None, **options: Any
301
+ ) -> tuple[str, str]:
302
+ # note: xv is pretty outdated. most modern systems have
303
+ # imagemagick's display command instead.
304
+ command = executable = "xv"
305
+ if title:
306
+ command += f" -name {quote(title)}"
307
+ return command, executable
308
+
309
+ def show_file(self, path: str, **options: Any) -> int:
310
+ """
311
+ Display given file.
312
+ """
313
+ if not os.path.exists(path):
314
+ raise FileNotFoundError
315
+ args = ["xv"]
316
+ title = options.get("title")
317
+ if title:
318
+ args += ["-name", title]
319
+ args.append(path)
320
+
321
+ subprocess.Popen(args)
322
+ return 1
323
+
324
+
325
+ if sys.platform not in ("win32", "darwin"): # unixoids
326
+ if shutil.which("xdg-open"):
327
+ register(XDGViewer)
328
+ if shutil.which("display"):
329
+ register(DisplayViewer)
330
+ if shutil.which("gm"):
331
+ register(GmDisplayViewer)
332
+ if shutil.which("eog"):
333
+ register(EogViewer)
334
+ if shutil.which("xv"):
335
+ register(XVViewer)
336
+
337
+
338
+ class IPythonViewer(Viewer):
339
+ """The viewer for IPython frontends."""
340
+
341
+ def show_image(self, image: Image.Image, **options: Any) -> int:
342
+ ipython_display(image)
343
+ return 1
344
+
345
+
346
+ try:
347
+ from IPython.display import display as ipython_display
348
+ except ImportError:
349
+ pass
350
+ else:
351
+ register(IPythonViewer)
352
+
353
+
354
+ if __name__ == "__main__":
355
+ if len(sys.argv) < 2:
356
+ print("Syntax: python3 ImageShow.py imagefile [title]")
357
+ sys.exit()
358
+
359
+ with Image.open(sys.argv[1]) as im:
360
+ print(show(im, *sys.argv[2:]))
phi4/lib/python3.10/site-packages/PIL/ImageTk.py ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # a Tk display interface
6
+ #
7
+ # History:
8
+ # 96-04-08 fl Created
9
+ # 96-09-06 fl Added getimage method
10
+ # 96-11-01 fl Rewritten, removed image attribute and crop method
11
+ # 97-05-09 fl Use PyImagingPaste method instead of image type
12
+ # 97-05-12 fl Minor tweaks to match the IFUNC95 interface
13
+ # 97-05-17 fl Support the "pilbitmap" booster patch
14
+ # 97-06-05 fl Added file= and data= argument to image constructors
15
+ # 98-03-09 fl Added width and height methods to Image classes
16
+ # 98-07-02 fl Use default mode for "P" images without palette attribute
17
+ # 98-07-02 fl Explicitly destroy Tkinter image objects
18
+ # 99-07-24 fl Support multiple Tk interpreters (from Greg Couch)
19
+ # 99-07-26 fl Automatically hook into Tkinter (if possible)
20
+ # 99-08-15 fl Hook uses _imagingtk instead of _imaging
21
+ #
22
+ # Copyright (c) 1997-1999 by Secret Labs AB
23
+ # Copyright (c) 1996-1997 by Fredrik Lundh
24
+ #
25
+ # See the README file for information on usage and redistribution.
26
+ #
27
+ from __future__ import annotations
28
+
29
+ import tkinter
30
+ from io import BytesIO
31
+ from typing import TYPE_CHECKING, Any, cast
32
+
33
+ from . import Image, ImageFile
34
+
35
+ if TYPE_CHECKING:
36
+ from ._typing import CapsuleType
37
+
38
+ # --------------------------------------------------------------------
39
+ # Check for Tkinter interface hooks
40
+
41
+
42
+ def _get_image_from_kw(kw: dict[str, Any]) -> ImageFile.ImageFile | None:
43
+ source = None
44
+ if "file" in kw:
45
+ source = kw.pop("file")
46
+ elif "data" in kw:
47
+ source = BytesIO(kw.pop("data"))
48
+ if not source:
49
+ return None
50
+ return Image.open(source)
51
+
52
+
53
+ def _pyimagingtkcall(
54
+ command: str, photo: PhotoImage | tkinter.PhotoImage, ptr: CapsuleType
55
+ ) -> None:
56
+ tk = photo.tk
57
+ try:
58
+ tk.call(command, photo, repr(ptr))
59
+ except tkinter.TclError:
60
+ # activate Tkinter hook
61
+ # may raise an error if it cannot attach to Tkinter
62
+ from . import _imagingtk
63
+
64
+ _imagingtk.tkinit(tk.interpaddr())
65
+ tk.call(command, photo, repr(ptr))
66
+
67
+
68
+ # --------------------------------------------------------------------
69
+ # PhotoImage
70
+
71
+
72
+ class PhotoImage:
73
+ """
74
+ A Tkinter-compatible photo image. This can be used
75
+ everywhere Tkinter expects an image object. If the image is an RGBA
76
+ image, pixels having alpha 0 are treated as transparent.
77
+
78
+ The constructor takes either a PIL image, or a mode and a size.
79
+ Alternatively, you can use the ``file`` or ``data`` options to initialize
80
+ the photo image object.
81
+
82
+ :param image: Either a PIL image, or a mode string. If a mode string is
83
+ used, a size must also be given.
84
+ :param size: If the first argument is a mode string, this defines the size
85
+ of the image.
86
+ :keyword file: A filename to load the image from (using
87
+ ``Image.open(file)``).
88
+ :keyword data: An 8-bit string containing image data (as loaded from an
89
+ image file).
90
+ """
91
+
92
+ def __init__(
93
+ self,
94
+ image: Image.Image | str | None = None,
95
+ size: tuple[int, int] | None = None,
96
+ **kw: Any,
97
+ ) -> None:
98
+ # Tk compatibility: file or data
99
+ if image is None:
100
+ image = _get_image_from_kw(kw)
101
+
102
+ if image is None:
103
+ msg = "Image is required"
104
+ raise ValueError(msg)
105
+ elif isinstance(image, str):
106
+ mode = image
107
+ image = None
108
+
109
+ if size is None:
110
+ msg = "If first argument is mode, size is required"
111
+ raise ValueError(msg)
112
+ else:
113
+ # got an image instead of a mode
114
+ mode = image.mode
115
+ if mode == "P":
116
+ # palette mapped data
117
+ image.apply_transparency()
118
+ image.load()
119
+ mode = image.palette.mode if image.palette else "RGB"
120
+ size = image.size
121
+ kw["width"], kw["height"] = size
122
+
123
+ if mode not in ["1", "L", "RGB", "RGBA"]:
124
+ mode = Image.getmodebase(mode)
125
+
126
+ self.__mode = mode
127
+ self.__size = size
128
+ self.__photo = tkinter.PhotoImage(**kw)
129
+ self.tk = self.__photo.tk
130
+ if image:
131
+ self.paste(image)
132
+
133
+ def __del__(self) -> None:
134
+ try:
135
+ name = self.__photo.name
136
+ except AttributeError:
137
+ return
138
+ self.__photo.name = None
139
+ try:
140
+ self.__photo.tk.call("image", "delete", name)
141
+ except Exception:
142
+ pass # ignore internal errors
143
+
144
+ def __str__(self) -> str:
145
+ """
146
+ Get the Tkinter photo image identifier. This method is automatically
147
+ called by Tkinter whenever a PhotoImage object is passed to a Tkinter
148
+ method.
149
+
150
+ :return: A Tkinter photo image identifier (a string).
151
+ """
152
+ return str(self.__photo)
153
+
154
+ def width(self) -> int:
155
+ """
156
+ Get the width of the image.
157
+
158
+ :return: The width, in pixels.
159
+ """
160
+ return self.__size[0]
161
+
162
+ def height(self) -> int:
163
+ """
164
+ Get the height of the image.
165
+
166
+ :return: The height, in pixels.
167
+ """
168
+ return self.__size[1]
169
+
170
+ def paste(self, im: Image.Image) -> None:
171
+ """
172
+ Paste a PIL image into the photo image. Note that this can
173
+ be very slow if the photo image is displayed.
174
+
175
+ :param im: A PIL image. The size must match the target region. If the
176
+ mode does not match, the image is converted to the mode of
177
+ the bitmap image.
178
+ """
179
+ # convert to blittable
180
+ ptr = im.getim()
181
+ image = im.im
182
+ if not image.isblock() or im.mode != self.__mode:
183
+ block = Image.core.new_block(self.__mode, im.size)
184
+ image.convert2(block, image) # convert directly between buffers
185
+ ptr = block.ptr
186
+
187
+ _pyimagingtkcall("PyImagingPhoto", self.__photo, ptr)
188
+
189
+
190
+ # --------------------------------------------------------------------
191
+ # BitmapImage
192
+
193
+
194
+ class BitmapImage:
195
+ """
196
+ A Tkinter-compatible bitmap image. This can be used everywhere Tkinter
197
+ expects an image object.
198
+
199
+ The given image must have mode "1". Pixels having value 0 are treated as
200
+ transparent. Options, if any, are passed on to Tkinter. The most commonly
201
+ used option is ``foreground``, which is used to specify the color for the
202
+ non-transparent parts. See the Tkinter documentation for information on
203
+ how to specify colours.
204
+
205
+ :param image: A PIL image.
206
+ """
207
+
208
+ def __init__(self, image: Image.Image | None = None, **kw: Any) -> None:
209
+ # Tk compatibility: file or data
210
+ if image is None:
211
+ image = _get_image_from_kw(kw)
212
+
213
+ if image is None:
214
+ msg = "Image is required"
215
+ raise ValueError(msg)
216
+ self.__mode = image.mode
217
+ self.__size = image.size
218
+
219
+ self.__photo = tkinter.BitmapImage(data=image.tobitmap(), **kw)
220
+
221
+ def __del__(self) -> None:
222
+ try:
223
+ name = self.__photo.name
224
+ except AttributeError:
225
+ return
226
+ self.__photo.name = None
227
+ try:
228
+ self.__photo.tk.call("image", "delete", name)
229
+ except Exception:
230
+ pass # ignore internal errors
231
+
232
+ def width(self) -> int:
233
+ """
234
+ Get the width of the image.
235
+
236
+ :return: The width, in pixels.
237
+ """
238
+ return self.__size[0]
239
+
240
+ def height(self) -> int:
241
+ """
242
+ Get the height of the image.
243
+
244
+ :return: The height, in pixels.
245
+ """
246
+ return self.__size[1]
247
+
248
+ def __str__(self) -> str:
249
+ """
250
+ Get the Tkinter bitmap image identifier. This method is automatically
251
+ called by Tkinter whenever a BitmapImage object is passed to a Tkinter
252
+ method.
253
+
254
+ :return: A Tkinter bitmap image identifier (a string).
255
+ """
256
+ return str(self.__photo)
257
+
258
+
259
+ def getimage(photo: PhotoImage) -> Image.Image:
260
+ """Copies the contents of a PhotoImage to a PIL image memory."""
261
+ im = Image.new("RGBA", (photo.width(), photo.height()))
262
+
263
+ _pyimagingtkcall("PyImagingPhotoGet", photo, im.getim())
264
+
265
+ return im
266
+
267
+
268
+ def _show(image: Image.Image, title: str | None) -> None:
269
+ """Helper for the Image.show method."""
270
+
271
+ class UI(tkinter.Label):
272
+ def __init__(self, master: tkinter.Toplevel, im: Image.Image) -> None:
273
+ self.image: BitmapImage | PhotoImage
274
+ if im.mode == "1":
275
+ self.image = BitmapImage(im, foreground="white", master=master)
276
+ else:
277
+ self.image = PhotoImage(im, master=master)
278
+ if TYPE_CHECKING:
279
+ image = cast(tkinter._Image, self.image)
280
+ else:
281
+ image = self.image
282
+ super().__init__(master, image=image, bg="black", bd=0)
283
+
284
+ if not getattr(tkinter, "_default_root"):
285
+ msg = "tkinter not initialized"
286
+ raise OSError(msg)
287
+ top = tkinter.Toplevel()
288
+ if title:
289
+ top.title(title)
290
+ UI(top, image).pack()
phi4/lib/python3.10/site-packages/PIL/ImageTransform.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # transform wrappers
6
+ #
7
+ # History:
8
+ # 2002-04-08 fl Created
9
+ #
10
+ # Copyright (c) 2002 by Secret Labs AB
11
+ # Copyright (c) 2002 by Fredrik Lundh
12
+ #
13
+ # See the README file for information on usage and redistribution.
14
+ #
15
+ from __future__ import annotations
16
+
17
+ from collections.abc import Sequence
18
+ from typing import Any
19
+
20
+ from . import Image
21
+
22
+
23
+ class Transform(Image.ImageTransformHandler):
24
+ """Base class for other transforms defined in :py:mod:`~PIL.ImageTransform`."""
25
+
26
+ method: Image.Transform
27
+
28
+ def __init__(self, data: Sequence[Any]) -> None:
29
+ self.data = data
30
+
31
+ def getdata(self) -> tuple[Image.Transform, Sequence[int]]:
32
+ return self.method, self.data
33
+
34
+ def transform(
35
+ self,
36
+ size: tuple[int, int],
37
+ image: Image.Image,
38
+ **options: Any,
39
+ ) -> Image.Image:
40
+ """Perform the transform. Called from :py:meth:`.Image.transform`."""
41
+ # can be overridden
42
+ method, data = self.getdata()
43
+ return image.transform(size, method, data, **options)
44
+
45
+
46
+ class AffineTransform(Transform):
47
+ """
48
+ Define an affine image transform.
49
+
50
+ This function takes a 6-tuple (a, b, c, d, e, f) which contain the first
51
+ two rows from an affine transform matrix. For each pixel (x, y) in the
52
+ output image, the new value is taken from a position (a x + b y + c,
53
+ d x + e y + f) in the input image, rounded to nearest pixel.
54
+
55
+ This function can be used to scale, translate, rotate, and shear the
56
+ original image.
57
+
58
+ See :py:meth:`.Image.transform`
59
+
60
+ :param matrix: A 6-tuple (a, b, c, d, e, f) containing the first two rows
61
+ from an affine transform matrix.
62
+ """
63
+
64
+ method = Image.Transform.AFFINE
65
+
66
+
67
+ class PerspectiveTransform(Transform):
68
+ """
69
+ Define a perspective image transform.
70
+
71
+ This function takes an 8-tuple (a, b, c, d, e, f, g, h). For each pixel
72
+ (x, y) in the output image, the new value is taken from a position
73
+ ((a x + b y + c) / (g x + h y + 1), (d x + e y + f) / (g x + h y + 1)) in
74
+ the input image, rounded to nearest pixel.
75
+
76
+ This function can be used to scale, translate, rotate, and shear the
77
+ original image.
78
+
79
+ See :py:meth:`.Image.transform`
80
+
81
+ :param matrix: An 8-tuple (a, b, c, d, e, f, g, h).
82
+ """
83
+
84
+ method = Image.Transform.PERSPECTIVE
85
+
86
+
87
+ class ExtentTransform(Transform):
88
+ """
89
+ Define a transform to extract a subregion from an image.
90
+
91
+ Maps a rectangle (defined by two corners) from the image to a rectangle of
92
+ the given size. The resulting image will contain data sampled from between
93
+ the corners, such that (x0, y0) in the input image will end up at (0,0) in
94
+ the output image, and (x1, y1) at size.
95
+
96
+ This method can be used to crop, stretch, shrink, or mirror an arbitrary
97
+ rectangle in the current image. It is slightly slower than crop, but about
98
+ as fast as a corresponding resize operation.
99
+
100
+ See :py:meth:`.Image.transform`
101
+
102
+ :param bbox: A 4-tuple (x0, y0, x1, y1) which specifies two points in the
103
+ input image's coordinate system. See :ref:`coordinate-system`.
104
+ """
105
+
106
+ method = Image.Transform.EXTENT
107
+
108
+
109
+ class QuadTransform(Transform):
110
+ """
111
+ Define a quad image transform.
112
+
113
+ Maps a quadrilateral (a region defined by four corners) from the image to a
114
+ rectangle of the given size.
115
+
116
+ See :py:meth:`.Image.transform`
117
+
118
+ :param xy: An 8-tuple (x0, y0, x1, y1, x2, y2, x3, y3) which contain the
119
+ upper left, lower left, lower right, and upper right corner of the
120
+ source quadrilateral.
121
+ """
122
+
123
+ method = Image.Transform.QUAD
124
+
125
+
126
+ class MeshTransform(Transform):
127
+ """
128
+ Define a mesh image transform. A mesh transform consists of one or more
129
+ individual quad transforms.
130
+
131
+ See :py:meth:`.Image.transform`
132
+
133
+ :param data: A list of (bbox, quad) tuples.
134
+ """
135
+
136
+ method = Image.Transform.MESH
phi4/lib/python3.10/site-packages/PIL/ImageWin.py ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # a Windows DIB display interface
6
+ #
7
+ # History:
8
+ # 1996-05-20 fl Created
9
+ # 1996-09-20 fl Fixed subregion exposure
10
+ # 1997-09-21 fl Added draw primitive (for tzPrint)
11
+ # 2003-05-21 fl Added experimental Window/ImageWindow classes
12
+ # 2003-09-05 fl Added fromstring/tostring methods
13
+ #
14
+ # Copyright (c) Secret Labs AB 1997-2003.
15
+ # Copyright (c) Fredrik Lundh 1996-2003.
16
+ #
17
+ # See the README file for information on usage and redistribution.
18
+ #
19
+ from __future__ import annotations
20
+
21
+ from . import Image
22
+
23
+
24
+ class HDC:
25
+ """
26
+ Wraps an HDC integer. The resulting object can be passed to the
27
+ :py:meth:`~PIL.ImageWin.Dib.draw` and :py:meth:`~PIL.ImageWin.Dib.expose`
28
+ methods.
29
+ """
30
+
31
+ def __init__(self, dc: int) -> None:
32
+ self.dc = dc
33
+
34
+ def __int__(self) -> int:
35
+ return self.dc
36
+
37
+
38
+ class HWND:
39
+ """
40
+ Wraps an HWND integer. The resulting object can be passed to the
41
+ :py:meth:`~PIL.ImageWin.Dib.draw` and :py:meth:`~PIL.ImageWin.Dib.expose`
42
+ methods, instead of a DC.
43
+ """
44
+
45
+ def __init__(self, wnd: int) -> None:
46
+ self.wnd = wnd
47
+
48
+ def __int__(self) -> int:
49
+ return self.wnd
50
+
51
+
52
+ class Dib:
53
+ """
54
+ A Windows bitmap with the given mode and size. The mode can be one of "1",
55
+ "L", "P", or "RGB".
56
+
57
+ If the display requires a palette, this constructor creates a suitable
58
+ palette and associates it with the image. For an "L" image, 128 graylevels
59
+ are allocated. For an "RGB" image, a 6x6x6 colour cube is used, together
60
+ with 20 graylevels.
61
+
62
+ To make sure that palettes work properly under Windows, you must call the
63
+ ``palette`` method upon certain events from Windows.
64
+
65
+ :param image: Either a PIL image, or a mode string. If a mode string is
66
+ used, a size must also be given. The mode can be one of "1",
67
+ "L", "P", or "RGB".
68
+ :param size: If the first argument is a mode string, this
69
+ defines the size of the image.
70
+ """
71
+
72
+ def __init__(
73
+ self, image: Image.Image | str, size: tuple[int, int] | None = None
74
+ ) -> None:
75
+ if isinstance(image, str):
76
+ mode = image
77
+ image = ""
78
+ if size is None:
79
+ msg = "If first argument is mode, size is required"
80
+ raise ValueError(msg)
81
+ else:
82
+ mode = image.mode
83
+ size = image.size
84
+ if mode not in ["1", "L", "P", "RGB"]:
85
+ mode = Image.getmodebase(mode)
86
+ self.image = Image.core.display(mode, size)
87
+ self.mode = mode
88
+ self.size = size
89
+ if image:
90
+ assert not isinstance(image, str)
91
+ self.paste(image)
92
+
93
+ def expose(self, handle: int | HDC | HWND) -> None:
94
+ """
95
+ Copy the bitmap contents to a device context.
96
+
97
+ :param handle: Device context (HDC), cast to a Python integer, or an
98
+ HDC or HWND instance. In PythonWin, you can use
99
+ ``CDC.GetHandleAttrib()`` to get a suitable handle.
100
+ """
101
+ handle_int = int(handle)
102
+ if isinstance(handle, HWND):
103
+ dc = self.image.getdc(handle_int)
104
+ try:
105
+ self.image.expose(dc)
106
+ finally:
107
+ self.image.releasedc(handle_int, dc)
108
+ else:
109
+ self.image.expose(handle_int)
110
+
111
+ def draw(
112
+ self,
113
+ handle: int | HDC | HWND,
114
+ dst: tuple[int, int, int, int],
115
+ src: tuple[int, int, int, int] | None = None,
116
+ ) -> None:
117
+ """
118
+ Same as expose, but allows you to specify where to draw the image, and
119
+ what part of it to draw.
120
+
121
+ The destination and source areas are given as 4-tuple rectangles. If
122
+ the source is omitted, the entire image is copied. If the source and
123
+ the destination have different sizes, the image is resized as
124
+ necessary.
125
+ """
126
+ if src is None:
127
+ src = (0, 0) + self.size
128
+ handle_int = int(handle)
129
+ if isinstance(handle, HWND):
130
+ dc = self.image.getdc(handle_int)
131
+ try:
132
+ self.image.draw(dc, dst, src)
133
+ finally:
134
+ self.image.releasedc(handle_int, dc)
135
+ else:
136
+ self.image.draw(handle_int, dst, src)
137
+
138
+ def query_palette(self, handle: int | HDC | HWND) -> int:
139
+ """
140
+ Installs the palette associated with the image in the given device
141
+ context.
142
+
143
+ This method should be called upon **QUERYNEWPALETTE** and
144
+ **PALETTECHANGED** events from Windows. If this method returns a
145
+ non-zero value, one or more display palette entries were changed, and
146
+ the image should be redrawn.
147
+
148
+ :param handle: Device context (HDC), cast to a Python integer, or an
149
+ HDC or HWND instance.
150
+ :return: The number of entries that were changed (if one or more entries,
151
+ this indicates that the image should be redrawn).
152
+ """
153
+ handle_int = int(handle)
154
+ if isinstance(handle, HWND):
155
+ handle = self.image.getdc(handle_int)
156
+ try:
157
+ result = self.image.query_palette(handle)
158
+ finally:
159
+ self.image.releasedc(handle, handle)
160
+ else:
161
+ result = self.image.query_palette(handle_int)
162
+ return result
163
+
164
+ def paste(
165
+ self, im: Image.Image, box: tuple[int, int, int, int] | None = None
166
+ ) -> None:
167
+ """
168
+ Paste a PIL image into the bitmap image.
169
+
170
+ :param im: A PIL image. The size must match the target region.
171
+ If the mode does not match, the image is converted to the
172
+ mode of the bitmap image.
173
+ :param box: A 4-tuple defining the left, upper, right, and
174
+ lower pixel coordinate. See :ref:`coordinate-system`. If
175
+ None is given instead of a tuple, all of the image is
176
+ assumed.
177
+ """
178
+ im.load()
179
+ if self.mode != im.mode:
180
+ im = im.convert(self.mode)
181
+ if box:
182
+ self.image.paste(im.im, box)
183
+ else:
184
+ self.image.paste(im.im)
185
+
186
+ def frombytes(self, buffer: bytes) -> None:
187
+ """
188
+ Load display memory contents from byte data.
189
+
190
+ :param buffer: A buffer containing display data (usually
191
+ data returned from :py:func:`~PIL.ImageWin.Dib.tobytes`)
192
+ """
193
+ self.image.frombytes(buffer)
194
+
195
+ def tobytes(self) -> bytes:
196
+ """
197
+ Copy display memory contents to bytes object.
198
+
199
+ :return: A bytes object containing display data.
200
+ """
201
+ return self.image.tobytes()
202
+
203
+
204
+ class Window:
205
+ """Create a Window with the given title size."""
206
+
207
+ def __init__(
208
+ self, title: str = "PIL", width: int | None = None, height: int | None = None
209
+ ) -> None:
210
+ self.hwnd = Image.core.createwindow(
211
+ title, self.__dispatcher, width or 0, height or 0
212
+ )
213
+
214
+ def __dispatcher(self, action: str, *args: int) -> None:
215
+ getattr(self, f"ui_handle_{action}")(*args)
216
+
217
+ def ui_handle_clear(self, dc: int, x0: int, y0: int, x1: int, y1: int) -> None:
218
+ pass
219
+
220
+ def ui_handle_damage(self, x0: int, y0: int, x1: int, y1: int) -> None:
221
+ pass
222
+
223
+ def ui_handle_destroy(self) -> None:
224
+ pass
225
+
226
+ def ui_handle_repair(self, dc: int, x0: int, y0: int, x1: int, y1: int) -> None:
227
+ pass
228
+
229
+ def ui_handle_resize(self, width: int, height: int) -> None:
230
+ pass
231
+
232
+ def mainloop(self) -> None:
233
+ Image.core.eventloop()
234
+
235
+
236
+ class ImageWindow(Window):
237
+ """Create an image window which displays the given image."""
238
+
239
+ def __init__(self, image: Image.Image | Dib, title: str = "PIL") -> None:
240
+ if not isinstance(image, Dib):
241
+ image = Dib(image)
242
+ self.image = image
243
+ width, height = image.size
244
+ super().__init__(title, width=width, height=height)
245
+
246
+ def ui_handle_repair(self, dc: int, x0: int, y0: int, x1: int, y1: int) -> None:
247
+ self.image.draw(dc, (x0, y0, x1, y1))
phi4/lib/python3.10/site-packages/PIL/ImtImagePlugin.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # IM Tools support for PIL
6
+ #
7
+ # history:
8
+ # 1996-05-27 fl Created (read 8-bit images only)
9
+ # 2001-02-17 fl Use 're' instead of 'regex' (Python 2.1) (0.2)
10
+ #
11
+ # Copyright (c) Secret Labs AB 1997-2001.
12
+ # Copyright (c) Fredrik Lundh 1996-2001.
13
+ #
14
+ # See the README file for information on usage and redistribution.
15
+ #
16
+ from __future__ import annotations
17
+
18
+ import re
19
+
20
+ from . import Image, ImageFile
21
+
22
+ #
23
+ # --------------------------------------------------------------------
24
+
25
+ field = re.compile(rb"([a-z]*) ([^ \r\n]*)")
26
+
27
+
28
+ ##
29
+ # Image plugin for IM Tools images.
30
+
31
+
32
+ class ImtImageFile(ImageFile.ImageFile):
33
+ format = "IMT"
34
+ format_description = "IM Tools"
35
+
36
+ def _open(self) -> None:
37
+ # Quick rejection: if there's not a LF among the first
38
+ # 100 bytes, this is (probably) not a text header.
39
+
40
+ assert self.fp is not None
41
+
42
+ buffer = self.fp.read(100)
43
+ if b"\n" not in buffer:
44
+ msg = "not an IM file"
45
+ raise SyntaxError(msg)
46
+
47
+ xsize = ysize = 0
48
+
49
+ while True:
50
+ if buffer:
51
+ s = buffer[:1]
52
+ buffer = buffer[1:]
53
+ else:
54
+ s = self.fp.read(1)
55
+ if not s:
56
+ break
57
+
58
+ if s == b"\x0C":
59
+ # image data begins
60
+ self.tile = [
61
+ ImageFile._Tile(
62
+ "raw",
63
+ (0, 0) + self.size,
64
+ self.fp.tell() - len(buffer),
65
+ self.mode,
66
+ )
67
+ ]
68
+
69
+ break
70
+
71
+ else:
72
+ # read key/value pair
73
+ if b"\n" not in buffer:
74
+ buffer += self.fp.read(100)
75
+ lines = buffer.split(b"\n")
76
+ s += lines.pop(0)
77
+ buffer = b"\n".join(lines)
78
+ if len(s) == 1 or len(s) > 100:
79
+ break
80
+ if s[0] == ord(b"*"):
81
+ continue # comment
82
+
83
+ m = field.match(s)
84
+ if not m:
85
+ break
86
+ k, v = m.group(1, 2)
87
+ if k == b"width":
88
+ xsize = int(v)
89
+ self._size = xsize, ysize
90
+ elif k == b"height":
91
+ ysize = int(v)
92
+ self._size = xsize, ysize
93
+ elif k == b"pixel" and v == b"n8":
94
+ self._mode = "L"
95
+
96
+
97
+ #
98
+ # --------------------------------------------------------------------
99
+
100
+ Image.register_open(ImtImageFile.format, ImtImageFile)
101
+
102
+ #
103
+ # no extension registered (".im" is simply too common)
phi4/lib/python3.10/site-packages/PIL/JpegPresets.py ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ JPEG quality settings equivalent to the Photoshop settings.
3
+ Can be used when saving JPEG files.
4
+
5
+ The following presets are available by default:
6
+ ``web_low``, ``web_medium``, ``web_high``, ``web_very_high``, ``web_maximum``,
7
+ ``low``, ``medium``, ``high``, ``maximum``.
8
+ More presets can be added to the :py:data:`presets` dict if needed.
9
+
10
+ To apply the preset, specify::
11
+
12
+ quality="preset_name"
13
+
14
+ To apply only the quantization table::
15
+
16
+ qtables="preset_name"
17
+
18
+ To apply only the subsampling setting::
19
+
20
+ subsampling="preset_name"
21
+
22
+ Example::
23
+
24
+ im.save("image_name.jpg", quality="web_high")
25
+
26
+ Subsampling
27
+ -----------
28
+
29
+ Subsampling is the practice of encoding images by implementing less resolution
30
+ for chroma information than for luma information.
31
+ (ref.: https://en.wikipedia.org/wiki/Chroma_subsampling)
32
+
33
+ Possible subsampling values are 0, 1 and 2 that correspond to 4:4:4, 4:2:2 and
34
+ 4:2:0.
35
+
36
+ You can get the subsampling of a JPEG with the
37
+ :func:`.JpegImagePlugin.get_sampling` function.
38
+
39
+ In JPEG compressed data a JPEG marker is used instead of an EXIF tag.
40
+ (ref.: https://exiv2.org/tags.html)
41
+
42
+
43
+ Quantization tables
44
+ -------------------
45
+
46
+ They are values use by the DCT (Discrete cosine transform) to remove
47
+ *unnecessary* information from the image (the lossy part of the compression).
48
+ (ref.: https://en.wikipedia.org/wiki/Quantization_matrix#Quantization_matrices,
49
+ https://en.wikipedia.org/wiki/JPEG#Quantization)
50
+
51
+ You can get the quantization tables of a JPEG with::
52
+
53
+ im.quantization
54
+
55
+ This will return a dict with a number of lists. You can pass this dict
56
+ directly as the qtables argument when saving a JPEG.
57
+
58
+ The quantization table format in presets is a list with sublists. These formats
59
+ are interchangeable.
60
+
61
+ Libjpeg ref.:
62
+ https://web.archive.org/web/20120328125543/http://www.jpegcameras.com/libjpeg/libjpeg-3.html
63
+
64
+ """
65
+
66
+ from __future__ import annotations
67
+
68
+ # fmt: off
69
+ presets = {
70
+ 'web_low': {'subsampling': 2, # "4:2:0"
71
+ 'quantization': [
72
+ [20, 16, 25, 39, 50, 46, 62, 68,
73
+ 16, 18, 23, 38, 38, 53, 65, 68,
74
+ 25, 23, 31, 38, 53, 65, 68, 68,
75
+ 39, 38, 38, 53, 65, 68, 68, 68,
76
+ 50, 38, 53, 65, 68, 68, 68, 68,
77
+ 46, 53, 65, 68, 68, 68, 68, 68,
78
+ 62, 65, 68, 68, 68, 68, 68, 68,
79
+ 68, 68, 68, 68, 68, 68, 68, 68],
80
+ [21, 25, 32, 38, 54, 68, 68, 68,
81
+ 25, 28, 24, 38, 54, 68, 68, 68,
82
+ 32, 24, 32, 43, 66, 68, 68, 68,
83
+ 38, 38, 43, 53, 68, 68, 68, 68,
84
+ 54, 54, 66, 68, 68, 68, 68, 68,
85
+ 68, 68, 68, 68, 68, 68, 68, 68,
86
+ 68, 68, 68, 68, 68, 68, 68, 68,
87
+ 68, 68, 68, 68, 68, 68, 68, 68]
88
+ ]},
89
+ 'web_medium': {'subsampling': 2, # "4:2:0"
90
+ 'quantization': [
91
+ [16, 11, 11, 16, 23, 27, 31, 30,
92
+ 11, 12, 12, 15, 20, 23, 23, 30,
93
+ 11, 12, 13, 16, 23, 26, 35, 47,
94
+ 16, 15, 16, 23, 26, 37, 47, 64,
95
+ 23, 20, 23, 26, 39, 51, 64, 64,
96
+ 27, 23, 26, 37, 51, 64, 64, 64,
97
+ 31, 23, 35, 47, 64, 64, 64, 64,
98
+ 30, 30, 47, 64, 64, 64, 64, 64],
99
+ [17, 15, 17, 21, 20, 26, 38, 48,
100
+ 15, 19, 18, 17, 20, 26, 35, 43,
101
+ 17, 18, 20, 22, 26, 30, 46, 53,
102
+ 21, 17, 22, 28, 30, 39, 53, 64,
103
+ 20, 20, 26, 30, 39, 48, 64, 64,
104
+ 26, 26, 30, 39, 48, 63, 64, 64,
105
+ 38, 35, 46, 53, 64, 64, 64, 64,
106
+ 48, 43, 53, 64, 64, 64, 64, 64]
107
+ ]},
108
+ 'web_high': {'subsampling': 0, # "4:4:4"
109
+ 'quantization': [
110
+ [6, 4, 4, 6, 9, 11, 12, 16,
111
+ 4, 5, 5, 6, 8, 10, 12, 12,
112
+ 4, 5, 5, 6, 10, 12, 14, 19,
113
+ 6, 6, 6, 11, 12, 15, 19, 28,
114
+ 9, 8, 10, 12, 16, 20, 27, 31,
115
+ 11, 10, 12, 15, 20, 27, 31, 31,
116
+ 12, 12, 14, 19, 27, 31, 31, 31,
117
+ 16, 12, 19, 28, 31, 31, 31, 31],
118
+ [7, 7, 13, 24, 26, 31, 31, 31,
119
+ 7, 12, 16, 21, 31, 31, 31, 31,
120
+ 13, 16, 17, 31, 31, 31, 31, 31,
121
+ 24, 21, 31, 31, 31, 31, 31, 31,
122
+ 26, 31, 31, 31, 31, 31, 31, 31,
123
+ 31, 31, 31, 31, 31, 31, 31, 31,
124
+ 31, 31, 31, 31, 31, 31, 31, 31,
125
+ 31, 31, 31, 31, 31, 31, 31, 31]
126
+ ]},
127
+ 'web_very_high': {'subsampling': 0, # "4:4:4"
128
+ 'quantization': [
129
+ [2, 2, 2, 2, 3, 4, 5, 6,
130
+ 2, 2, 2, 2, 3, 4, 5, 6,
131
+ 2, 2, 2, 2, 4, 5, 7, 9,
132
+ 2, 2, 2, 4, 5, 7, 9, 12,
133
+ 3, 3, 4, 5, 8, 10, 12, 12,
134
+ 4, 4, 5, 7, 10, 12, 12, 12,
135
+ 5, 5, 7, 9, 12, 12, 12, 12,
136
+ 6, 6, 9, 12, 12, 12, 12, 12],
137
+ [3, 3, 5, 9, 13, 15, 15, 15,
138
+ 3, 4, 6, 11, 14, 12, 12, 12,
139
+ 5, 6, 9, 14, 12, 12, 12, 12,
140
+ 9, 11, 14, 12, 12, 12, 12, 12,
141
+ 13, 14, 12, 12, 12, 12, 12, 12,
142
+ 15, 12, 12, 12, 12, 12, 12, 12,
143
+ 15, 12, 12, 12, 12, 12, 12, 12,
144
+ 15, 12, 12, 12, 12, 12, 12, 12]
145
+ ]},
146
+ 'web_maximum': {'subsampling': 0, # "4:4:4"
147
+ 'quantization': [
148
+ [1, 1, 1, 1, 1, 1, 1, 1,
149
+ 1, 1, 1, 1, 1, 1, 1, 1,
150
+ 1, 1, 1, 1, 1, 1, 1, 2,
151
+ 1, 1, 1, 1, 1, 1, 2, 2,
152
+ 1, 1, 1, 1, 1, 2, 2, 3,
153
+ 1, 1, 1, 1, 2, 2, 3, 3,
154
+ 1, 1, 1, 2, 2, 3, 3, 3,
155
+ 1, 1, 2, 2, 3, 3, 3, 3],
156
+ [1, 1, 1, 2, 2, 3, 3, 3,
157
+ 1, 1, 1, 2, 3, 3, 3, 3,
158
+ 1, 1, 1, 3, 3, 3, 3, 3,
159
+ 2, 2, 3, 3, 3, 3, 3, 3,
160
+ 2, 3, 3, 3, 3, 3, 3, 3,
161
+ 3, 3, 3, 3, 3, 3, 3, 3,
162
+ 3, 3, 3, 3, 3, 3, 3, 3,
163
+ 3, 3, 3, 3, 3, 3, 3, 3]
164
+ ]},
165
+ 'low': {'subsampling': 2, # "4:2:0"
166
+ 'quantization': [
167
+ [18, 14, 14, 21, 30, 35, 34, 17,
168
+ 14, 16, 16, 19, 26, 23, 12, 12,
169
+ 14, 16, 17, 21, 23, 12, 12, 12,
170
+ 21, 19, 21, 23, 12, 12, 12, 12,
171
+ 30, 26, 23, 12, 12, 12, 12, 12,
172
+ 35, 23, 12, 12, 12, 12, 12, 12,
173
+ 34, 12, 12, 12, 12, 12, 12, 12,
174
+ 17, 12, 12, 12, 12, 12, 12, 12],
175
+ [20, 19, 22, 27, 20, 20, 17, 17,
176
+ 19, 25, 23, 14, 14, 12, 12, 12,
177
+ 22, 23, 14, 14, 12, 12, 12, 12,
178
+ 27, 14, 14, 12, 12, 12, 12, 12,
179
+ 20, 14, 12, 12, 12, 12, 12, 12,
180
+ 20, 12, 12, 12, 12, 12, 12, 12,
181
+ 17, 12, 12, 12, 12, 12, 12, 12,
182
+ 17, 12, 12, 12, 12, 12, 12, 12]
183
+ ]},
184
+ 'medium': {'subsampling': 2, # "4:2:0"
185
+ 'quantization': [
186
+ [12, 8, 8, 12, 17, 21, 24, 17,
187
+ 8, 9, 9, 11, 15, 19, 12, 12,
188
+ 8, 9, 10, 12, 19, 12, 12, 12,
189
+ 12, 11, 12, 21, 12, 12, 12, 12,
190
+ 17, 15, 19, 12, 12, 12, 12, 12,
191
+ 21, 19, 12, 12, 12, 12, 12, 12,
192
+ 24, 12, 12, 12, 12, 12, 12, 12,
193
+ 17, 12, 12, 12, 12, 12, 12, 12],
194
+ [13, 11, 13, 16, 20, 20, 17, 17,
195
+ 11, 14, 14, 14, 14, 12, 12, 12,
196
+ 13, 14, 14, 14, 12, 12, 12, 12,
197
+ 16, 14, 14, 12, 12, 12, 12, 12,
198
+ 20, 14, 12, 12, 12, 12, 12, 12,
199
+ 20, 12, 12, 12, 12, 12, 12, 12,
200
+ 17, 12, 12, 12, 12, 12, 12, 12,
201
+ 17, 12, 12, 12, 12, 12, 12, 12]
202
+ ]},
203
+ 'high': {'subsampling': 0, # "4:4:4"
204
+ 'quantization': [
205
+ [6, 4, 4, 6, 9, 11, 12, 16,
206
+ 4, 5, 5, 6, 8, 10, 12, 12,
207
+ 4, 5, 5, 6, 10, 12, 12, 12,
208
+ 6, 6, 6, 11, 12, 12, 12, 12,
209
+ 9, 8, 10, 12, 12, 12, 12, 12,
210
+ 11, 10, 12, 12, 12, 12, 12, 12,
211
+ 12, 12, 12, 12, 12, 12, 12, 12,
212
+ 16, 12, 12, 12, 12, 12, 12, 12],
213
+ [7, 7, 13, 24, 20, 20, 17, 17,
214
+ 7, 12, 16, 14, 14, 12, 12, 12,
215
+ 13, 16, 14, 14, 12, 12, 12, 12,
216
+ 24, 14, 14, 12, 12, 12, 12, 12,
217
+ 20, 14, 12, 12, 12, 12, 12, 12,
218
+ 20, 12, 12, 12, 12, 12, 12, 12,
219
+ 17, 12, 12, 12, 12, 12, 12, 12,
220
+ 17, 12, 12, 12, 12, 12, 12, 12]
221
+ ]},
222
+ 'maximum': {'subsampling': 0, # "4:4:4"
223
+ 'quantization': [
224
+ [2, 2, 2, 2, 3, 4, 5, 6,
225
+ 2, 2, 2, 2, 3, 4, 5, 6,
226
+ 2, 2, 2, 2, 4, 5, 7, 9,
227
+ 2, 2, 2, 4, 5, 7, 9, 12,
228
+ 3, 3, 4, 5, 8, 10, 12, 12,
229
+ 4, 4, 5, 7, 10, 12, 12, 12,
230
+ 5, 5, 7, 9, 12, 12, 12, 12,
231
+ 6, 6, 9, 12, 12, 12, 12, 12],
232
+ [3, 3, 5, 9, 13, 15, 15, 15,
233
+ 3, 4, 6, 10, 14, 12, 12, 12,
234
+ 5, 6, 9, 14, 12, 12, 12, 12,
235
+ 9, 10, 14, 12, 12, 12, 12, 12,
236
+ 13, 14, 12, 12, 12, 12, 12, 12,
237
+ 15, 12, 12, 12, 12, 12, 12, 12,
238
+ 15, 12, 12, 12, 12, 12, 12, 12,
239
+ 15, 12, 12, 12, 12, 12, 12, 12]
240
+ ]},
241
+ }
242
+ # fmt: on
phi4/lib/python3.10/site-packages/PIL/MicImagePlugin.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # Microsoft Image Composer support for PIL
6
+ #
7
+ # Notes:
8
+ # uses TiffImagePlugin.py to read the actual image streams
9
+ #
10
+ # History:
11
+ # 97-01-20 fl Created
12
+ #
13
+ # Copyright (c) Secret Labs AB 1997.
14
+ # Copyright (c) Fredrik Lundh 1997.
15
+ #
16
+ # See the README file for information on usage and redistribution.
17
+ #
18
+ from __future__ import annotations
19
+
20
+ import olefile
21
+
22
+ from . import Image, TiffImagePlugin
23
+
24
+ #
25
+ # --------------------------------------------------------------------
26
+
27
+
28
+ def _accept(prefix: bytes) -> bool:
29
+ return prefix[:8] == olefile.MAGIC
30
+
31
+
32
+ ##
33
+ # Image plugin for Microsoft's Image Composer file format.
34
+
35
+
36
+ class MicImageFile(TiffImagePlugin.TiffImageFile):
37
+ format = "MIC"
38
+ format_description = "Microsoft Image Composer"
39
+ _close_exclusive_fp_after_loading = False
40
+
41
+ def _open(self) -> None:
42
+ # read the OLE directory and see if this is a likely
43
+ # to be a Microsoft Image Composer file
44
+
45
+ try:
46
+ self.ole = olefile.OleFileIO(self.fp)
47
+ except OSError as e:
48
+ msg = "not an MIC file; invalid OLE file"
49
+ raise SyntaxError(msg) from e
50
+
51
+ # find ACI subfiles with Image members (maybe not the
52
+ # best way to identify MIC files, but what the... ;-)
53
+
54
+ self.images = [
55
+ path
56
+ for path in self.ole.listdir()
57
+ if path[1:] and path[0][-4:] == ".ACI" and path[1] == "Image"
58
+ ]
59
+
60
+ # if we didn't find any images, this is probably not
61
+ # an MIC file.
62
+ if not self.images:
63
+ msg = "not an MIC file; no image entries"
64
+ raise SyntaxError(msg)
65
+
66
+ self.frame = -1
67
+ self._n_frames = len(self.images)
68
+ self.is_animated = self._n_frames > 1
69
+
70
+ self.__fp = self.fp
71
+ self.seek(0)
72
+
73
+ def seek(self, frame: int) -> None:
74
+ if not self._seek_check(frame):
75
+ return
76
+ try:
77
+ filename = self.images[frame]
78
+ except IndexError as e:
79
+ msg = "no such frame"
80
+ raise EOFError(msg) from e
81
+
82
+ self.fp = self.ole.openstream(filename)
83
+
84
+ TiffImagePlugin.TiffImageFile._open(self)
85
+
86
+ self.frame = frame
87
+
88
+ def tell(self) -> int:
89
+ return self.frame
90
+
91
+ def close(self) -> None:
92
+ self.__fp.close()
93
+ self.ole.close()
94
+ super().close()
95
+
96
+ def __exit__(self, *args: object) -> None:
97
+ self.__fp.close()
98
+ self.ole.close()
99
+ super().__exit__()
100
+
101
+
102
+ #
103
+ # --------------------------------------------------------------------
104
+
105
+ Image.register_open(MicImageFile.format, MicImageFile, _accept)
106
+
107
+ Image.register_extension(MicImageFile.format, ".mic")
phi4/lib/python3.10/site-packages/PIL/PngImagePlugin.py ADDED
@@ -0,0 +1,1544 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # PNG support code
6
+ #
7
+ # See "PNG (Portable Network Graphics) Specification, version 1.0;
8
+ # W3C Recommendation", 1996-10-01, Thomas Boutell (ed.).
9
+ #
10
+ # history:
11
+ # 1996-05-06 fl Created (couldn't resist it)
12
+ # 1996-12-14 fl Upgraded, added read and verify support (0.2)
13
+ # 1996-12-15 fl Separate PNG stream parser
14
+ # 1996-12-29 fl Added write support, added getchunks
15
+ # 1996-12-30 fl Eliminated circular references in decoder (0.3)
16
+ # 1998-07-12 fl Read/write 16-bit images as mode I (0.4)
17
+ # 2001-02-08 fl Added transparency support (from Zircon) (0.5)
18
+ # 2001-04-16 fl Don't close data source in "open" method (0.6)
19
+ # 2004-02-24 fl Don't even pretend to support interlaced files (0.7)
20
+ # 2004-08-31 fl Do basic sanity check on chunk identifiers (0.8)
21
+ # 2004-09-20 fl Added PngInfo chunk container
22
+ # 2004-12-18 fl Added DPI read support (based on code by Niki Spahiev)
23
+ # 2008-08-13 fl Added tRNS support for RGB images
24
+ # 2009-03-06 fl Support for preserving ICC profiles (by Florian Hoech)
25
+ # 2009-03-08 fl Added zTXT support (from Lowell Alleman)
26
+ # 2009-03-29 fl Read interlaced PNG files (from Conrado Porto Lopes Gouvua)
27
+ #
28
+ # Copyright (c) 1997-2009 by Secret Labs AB
29
+ # Copyright (c) 1996 by Fredrik Lundh
30
+ #
31
+ # See the README file for information on usage and redistribution.
32
+ #
33
+ from __future__ import annotations
34
+
35
+ import itertools
36
+ import logging
37
+ import re
38
+ import struct
39
+ import warnings
40
+ import zlib
41
+ from collections.abc import Callable
42
+ from enum import IntEnum
43
+ from typing import IO, TYPE_CHECKING, Any, NamedTuple, NoReturn, cast
44
+
45
+ from . import Image, ImageChops, ImageFile, ImagePalette, ImageSequence
46
+ from ._binary import i16be as i16
47
+ from ._binary import i32be as i32
48
+ from ._binary import o8
49
+ from ._binary import o16be as o16
50
+ from ._binary import o32be as o32
51
+
52
+ if TYPE_CHECKING:
53
+ from . import _imaging
54
+
55
+ logger = logging.getLogger(__name__)
56
+
57
+ is_cid = re.compile(rb"\w\w\w\w").match
58
+
59
+
60
+ _MAGIC = b"\211PNG\r\n\032\n"
61
+
62
+
63
+ _MODES = {
64
+ # supported bits/color combinations, and corresponding modes/rawmodes
65
+ # Grayscale
66
+ (1, 0): ("1", "1"),
67
+ (2, 0): ("L", "L;2"),
68
+ (4, 0): ("L", "L;4"),
69
+ (8, 0): ("L", "L"),
70
+ (16, 0): ("I;16", "I;16B"),
71
+ # Truecolour
72
+ (8, 2): ("RGB", "RGB"),
73
+ (16, 2): ("RGB", "RGB;16B"),
74
+ # Indexed-colour
75
+ (1, 3): ("P", "P;1"),
76
+ (2, 3): ("P", "P;2"),
77
+ (4, 3): ("P", "P;4"),
78
+ (8, 3): ("P", "P"),
79
+ # Grayscale with alpha
80
+ (8, 4): ("LA", "LA"),
81
+ (16, 4): ("RGBA", "LA;16B"), # LA;16B->LA not yet available
82
+ # Truecolour with alpha
83
+ (8, 6): ("RGBA", "RGBA"),
84
+ (16, 6): ("RGBA", "RGBA;16B"),
85
+ }
86
+
87
+
88
+ _simple_palette = re.compile(b"^\xff*\x00\xff*$")
89
+
90
+ MAX_TEXT_CHUNK = ImageFile.SAFEBLOCK
91
+ """
92
+ Maximum decompressed size for a iTXt or zTXt chunk.
93
+ Eliminates decompression bombs where compressed chunks can expand 1000x.
94
+ See :ref:`Text in PNG File Format<png-text>`.
95
+ """
96
+ MAX_TEXT_MEMORY = 64 * MAX_TEXT_CHUNK
97
+ """
98
+ Set the maximum total text chunk size.
99
+ See :ref:`Text in PNG File Format<png-text>`.
100
+ """
101
+
102
+
103
+ # APNG frame disposal modes
104
+ class Disposal(IntEnum):
105
+ OP_NONE = 0
106
+ """
107
+ No disposal is done on this frame before rendering the next frame.
108
+ See :ref:`Saving APNG sequences<apng-saving>`.
109
+ """
110
+ OP_BACKGROUND = 1
111
+ """
112
+ This frame’s modified region is cleared to fully transparent black before rendering
113
+ the next frame.
114
+ See :ref:`Saving APNG sequences<apng-saving>`.
115
+ """
116
+ OP_PREVIOUS = 2
117
+ """
118
+ This frame’s modified region is reverted to the previous frame’s contents before
119
+ rendering the next frame.
120
+ See :ref:`Saving APNG sequences<apng-saving>`.
121
+ """
122
+
123
+
124
+ # APNG frame blend modes
125
+ class Blend(IntEnum):
126
+ OP_SOURCE = 0
127
+ """
128
+ All color components of this frame, including alpha, overwrite the previous output
129
+ image contents.
130
+ See :ref:`Saving APNG sequences<apng-saving>`.
131
+ """
132
+ OP_OVER = 1
133
+ """
134
+ This frame should be alpha composited with the previous output image contents.
135
+ See :ref:`Saving APNG sequences<apng-saving>`.
136
+ """
137
+
138
+
139
+ def _safe_zlib_decompress(s: bytes) -> bytes:
140
+ dobj = zlib.decompressobj()
141
+ plaintext = dobj.decompress(s, MAX_TEXT_CHUNK)
142
+ if dobj.unconsumed_tail:
143
+ msg = "Decompressed data too large for PngImagePlugin.MAX_TEXT_CHUNK"
144
+ raise ValueError(msg)
145
+ return plaintext
146
+
147
+
148
+ def _crc32(data: bytes, seed: int = 0) -> int:
149
+ return zlib.crc32(data, seed) & 0xFFFFFFFF
150
+
151
+
152
+ # --------------------------------------------------------------------
153
+ # Support classes. Suitable for PNG and related formats like MNG etc.
154
+
155
+
156
+ class ChunkStream:
157
+ def __init__(self, fp: IO[bytes]) -> None:
158
+ self.fp: IO[bytes] | None = fp
159
+ self.queue: list[tuple[bytes, int, int]] | None = []
160
+
161
+ def read(self) -> tuple[bytes, int, int]:
162
+ """Fetch a new chunk. Returns header information."""
163
+ cid = None
164
+
165
+ assert self.fp is not None
166
+ if self.queue:
167
+ cid, pos, length = self.queue.pop()
168
+ self.fp.seek(pos)
169
+ else:
170
+ s = self.fp.read(8)
171
+ cid = s[4:]
172
+ pos = self.fp.tell()
173
+ length = i32(s)
174
+
175
+ if not is_cid(cid):
176
+ if not ImageFile.LOAD_TRUNCATED_IMAGES:
177
+ msg = f"broken PNG file (chunk {repr(cid)})"
178
+ raise SyntaxError(msg)
179
+
180
+ return cid, pos, length
181
+
182
+ def __enter__(self) -> ChunkStream:
183
+ return self
184
+
185
+ def __exit__(self, *args: object) -> None:
186
+ self.close()
187
+
188
+ def close(self) -> None:
189
+ self.queue = self.fp = None
190
+
191
+ def push(self, cid: bytes, pos: int, length: int) -> None:
192
+ assert self.queue is not None
193
+ self.queue.append((cid, pos, length))
194
+
195
+ def call(self, cid: bytes, pos: int, length: int) -> bytes:
196
+ """Call the appropriate chunk handler"""
197
+
198
+ logger.debug("STREAM %r %s %s", cid, pos, length)
199
+ return getattr(self, f"chunk_{cid.decode('ascii')}")(pos, length)
200
+
201
+ def crc(self, cid: bytes, data: bytes) -> None:
202
+ """Read and verify checksum"""
203
+
204
+ # Skip CRC checks for ancillary chunks if allowed to load truncated
205
+ # images
206
+ # 5th byte of first char is 1 [specs, section 5.4]
207
+ if ImageFile.LOAD_TRUNCATED_IMAGES and (cid[0] >> 5 & 1):
208
+ self.crc_skip(cid, data)
209
+ return
210
+
211
+ assert self.fp is not None
212
+ try:
213
+ crc1 = _crc32(data, _crc32(cid))
214
+ crc2 = i32(self.fp.read(4))
215
+ if crc1 != crc2:
216
+ msg = f"broken PNG file (bad header checksum in {repr(cid)})"
217
+ raise SyntaxError(msg)
218
+ except struct.error as e:
219
+ msg = f"broken PNG file (incomplete checksum in {repr(cid)})"
220
+ raise SyntaxError(msg) from e
221
+
222
+ def crc_skip(self, cid: bytes, data: bytes) -> None:
223
+ """Read checksum"""
224
+
225
+ assert self.fp is not None
226
+ self.fp.read(4)
227
+
228
+ def verify(self, endchunk: bytes = b"IEND") -> list[bytes]:
229
+ # Simple approach; just calculate checksum for all remaining
230
+ # blocks. Must be called directly after open.
231
+
232
+ cids = []
233
+
234
+ assert self.fp is not None
235
+ while True:
236
+ try:
237
+ cid, pos, length = self.read()
238
+ except struct.error as e:
239
+ msg = "truncated PNG file"
240
+ raise OSError(msg) from e
241
+
242
+ if cid == endchunk:
243
+ break
244
+ self.crc(cid, ImageFile._safe_read(self.fp, length))
245
+ cids.append(cid)
246
+
247
+ return cids
248
+
249
+
250
+ class iTXt(str):
251
+ """
252
+ Subclass of string to allow iTXt chunks to look like strings while
253
+ keeping their extra information
254
+
255
+ """
256
+
257
+ lang: str | bytes | None
258
+ tkey: str | bytes | None
259
+
260
+ @staticmethod
261
+ def __new__(
262
+ cls, text: str, lang: str | None = None, tkey: str | None = None
263
+ ) -> iTXt:
264
+ """
265
+ :param cls: the class to use when creating the instance
266
+ :param text: value for this key
267
+ :param lang: language code
268
+ :param tkey: UTF-8 version of the key name
269
+ """
270
+
271
+ self = str.__new__(cls, text)
272
+ self.lang = lang
273
+ self.tkey = tkey
274
+ return self
275
+
276
+
277
+ class PngInfo:
278
+ """
279
+ PNG chunk container (for use with save(pnginfo=))
280
+
281
+ """
282
+
283
+ def __init__(self) -> None:
284
+ self.chunks: list[tuple[bytes, bytes, bool]] = []
285
+
286
+ def add(self, cid: bytes, data: bytes, after_idat: bool = False) -> None:
287
+ """Appends an arbitrary chunk. Use with caution.
288
+
289
+ :param cid: a byte string, 4 bytes long.
290
+ :param data: a byte string of the encoded data
291
+ :param after_idat: for use with private chunks. Whether the chunk
292
+ should be written after IDAT
293
+
294
+ """
295
+
296
+ self.chunks.append((cid, data, after_idat))
297
+
298
+ def add_itxt(
299
+ self,
300
+ key: str | bytes,
301
+ value: str | bytes,
302
+ lang: str | bytes = "",
303
+ tkey: str | bytes = "",
304
+ zip: bool = False,
305
+ ) -> None:
306
+ """Appends an iTXt chunk.
307
+
308
+ :param key: latin-1 encodable text key name
309
+ :param value: value for this key
310
+ :param lang: language code
311
+ :param tkey: UTF-8 version of the key name
312
+ :param zip: compression flag
313
+
314
+ """
315
+
316
+ if not isinstance(key, bytes):
317
+ key = key.encode("latin-1", "strict")
318
+ if not isinstance(value, bytes):
319
+ value = value.encode("utf-8", "strict")
320
+ if not isinstance(lang, bytes):
321
+ lang = lang.encode("utf-8", "strict")
322
+ if not isinstance(tkey, bytes):
323
+ tkey = tkey.encode("utf-8", "strict")
324
+
325
+ if zip:
326
+ self.add(
327
+ b"iTXt",
328
+ key + b"\0\x01\0" + lang + b"\0" + tkey + b"\0" + zlib.compress(value),
329
+ )
330
+ else:
331
+ self.add(b"iTXt", key + b"\0\0\0" + lang + b"\0" + tkey + b"\0" + value)
332
+
333
+ def add_text(
334
+ self, key: str | bytes, value: str | bytes | iTXt, zip: bool = False
335
+ ) -> None:
336
+ """Appends a text chunk.
337
+
338
+ :param key: latin-1 encodable text key name
339
+ :param value: value for this key, text or an
340
+ :py:class:`PIL.PngImagePlugin.iTXt` instance
341
+ :param zip: compression flag
342
+
343
+ """
344
+ if isinstance(value, iTXt):
345
+ return self.add_itxt(
346
+ key,
347
+ value,
348
+ value.lang if value.lang is not None else b"",
349
+ value.tkey if value.tkey is not None else b"",
350
+ zip=zip,
351
+ )
352
+
353
+ # The tEXt chunk stores latin-1 text
354
+ if not isinstance(value, bytes):
355
+ try:
356
+ value = value.encode("latin-1", "strict")
357
+ except UnicodeError:
358
+ return self.add_itxt(key, value, zip=zip)
359
+
360
+ if not isinstance(key, bytes):
361
+ key = key.encode("latin-1", "strict")
362
+
363
+ if zip:
364
+ self.add(b"zTXt", key + b"\0\0" + zlib.compress(value))
365
+ else:
366
+ self.add(b"tEXt", key + b"\0" + value)
367
+
368
+
369
+ # --------------------------------------------------------------------
370
+ # PNG image stream (IHDR/IEND)
371
+
372
+
373
+ class _RewindState(NamedTuple):
374
+ info: dict[str | tuple[int, int], Any]
375
+ tile: list[ImageFile._Tile]
376
+ seq_num: int | None
377
+
378
+
379
+ class PngStream(ChunkStream):
380
+ def __init__(self, fp: IO[bytes]) -> None:
381
+ super().__init__(fp)
382
+
383
+ # local copies of Image attributes
384
+ self.im_info: dict[str | tuple[int, int], Any] = {}
385
+ self.im_text: dict[str, str | iTXt] = {}
386
+ self.im_size = (0, 0)
387
+ self.im_mode = ""
388
+ self.im_tile: list[ImageFile._Tile] = []
389
+ self.im_palette: tuple[str, bytes] | None = None
390
+ self.im_custom_mimetype: str | None = None
391
+ self.im_n_frames: int | None = None
392
+ self._seq_num: int | None = None
393
+ self.rewind_state = _RewindState({}, [], None)
394
+
395
+ self.text_memory = 0
396
+
397
+ def check_text_memory(self, chunklen: int) -> None:
398
+ self.text_memory += chunklen
399
+ if self.text_memory > MAX_TEXT_MEMORY:
400
+ msg = (
401
+ "Too much memory used in text chunks: "
402
+ f"{self.text_memory}>MAX_TEXT_MEMORY"
403
+ )
404
+ raise ValueError(msg)
405
+
406
+ def save_rewind(self) -> None:
407
+ self.rewind_state = _RewindState(
408
+ self.im_info.copy(),
409
+ self.im_tile,
410
+ self._seq_num,
411
+ )
412
+
413
+ def rewind(self) -> None:
414
+ self.im_info = self.rewind_state.info.copy()
415
+ self.im_tile = self.rewind_state.tile
416
+ self._seq_num = self.rewind_state.seq_num
417
+
418
+ def chunk_iCCP(self, pos: int, length: int) -> bytes:
419
+ # ICC profile
420
+ assert self.fp is not None
421
+ s = ImageFile._safe_read(self.fp, length)
422
+ # according to PNG spec, the iCCP chunk contains:
423
+ # Profile name 1-79 bytes (character string)
424
+ # Null separator 1 byte (null character)
425
+ # Compression method 1 byte (0)
426
+ # Compressed profile n bytes (zlib with deflate compression)
427
+ i = s.find(b"\0")
428
+ logger.debug("iCCP profile name %r", s[:i])
429
+ comp_method = s[i + 1]
430
+ logger.debug("Compression method %s", comp_method)
431
+ if comp_method != 0:
432
+ msg = f"Unknown compression method {comp_method} in iCCP chunk"
433
+ raise SyntaxError(msg)
434
+ try:
435
+ icc_profile = _safe_zlib_decompress(s[i + 2 :])
436
+ except ValueError:
437
+ if ImageFile.LOAD_TRUNCATED_IMAGES:
438
+ icc_profile = None
439
+ else:
440
+ raise
441
+ except zlib.error:
442
+ icc_profile = None # FIXME
443
+ self.im_info["icc_profile"] = icc_profile
444
+ return s
445
+
446
+ def chunk_IHDR(self, pos: int, length: int) -> bytes:
447
+ # image header
448
+ assert self.fp is not None
449
+ s = ImageFile._safe_read(self.fp, length)
450
+ if length < 13:
451
+ if ImageFile.LOAD_TRUNCATED_IMAGES:
452
+ return s
453
+ msg = "Truncated IHDR chunk"
454
+ raise ValueError(msg)
455
+ self.im_size = i32(s, 0), i32(s, 4)
456
+ try:
457
+ self.im_mode, self.im_rawmode = _MODES[(s[8], s[9])]
458
+ except Exception:
459
+ pass
460
+ if s[12]:
461
+ self.im_info["interlace"] = 1
462
+ if s[11]:
463
+ msg = "unknown filter category"
464
+ raise SyntaxError(msg)
465
+ return s
466
+
467
+ def chunk_IDAT(self, pos: int, length: int) -> NoReturn:
468
+ # image data
469
+ if "bbox" in self.im_info:
470
+ tile = [ImageFile._Tile("zip", self.im_info["bbox"], pos, self.im_rawmode)]
471
+ else:
472
+ if self.im_n_frames is not None:
473
+ self.im_info["default_image"] = True
474
+ tile = [ImageFile._Tile("zip", (0, 0) + self.im_size, pos, self.im_rawmode)]
475
+ self.im_tile = tile
476
+ self.im_idat = length
477
+ msg = "image data found"
478
+ raise EOFError(msg)
479
+
480
+ def chunk_IEND(self, pos: int, length: int) -> NoReturn:
481
+ msg = "end of PNG image"
482
+ raise EOFError(msg)
483
+
484
+ def chunk_PLTE(self, pos: int, length: int) -> bytes:
485
+ # palette
486
+ assert self.fp is not None
487
+ s = ImageFile._safe_read(self.fp, length)
488
+ if self.im_mode == "P":
489
+ self.im_palette = "RGB", s
490
+ return s
491
+
492
+ def chunk_tRNS(self, pos: int, length: int) -> bytes:
493
+ # transparency
494
+ assert self.fp is not None
495
+ s = ImageFile._safe_read(self.fp, length)
496
+ if self.im_mode == "P":
497
+ if _simple_palette.match(s):
498
+ # tRNS contains only one full-transparent entry,
499
+ # other entries are full opaque
500
+ i = s.find(b"\0")
501
+ if i >= 0:
502
+ self.im_info["transparency"] = i
503
+ else:
504
+ # otherwise, we have a byte string with one alpha value
505
+ # for each palette entry
506
+ self.im_info["transparency"] = s
507
+ elif self.im_mode in ("1", "L", "I;16"):
508
+ self.im_info["transparency"] = i16(s)
509
+ elif self.im_mode == "RGB":
510
+ self.im_info["transparency"] = i16(s), i16(s, 2), i16(s, 4)
511
+ return s
512
+
513
+ def chunk_gAMA(self, pos: int, length: int) -> bytes:
514
+ # gamma setting
515
+ assert self.fp is not None
516
+ s = ImageFile._safe_read(self.fp, length)
517
+ self.im_info["gamma"] = i32(s) / 100000.0
518
+ return s
519
+
520
+ def chunk_cHRM(self, pos: int, length: int) -> bytes:
521
+ # chromaticity, 8 unsigned ints, actual value is scaled by 100,000
522
+ # WP x,y, Red x,y, Green x,y Blue x,y
523
+
524
+ assert self.fp is not None
525
+ s = ImageFile._safe_read(self.fp, length)
526
+ raw_vals = struct.unpack(f">{len(s) // 4}I", s)
527
+ self.im_info["chromaticity"] = tuple(elt / 100000.0 for elt in raw_vals)
528
+ return s
529
+
530
+ def chunk_sRGB(self, pos: int, length: int) -> bytes:
531
+ # srgb rendering intent, 1 byte
532
+ # 0 perceptual
533
+ # 1 relative colorimetric
534
+ # 2 saturation
535
+ # 3 absolute colorimetric
536
+
537
+ assert self.fp is not None
538
+ s = ImageFile._safe_read(self.fp, length)
539
+ if length < 1:
540
+ if ImageFile.LOAD_TRUNCATED_IMAGES:
541
+ return s
542
+ msg = "Truncated sRGB chunk"
543
+ raise ValueError(msg)
544
+ self.im_info["srgb"] = s[0]
545
+ return s
546
+
547
+ def chunk_pHYs(self, pos: int, length: int) -> bytes:
548
+ # pixels per unit
549
+ assert self.fp is not None
550
+ s = ImageFile._safe_read(self.fp, length)
551
+ if length < 9:
552
+ if ImageFile.LOAD_TRUNCATED_IMAGES:
553
+ return s
554
+ msg = "Truncated pHYs chunk"
555
+ raise ValueError(msg)
556
+ px, py = i32(s, 0), i32(s, 4)
557
+ unit = s[8]
558
+ if unit == 1: # meter
559
+ dpi = px * 0.0254, py * 0.0254
560
+ self.im_info["dpi"] = dpi
561
+ elif unit == 0:
562
+ self.im_info["aspect"] = px, py
563
+ return s
564
+
565
+ def chunk_tEXt(self, pos: int, length: int) -> bytes:
566
+ # text
567
+ assert self.fp is not None
568
+ s = ImageFile._safe_read(self.fp, length)
569
+ try:
570
+ k, v = s.split(b"\0", 1)
571
+ except ValueError:
572
+ # fallback for broken tEXt tags
573
+ k = s
574
+ v = b""
575
+ if k:
576
+ k_str = k.decode("latin-1", "strict")
577
+ v_str = v.decode("latin-1", "replace")
578
+
579
+ self.im_info[k_str] = v if k == b"exif" else v_str
580
+ self.im_text[k_str] = v_str
581
+ self.check_text_memory(len(v_str))
582
+
583
+ return s
584
+
585
+ def chunk_zTXt(self, pos: int, length: int) -> bytes:
586
+ # compressed text
587
+ assert self.fp is not None
588
+ s = ImageFile._safe_read(self.fp, length)
589
+ try:
590
+ k, v = s.split(b"\0", 1)
591
+ except ValueError:
592
+ k = s
593
+ v = b""
594
+ if v:
595
+ comp_method = v[0]
596
+ else:
597
+ comp_method = 0
598
+ if comp_method != 0:
599
+ msg = f"Unknown compression method {comp_method} in zTXt chunk"
600
+ raise SyntaxError(msg)
601
+ try:
602
+ v = _safe_zlib_decompress(v[1:])
603
+ except ValueError:
604
+ if ImageFile.LOAD_TRUNCATED_IMAGES:
605
+ v = b""
606
+ else:
607
+ raise
608
+ except zlib.error:
609
+ v = b""
610
+
611
+ if k:
612
+ k_str = k.decode("latin-1", "strict")
613
+ v_str = v.decode("latin-1", "replace")
614
+
615
+ self.im_info[k_str] = self.im_text[k_str] = v_str
616
+ self.check_text_memory(len(v_str))
617
+
618
+ return s
619
+
620
+ def chunk_iTXt(self, pos: int, length: int) -> bytes:
621
+ # international text
622
+ assert self.fp is not None
623
+ r = s = ImageFile._safe_read(self.fp, length)
624
+ try:
625
+ k, r = r.split(b"\0", 1)
626
+ except ValueError:
627
+ return s
628
+ if len(r) < 2:
629
+ return s
630
+ cf, cm, r = r[0], r[1], r[2:]
631
+ try:
632
+ lang, tk, v = r.split(b"\0", 2)
633
+ except ValueError:
634
+ return s
635
+ if cf != 0:
636
+ if cm == 0:
637
+ try:
638
+ v = _safe_zlib_decompress(v)
639
+ except ValueError:
640
+ if ImageFile.LOAD_TRUNCATED_IMAGES:
641
+ return s
642
+ else:
643
+ raise
644
+ except zlib.error:
645
+ return s
646
+ else:
647
+ return s
648
+ if k == b"XML:com.adobe.xmp":
649
+ self.im_info["xmp"] = v
650
+ try:
651
+ k_str = k.decode("latin-1", "strict")
652
+ lang_str = lang.decode("utf-8", "strict")
653
+ tk_str = tk.decode("utf-8", "strict")
654
+ v_str = v.decode("utf-8", "strict")
655
+ except UnicodeError:
656
+ return s
657
+
658
+ self.im_info[k_str] = self.im_text[k_str] = iTXt(v_str, lang_str, tk_str)
659
+ self.check_text_memory(len(v_str))
660
+
661
+ return s
662
+
663
+ def chunk_eXIf(self, pos: int, length: int) -> bytes:
664
+ assert self.fp is not None
665
+ s = ImageFile._safe_read(self.fp, length)
666
+ self.im_info["exif"] = b"Exif\x00\x00" + s
667
+ return s
668
+
669
+ # APNG chunks
670
+ def chunk_acTL(self, pos: int, length: int) -> bytes:
671
+ assert self.fp is not None
672
+ s = ImageFile._safe_read(self.fp, length)
673
+ if length < 8:
674
+ if ImageFile.LOAD_TRUNCATED_IMAGES:
675
+ return s
676
+ msg = "APNG contains truncated acTL chunk"
677
+ raise ValueError(msg)
678
+ if self.im_n_frames is not None:
679
+ self.im_n_frames = None
680
+ warnings.warn("Invalid APNG, will use default PNG image if possible")
681
+ return s
682
+ n_frames = i32(s)
683
+ if n_frames == 0 or n_frames > 0x80000000:
684
+ warnings.warn("Invalid APNG, will use default PNG image if possible")
685
+ return s
686
+ self.im_n_frames = n_frames
687
+ self.im_info["loop"] = i32(s, 4)
688
+ self.im_custom_mimetype = "image/apng"
689
+ return s
690
+
691
+ def chunk_fcTL(self, pos: int, length: int) -> bytes:
692
+ assert self.fp is not None
693
+ s = ImageFile._safe_read(self.fp, length)
694
+ if length < 26:
695
+ if ImageFile.LOAD_TRUNCATED_IMAGES:
696
+ return s
697
+ msg = "APNG contains truncated fcTL chunk"
698
+ raise ValueError(msg)
699
+ seq = i32(s)
700
+ if (self._seq_num is None and seq != 0) or (
701
+ self._seq_num is not None and self._seq_num != seq - 1
702
+ ):
703
+ msg = "APNG contains frame sequence errors"
704
+ raise SyntaxError(msg)
705
+ self._seq_num = seq
706
+ width, height = i32(s, 4), i32(s, 8)
707
+ px, py = i32(s, 12), i32(s, 16)
708
+ im_w, im_h = self.im_size
709
+ if px + width > im_w or py + height > im_h:
710
+ msg = "APNG contains invalid frames"
711
+ raise SyntaxError(msg)
712
+ self.im_info["bbox"] = (px, py, px + width, py + height)
713
+ delay_num, delay_den = i16(s, 20), i16(s, 22)
714
+ if delay_den == 0:
715
+ delay_den = 100
716
+ self.im_info["duration"] = float(delay_num) / float(delay_den) * 1000
717
+ self.im_info["disposal"] = s[24]
718
+ self.im_info["blend"] = s[25]
719
+ return s
720
+
721
+ def chunk_fdAT(self, pos: int, length: int) -> bytes:
722
+ assert self.fp is not None
723
+ if length < 4:
724
+ if ImageFile.LOAD_TRUNCATED_IMAGES:
725
+ s = ImageFile._safe_read(self.fp, length)
726
+ return s
727
+ msg = "APNG contains truncated fDAT chunk"
728
+ raise ValueError(msg)
729
+ s = ImageFile._safe_read(self.fp, 4)
730
+ seq = i32(s)
731
+ if self._seq_num != seq - 1:
732
+ msg = "APNG contains frame sequence errors"
733
+ raise SyntaxError(msg)
734
+ self._seq_num = seq
735
+ return self.chunk_IDAT(pos + 4, length - 4)
736
+
737
+
738
+ # --------------------------------------------------------------------
739
+ # PNG reader
740
+
741
+
742
+ def _accept(prefix: bytes) -> bool:
743
+ return prefix[:8] == _MAGIC
744
+
745
+
746
+ ##
747
+ # Image plugin for PNG images.
748
+
749
+
750
+ class PngImageFile(ImageFile.ImageFile):
751
+ format = "PNG"
752
+ format_description = "Portable network graphics"
753
+
754
+ def _open(self) -> None:
755
+ if not _accept(self.fp.read(8)):
756
+ msg = "not a PNG file"
757
+ raise SyntaxError(msg)
758
+ self._fp = self.fp
759
+ self.__frame = 0
760
+
761
+ #
762
+ # Parse headers up to the first IDAT or fDAT chunk
763
+
764
+ self.private_chunks: list[tuple[bytes, bytes] | tuple[bytes, bytes, bool]] = []
765
+ self.png: PngStream | None = PngStream(self.fp)
766
+
767
+ while True:
768
+ #
769
+ # get next chunk
770
+
771
+ cid, pos, length = self.png.read()
772
+
773
+ try:
774
+ s = self.png.call(cid, pos, length)
775
+ except EOFError:
776
+ break
777
+ except AttributeError:
778
+ logger.debug("%r %s %s (unknown)", cid, pos, length)
779
+ s = ImageFile._safe_read(self.fp, length)
780
+ if cid[1:2].islower():
781
+ self.private_chunks.append((cid, s))
782
+
783
+ self.png.crc(cid, s)
784
+
785
+ #
786
+ # Copy relevant attributes from the PngStream. An alternative
787
+ # would be to let the PngStream class modify these attributes
788
+ # directly, but that introduces circular references which are
789
+ # difficult to break if things go wrong in the decoder...
790
+ # (believe me, I've tried ;-)
791
+
792
+ self._mode = self.png.im_mode
793
+ self._size = self.png.im_size
794
+ self.info = self.png.im_info
795
+ self._text: dict[str, str | iTXt] | None = None
796
+ self.tile = self.png.im_tile
797
+ self.custom_mimetype = self.png.im_custom_mimetype
798
+ self.n_frames = self.png.im_n_frames or 1
799
+ self.default_image = self.info.get("default_image", False)
800
+
801
+ if self.png.im_palette:
802
+ rawmode, data = self.png.im_palette
803
+ self.palette = ImagePalette.raw(rawmode, data)
804
+
805
+ if cid == b"fdAT":
806
+ self.__prepare_idat = length - 4
807
+ else:
808
+ self.__prepare_idat = length # used by load_prepare()
809
+
810
+ if self.png.im_n_frames is not None:
811
+ self._close_exclusive_fp_after_loading = False
812
+ self.png.save_rewind()
813
+ self.__rewind_idat = self.__prepare_idat
814
+ self.__rewind = self._fp.tell()
815
+ if self.default_image:
816
+ # IDAT chunk contains default image and not first animation frame
817
+ self.n_frames += 1
818
+ self._seek(0)
819
+ self.is_animated = self.n_frames > 1
820
+
821
+ @property
822
+ def text(self) -> dict[str, str | iTXt]:
823
+ # experimental
824
+ if self._text is None:
825
+ # iTxt, tEXt and zTXt chunks may appear at the end of the file
826
+ # So load the file to ensure that they are read
827
+ if self.is_animated:
828
+ frame = self.__frame
829
+ # for APNG, seek to the final frame before loading
830
+ self.seek(self.n_frames - 1)
831
+ self.load()
832
+ if self.is_animated:
833
+ self.seek(frame)
834
+ assert self._text is not None
835
+ return self._text
836
+
837
+ def verify(self) -> None:
838
+ """Verify PNG file"""
839
+
840
+ if self.fp is None:
841
+ msg = "verify must be called directly after open"
842
+ raise RuntimeError(msg)
843
+
844
+ # back up to beginning of IDAT block
845
+ self.fp.seek(self.tile[0][2] - 8)
846
+
847
+ assert self.png is not None
848
+ self.png.verify()
849
+ self.png.close()
850
+
851
+ if self._exclusive_fp:
852
+ self.fp.close()
853
+ self.fp = None
854
+
855
+ def seek(self, frame: int) -> None:
856
+ if not self._seek_check(frame):
857
+ return
858
+ if frame < self.__frame:
859
+ self._seek(0, True)
860
+
861
+ last_frame = self.__frame
862
+ for f in range(self.__frame + 1, frame + 1):
863
+ try:
864
+ self._seek(f)
865
+ except EOFError as e:
866
+ self.seek(last_frame)
867
+ msg = "no more images in APNG file"
868
+ raise EOFError(msg) from e
869
+
870
+ def _seek(self, frame: int, rewind: bool = False) -> None:
871
+ assert self.png is not None
872
+
873
+ self.dispose: _imaging.ImagingCore | None
874
+ dispose_extent = None
875
+ if frame == 0:
876
+ if rewind:
877
+ self._fp.seek(self.__rewind)
878
+ self.png.rewind()
879
+ self.__prepare_idat = self.__rewind_idat
880
+ self._im = None
881
+ self.info = self.png.im_info
882
+ self.tile = self.png.im_tile
883
+ self.fp = self._fp
884
+ self._prev_im = None
885
+ self.dispose = None
886
+ self.default_image = self.info.get("default_image", False)
887
+ self.dispose_op = self.info.get("disposal")
888
+ self.blend_op = self.info.get("blend")
889
+ dispose_extent = self.info.get("bbox")
890
+ self.__frame = 0
891
+ else:
892
+ if frame != self.__frame + 1:
893
+ msg = f"cannot seek to frame {frame}"
894
+ raise ValueError(msg)
895
+
896
+ # ensure previous frame was loaded
897
+ self.load()
898
+
899
+ if self.dispose:
900
+ self.im.paste(self.dispose, self.dispose_extent)
901
+ self._prev_im = self.im.copy()
902
+
903
+ self.fp = self._fp
904
+
905
+ # advance to the next frame
906
+ if self.__prepare_idat:
907
+ ImageFile._safe_read(self.fp, self.__prepare_idat)
908
+ self.__prepare_idat = 0
909
+ frame_start = False
910
+ while True:
911
+ self.fp.read(4) # CRC
912
+
913
+ try:
914
+ cid, pos, length = self.png.read()
915
+ except (struct.error, SyntaxError):
916
+ break
917
+
918
+ if cid == b"IEND":
919
+ msg = "No more images in APNG file"
920
+ raise EOFError(msg)
921
+ if cid == b"fcTL":
922
+ if frame_start:
923
+ # there must be at least one fdAT chunk between fcTL chunks
924
+ msg = "APNG missing frame data"
925
+ raise SyntaxError(msg)
926
+ frame_start = True
927
+
928
+ try:
929
+ self.png.call(cid, pos, length)
930
+ except UnicodeDecodeError:
931
+ break
932
+ except EOFError:
933
+ if cid == b"fdAT":
934
+ length -= 4
935
+ if frame_start:
936
+ self.__prepare_idat = length
937
+ break
938
+ ImageFile._safe_read(self.fp, length)
939
+ except AttributeError:
940
+ logger.debug("%r %s %s (unknown)", cid, pos, length)
941
+ ImageFile._safe_read(self.fp, length)
942
+
943
+ self.__frame = frame
944
+ self.tile = self.png.im_tile
945
+ self.dispose_op = self.info.get("disposal")
946
+ self.blend_op = self.info.get("blend")
947
+ dispose_extent = self.info.get("bbox")
948
+
949
+ if not self.tile:
950
+ msg = "image not found in APNG frame"
951
+ raise EOFError(msg)
952
+ if dispose_extent:
953
+ self.dispose_extent: tuple[float, float, float, float] = dispose_extent
954
+
955
+ # setup frame disposal (actual disposal done when needed in the next _seek())
956
+ if self._prev_im is None and self.dispose_op == Disposal.OP_PREVIOUS:
957
+ self.dispose_op = Disposal.OP_BACKGROUND
958
+
959
+ self.dispose = None
960
+ if self.dispose_op == Disposal.OP_PREVIOUS:
961
+ if self._prev_im:
962
+ self.dispose = self._prev_im.copy()
963
+ self.dispose = self._crop(self.dispose, self.dispose_extent)
964
+ elif self.dispose_op == Disposal.OP_BACKGROUND:
965
+ self.dispose = Image.core.fill(self.mode, self.size)
966
+ self.dispose = self._crop(self.dispose, self.dispose_extent)
967
+
968
+ def tell(self) -> int:
969
+ return self.__frame
970
+
971
+ def load_prepare(self) -> None:
972
+ """internal: prepare to read PNG file"""
973
+
974
+ if self.info.get("interlace"):
975
+ self.decoderconfig = self.decoderconfig + (1,)
976
+
977
+ self.__idat = self.__prepare_idat # used by load_read()
978
+ ImageFile.ImageFile.load_prepare(self)
979
+
980
+ def load_read(self, read_bytes: int) -> bytes:
981
+ """internal: read more image data"""
982
+
983
+ assert self.png is not None
984
+ while self.__idat == 0:
985
+ # end of chunk, skip forward to next one
986
+
987
+ self.fp.read(4) # CRC
988
+
989
+ cid, pos, length = self.png.read()
990
+
991
+ if cid not in [b"IDAT", b"DDAT", b"fdAT"]:
992
+ self.png.push(cid, pos, length)
993
+ return b""
994
+
995
+ if cid == b"fdAT":
996
+ try:
997
+ self.png.call(cid, pos, length)
998
+ except EOFError:
999
+ pass
1000
+ self.__idat = length - 4 # sequence_num has already been read
1001
+ else:
1002
+ self.__idat = length # empty chunks are allowed
1003
+
1004
+ # read more data from this chunk
1005
+ if read_bytes <= 0:
1006
+ read_bytes = self.__idat
1007
+ else:
1008
+ read_bytes = min(read_bytes, self.__idat)
1009
+
1010
+ self.__idat = self.__idat - read_bytes
1011
+
1012
+ return self.fp.read(read_bytes)
1013
+
1014
+ def load_end(self) -> None:
1015
+ """internal: finished reading image data"""
1016
+ assert self.png is not None
1017
+ if self.__idat != 0:
1018
+ self.fp.read(self.__idat)
1019
+ while True:
1020
+ self.fp.read(4) # CRC
1021
+
1022
+ try:
1023
+ cid, pos, length = self.png.read()
1024
+ except (struct.error, SyntaxError):
1025
+ break
1026
+
1027
+ if cid == b"IEND":
1028
+ break
1029
+ elif cid == b"fcTL" and self.is_animated:
1030
+ # start of the next frame, stop reading
1031
+ self.__prepare_idat = 0
1032
+ self.png.push(cid, pos, length)
1033
+ break
1034
+
1035
+ try:
1036
+ self.png.call(cid, pos, length)
1037
+ except UnicodeDecodeError:
1038
+ break
1039
+ except EOFError:
1040
+ if cid == b"fdAT":
1041
+ length -= 4
1042
+ try:
1043
+ ImageFile._safe_read(self.fp, length)
1044
+ except OSError as e:
1045
+ if ImageFile.LOAD_TRUNCATED_IMAGES:
1046
+ break
1047
+ else:
1048
+ raise e
1049
+ except AttributeError:
1050
+ logger.debug("%r %s %s (unknown)", cid, pos, length)
1051
+ s = ImageFile._safe_read(self.fp, length)
1052
+ if cid[1:2].islower():
1053
+ self.private_chunks.append((cid, s, True))
1054
+ self._text = self.png.im_text
1055
+ if not self.is_animated:
1056
+ self.png.close()
1057
+ self.png = None
1058
+ else:
1059
+ if self._prev_im and self.blend_op == Blend.OP_OVER:
1060
+ updated = self._crop(self.im, self.dispose_extent)
1061
+ if self.im.mode == "RGB" and "transparency" in self.info:
1062
+ mask = updated.convert_transparent(
1063
+ "RGBA", self.info["transparency"]
1064
+ )
1065
+ else:
1066
+ if self.im.mode == "P" and "transparency" in self.info:
1067
+ t = self.info["transparency"]
1068
+ if isinstance(t, bytes):
1069
+ updated.putpalettealphas(t)
1070
+ elif isinstance(t, int):
1071
+ updated.putpalettealpha(t)
1072
+ mask = updated.convert("RGBA")
1073
+ self._prev_im.paste(updated, self.dispose_extent, mask)
1074
+ self.im = self._prev_im
1075
+
1076
+ def _getexif(self) -> dict[int, Any] | None:
1077
+ if "exif" not in self.info:
1078
+ self.load()
1079
+ if "exif" not in self.info and "Raw profile type exif" not in self.info:
1080
+ return None
1081
+ return self.getexif()._get_merged_dict()
1082
+
1083
+ def getexif(self) -> Image.Exif:
1084
+ if "exif" not in self.info:
1085
+ self.load()
1086
+
1087
+ return super().getexif()
1088
+
1089
+
1090
+ # --------------------------------------------------------------------
1091
+ # PNG writer
1092
+
1093
+ _OUTMODES = {
1094
+ # supported PIL modes, and corresponding rawmode, bit depth and color type
1095
+ "1": ("1", b"\x01", b"\x00"),
1096
+ "L;1": ("L;1", b"\x01", b"\x00"),
1097
+ "L;2": ("L;2", b"\x02", b"\x00"),
1098
+ "L;4": ("L;4", b"\x04", b"\x00"),
1099
+ "L": ("L", b"\x08", b"\x00"),
1100
+ "LA": ("LA", b"\x08", b"\x04"),
1101
+ "I": ("I;16B", b"\x10", b"\x00"),
1102
+ "I;16": ("I;16B", b"\x10", b"\x00"),
1103
+ "I;16B": ("I;16B", b"\x10", b"\x00"),
1104
+ "P;1": ("P;1", b"\x01", b"\x03"),
1105
+ "P;2": ("P;2", b"\x02", b"\x03"),
1106
+ "P;4": ("P;4", b"\x04", b"\x03"),
1107
+ "P": ("P", b"\x08", b"\x03"),
1108
+ "RGB": ("RGB", b"\x08", b"\x02"),
1109
+ "RGBA": ("RGBA", b"\x08", b"\x06"),
1110
+ }
1111
+
1112
+
1113
+ def putchunk(fp: IO[bytes], cid: bytes, *data: bytes) -> None:
1114
+ """Write a PNG chunk (including CRC field)"""
1115
+
1116
+ byte_data = b"".join(data)
1117
+
1118
+ fp.write(o32(len(byte_data)) + cid)
1119
+ fp.write(byte_data)
1120
+ crc = _crc32(byte_data, _crc32(cid))
1121
+ fp.write(o32(crc))
1122
+
1123
+
1124
+ class _idat:
1125
+ # wrap output from the encoder in IDAT chunks
1126
+
1127
+ def __init__(self, fp: IO[bytes], chunk: Callable[..., None]) -> None:
1128
+ self.fp = fp
1129
+ self.chunk = chunk
1130
+
1131
+ def write(self, data: bytes) -> None:
1132
+ self.chunk(self.fp, b"IDAT", data)
1133
+
1134
+
1135
+ class _fdat:
1136
+ # wrap encoder output in fdAT chunks
1137
+
1138
+ def __init__(self, fp: IO[bytes], chunk: Callable[..., None], seq_num: int) -> None:
1139
+ self.fp = fp
1140
+ self.chunk = chunk
1141
+ self.seq_num = seq_num
1142
+
1143
+ def write(self, data: bytes) -> None:
1144
+ self.chunk(self.fp, b"fdAT", o32(self.seq_num), data)
1145
+ self.seq_num += 1
1146
+
1147
+
1148
+ class _Frame(NamedTuple):
1149
+ im: Image.Image
1150
+ bbox: tuple[int, int, int, int] | None
1151
+ encoderinfo: dict[str, Any]
1152
+
1153
+
1154
+ def _write_multiple_frames(
1155
+ im: Image.Image,
1156
+ fp: IO[bytes],
1157
+ chunk: Callable[..., None],
1158
+ mode: str,
1159
+ rawmode: str,
1160
+ default_image: Image.Image | None,
1161
+ append_images: list[Image.Image],
1162
+ ) -> Image.Image | None:
1163
+ duration = im.encoderinfo.get("duration")
1164
+ loop = im.encoderinfo.get("loop", im.info.get("loop", 0))
1165
+ disposal = im.encoderinfo.get("disposal", im.info.get("disposal", Disposal.OP_NONE))
1166
+ blend = im.encoderinfo.get("blend", im.info.get("blend", Blend.OP_SOURCE))
1167
+
1168
+ if default_image:
1169
+ chain = itertools.chain(append_images)
1170
+ else:
1171
+ chain = itertools.chain([im], append_images)
1172
+
1173
+ im_frames: list[_Frame] = []
1174
+ frame_count = 0
1175
+ for im_seq in chain:
1176
+ for im_frame in ImageSequence.Iterator(im_seq):
1177
+ if im_frame.mode == mode:
1178
+ im_frame = im_frame.copy()
1179
+ else:
1180
+ im_frame = im_frame.convert(mode)
1181
+ encoderinfo = im.encoderinfo.copy()
1182
+ if isinstance(duration, (list, tuple)):
1183
+ encoderinfo["duration"] = duration[frame_count]
1184
+ elif duration is None and "duration" in im_frame.info:
1185
+ encoderinfo["duration"] = im_frame.info["duration"]
1186
+ if isinstance(disposal, (list, tuple)):
1187
+ encoderinfo["disposal"] = disposal[frame_count]
1188
+ if isinstance(blend, (list, tuple)):
1189
+ encoderinfo["blend"] = blend[frame_count]
1190
+ frame_count += 1
1191
+
1192
+ if im_frames:
1193
+ previous = im_frames[-1]
1194
+ prev_disposal = previous.encoderinfo.get("disposal")
1195
+ prev_blend = previous.encoderinfo.get("blend")
1196
+ if prev_disposal == Disposal.OP_PREVIOUS and len(im_frames) < 2:
1197
+ prev_disposal = Disposal.OP_BACKGROUND
1198
+
1199
+ if prev_disposal == Disposal.OP_BACKGROUND:
1200
+ base_im = previous.im.copy()
1201
+ dispose = Image.core.fill("RGBA", im.size, (0, 0, 0, 0))
1202
+ bbox = previous.bbox
1203
+ if bbox:
1204
+ dispose = dispose.crop(bbox)
1205
+ else:
1206
+ bbox = (0, 0) + im.size
1207
+ base_im.paste(dispose, bbox)
1208
+ elif prev_disposal == Disposal.OP_PREVIOUS:
1209
+ base_im = im_frames[-2].im
1210
+ else:
1211
+ base_im = previous.im
1212
+ delta = ImageChops.subtract_modulo(
1213
+ im_frame.convert("RGBA"), base_im.convert("RGBA")
1214
+ )
1215
+ bbox = delta.getbbox(alpha_only=False)
1216
+ if (
1217
+ not bbox
1218
+ and prev_disposal == encoderinfo.get("disposal")
1219
+ and prev_blend == encoderinfo.get("blend")
1220
+ and "duration" in encoderinfo
1221
+ ):
1222
+ previous.encoderinfo["duration"] += encoderinfo["duration"]
1223
+ continue
1224
+ else:
1225
+ bbox = None
1226
+ im_frames.append(_Frame(im_frame, bbox, encoderinfo))
1227
+
1228
+ if len(im_frames) == 1 and not default_image:
1229
+ return im_frames[0].im
1230
+
1231
+ # animation control
1232
+ chunk(
1233
+ fp,
1234
+ b"acTL",
1235
+ o32(len(im_frames)), # 0: num_frames
1236
+ o32(loop), # 4: num_plays
1237
+ )
1238
+
1239
+ # default image IDAT (if it exists)
1240
+ if default_image:
1241
+ if im.mode != mode:
1242
+ im = im.convert(mode)
1243
+ ImageFile._save(
1244
+ im,
1245
+ cast(IO[bytes], _idat(fp, chunk)),
1246
+ [ImageFile._Tile("zip", (0, 0) + im.size, 0, rawmode)],
1247
+ )
1248
+
1249
+ seq_num = 0
1250
+ for frame, frame_data in enumerate(im_frames):
1251
+ im_frame = frame_data.im
1252
+ if not frame_data.bbox:
1253
+ bbox = (0, 0) + im_frame.size
1254
+ else:
1255
+ bbox = frame_data.bbox
1256
+ im_frame = im_frame.crop(bbox)
1257
+ size = im_frame.size
1258
+ encoderinfo = frame_data.encoderinfo
1259
+ frame_duration = int(round(encoderinfo.get("duration", 0)))
1260
+ frame_disposal = encoderinfo.get("disposal", disposal)
1261
+ frame_blend = encoderinfo.get("blend", blend)
1262
+ # frame control
1263
+ chunk(
1264
+ fp,
1265
+ b"fcTL",
1266
+ o32(seq_num), # sequence_number
1267
+ o32(size[0]), # width
1268
+ o32(size[1]), # height
1269
+ o32(bbox[0]), # x_offset
1270
+ o32(bbox[1]), # y_offset
1271
+ o16(frame_duration), # delay_numerator
1272
+ o16(1000), # delay_denominator
1273
+ o8(frame_disposal), # dispose_op
1274
+ o8(frame_blend), # blend_op
1275
+ )
1276
+ seq_num += 1
1277
+ # frame data
1278
+ if frame == 0 and not default_image:
1279
+ # first frame must be in IDAT chunks for backwards compatibility
1280
+ ImageFile._save(
1281
+ im_frame,
1282
+ cast(IO[bytes], _idat(fp, chunk)),
1283
+ [ImageFile._Tile("zip", (0, 0) + im_frame.size, 0, rawmode)],
1284
+ )
1285
+ else:
1286
+ fdat_chunks = _fdat(fp, chunk, seq_num)
1287
+ ImageFile._save(
1288
+ im_frame,
1289
+ cast(IO[bytes], fdat_chunks),
1290
+ [ImageFile._Tile("zip", (0, 0) + im_frame.size, 0, rawmode)],
1291
+ )
1292
+ seq_num = fdat_chunks.seq_num
1293
+ return None
1294
+
1295
+
1296
+ def _save_all(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
1297
+ _save(im, fp, filename, save_all=True)
1298
+
1299
+
1300
+ def _save(
1301
+ im: Image.Image,
1302
+ fp: IO[bytes],
1303
+ filename: str | bytes,
1304
+ chunk: Callable[..., None] = putchunk,
1305
+ save_all: bool = False,
1306
+ ) -> None:
1307
+ # save an image to disk (called by the save method)
1308
+
1309
+ if save_all:
1310
+ default_image = im.encoderinfo.get(
1311
+ "default_image", im.info.get("default_image")
1312
+ )
1313
+ modes = set()
1314
+ sizes = set()
1315
+ append_images = im.encoderinfo.get("append_images", [])
1316
+ for im_seq in itertools.chain([im], append_images):
1317
+ for im_frame in ImageSequence.Iterator(im_seq):
1318
+ modes.add(im_frame.mode)
1319
+ sizes.add(im_frame.size)
1320
+ for mode in ("RGBA", "RGB", "P"):
1321
+ if mode in modes:
1322
+ break
1323
+ else:
1324
+ mode = modes.pop()
1325
+ size = tuple(max(frame_size[i] for frame_size in sizes) for i in range(2))
1326
+ else:
1327
+ size = im.size
1328
+ mode = im.mode
1329
+
1330
+ outmode = mode
1331
+ if mode == "P":
1332
+ #
1333
+ # attempt to minimize storage requirements for palette images
1334
+ if "bits" in im.encoderinfo:
1335
+ # number of bits specified by user
1336
+ colors = min(1 << im.encoderinfo["bits"], 256)
1337
+ else:
1338
+ # check palette contents
1339
+ if im.palette:
1340
+ colors = max(min(len(im.palette.getdata()[1]) // 3, 256), 1)
1341
+ else:
1342
+ colors = 256
1343
+
1344
+ if colors <= 16:
1345
+ if colors <= 2:
1346
+ bits = 1
1347
+ elif colors <= 4:
1348
+ bits = 2
1349
+ else:
1350
+ bits = 4
1351
+ outmode += f";{bits}"
1352
+
1353
+ # encoder options
1354
+ im.encoderconfig = (
1355
+ im.encoderinfo.get("optimize", False),
1356
+ im.encoderinfo.get("compress_level", -1),
1357
+ im.encoderinfo.get("compress_type", -1),
1358
+ im.encoderinfo.get("dictionary", b""),
1359
+ )
1360
+
1361
+ # get the corresponding PNG mode
1362
+ try:
1363
+ rawmode, bit_depth, color_type = _OUTMODES[outmode]
1364
+ except KeyError as e:
1365
+ msg = f"cannot write mode {mode} as PNG"
1366
+ raise OSError(msg) from e
1367
+
1368
+ #
1369
+ # write minimal PNG file
1370
+
1371
+ fp.write(_MAGIC)
1372
+
1373
+ chunk(
1374
+ fp,
1375
+ b"IHDR",
1376
+ o32(size[0]), # 0: size
1377
+ o32(size[1]),
1378
+ bit_depth,
1379
+ color_type,
1380
+ b"\0", # 10: compression
1381
+ b"\0", # 11: filter category
1382
+ b"\0", # 12: interlace flag
1383
+ )
1384
+
1385
+ chunks = [b"cHRM", b"gAMA", b"sBIT", b"sRGB", b"tIME"]
1386
+
1387
+ icc = im.encoderinfo.get("icc_profile", im.info.get("icc_profile"))
1388
+ if icc:
1389
+ # ICC profile
1390
+ # according to PNG spec, the iCCP chunk contains:
1391
+ # Profile name 1-79 bytes (character string)
1392
+ # Null separator 1 byte (null character)
1393
+ # Compression method 1 byte (0)
1394
+ # Compressed profile n bytes (zlib with deflate compression)
1395
+ name = b"ICC Profile"
1396
+ data = name + b"\0\0" + zlib.compress(icc)
1397
+ chunk(fp, b"iCCP", data)
1398
+
1399
+ # You must either have sRGB or iCCP.
1400
+ # Disallow sRGB chunks when an iCCP-chunk has been emitted.
1401
+ chunks.remove(b"sRGB")
1402
+
1403
+ info = im.encoderinfo.get("pnginfo")
1404
+ if info:
1405
+ chunks_multiple_allowed = [b"sPLT", b"iTXt", b"tEXt", b"zTXt"]
1406
+ for info_chunk in info.chunks:
1407
+ cid, data = info_chunk[:2]
1408
+ if cid in chunks:
1409
+ chunks.remove(cid)
1410
+ chunk(fp, cid, data)
1411
+ elif cid in chunks_multiple_allowed:
1412
+ chunk(fp, cid, data)
1413
+ elif cid[1:2].islower():
1414
+ # Private chunk
1415
+ after_idat = len(info_chunk) == 3 and info_chunk[2]
1416
+ if not after_idat:
1417
+ chunk(fp, cid, data)
1418
+
1419
+ if im.mode == "P":
1420
+ palette_byte_number = colors * 3
1421
+ palette_bytes = im.im.getpalette("RGB")[:palette_byte_number]
1422
+ while len(palette_bytes) < palette_byte_number:
1423
+ palette_bytes += b"\0"
1424
+ chunk(fp, b"PLTE", palette_bytes)
1425
+
1426
+ transparency = im.encoderinfo.get("transparency", im.info.get("transparency", None))
1427
+
1428
+ if transparency or transparency == 0:
1429
+ if im.mode == "P":
1430
+ # limit to actual palette size
1431
+ alpha_bytes = colors
1432
+ if isinstance(transparency, bytes):
1433
+ chunk(fp, b"tRNS", transparency[:alpha_bytes])
1434
+ else:
1435
+ transparency = max(0, min(255, transparency))
1436
+ alpha = b"\xFF" * transparency + b"\0"
1437
+ chunk(fp, b"tRNS", alpha[:alpha_bytes])
1438
+ elif im.mode in ("1", "L", "I", "I;16"):
1439
+ transparency = max(0, min(65535, transparency))
1440
+ chunk(fp, b"tRNS", o16(transparency))
1441
+ elif im.mode == "RGB":
1442
+ red, green, blue = transparency
1443
+ chunk(fp, b"tRNS", o16(red) + o16(green) + o16(blue))
1444
+ else:
1445
+ if "transparency" in im.encoderinfo:
1446
+ # don't bother with transparency if it's an RGBA
1447
+ # and it's in the info dict. It's probably just stale.
1448
+ msg = "cannot use transparency for this mode"
1449
+ raise OSError(msg)
1450
+ else:
1451
+ if im.mode == "P" and im.im.getpalettemode() == "RGBA":
1452
+ alpha = im.im.getpalette("RGBA", "A")
1453
+ alpha_bytes = colors
1454
+ chunk(fp, b"tRNS", alpha[:alpha_bytes])
1455
+
1456
+ dpi = im.encoderinfo.get("dpi")
1457
+ if dpi:
1458
+ chunk(
1459
+ fp,
1460
+ b"pHYs",
1461
+ o32(int(dpi[0] / 0.0254 + 0.5)),
1462
+ o32(int(dpi[1] / 0.0254 + 0.5)),
1463
+ b"\x01",
1464
+ )
1465
+
1466
+ if info:
1467
+ chunks = [b"bKGD", b"hIST"]
1468
+ for info_chunk in info.chunks:
1469
+ cid, data = info_chunk[:2]
1470
+ if cid in chunks:
1471
+ chunks.remove(cid)
1472
+ chunk(fp, cid, data)
1473
+
1474
+ exif = im.encoderinfo.get("exif")
1475
+ if exif:
1476
+ if isinstance(exif, Image.Exif):
1477
+ exif = exif.tobytes(8)
1478
+ if exif.startswith(b"Exif\x00\x00"):
1479
+ exif = exif[6:]
1480
+ chunk(fp, b"eXIf", exif)
1481
+
1482
+ single_im: Image.Image | None = im
1483
+ if save_all:
1484
+ single_im = _write_multiple_frames(
1485
+ im, fp, chunk, mode, rawmode, default_image, append_images
1486
+ )
1487
+ if single_im:
1488
+ ImageFile._save(
1489
+ single_im,
1490
+ cast(IO[bytes], _idat(fp, chunk)),
1491
+ [ImageFile._Tile("zip", (0, 0) + single_im.size, 0, rawmode)],
1492
+ )
1493
+
1494
+ if info:
1495
+ for info_chunk in info.chunks:
1496
+ cid, data = info_chunk[:2]
1497
+ if cid[1:2].islower():
1498
+ # Private chunk
1499
+ after_idat = len(info_chunk) == 3 and info_chunk[2]
1500
+ if after_idat:
1501
+ chunk(fp, cid, data)
1502
+
1503
+ chunk(fp, b"IEND", b"")
1504
+
1505
+ if hasattr(fp, "flush"):
1506
+ fp.flush()
1507
+
1508
+
1509
+ # --------------------------------------------------------------------
1510
+ # PNG chunk converter
1511
+
1512
+
1513
+ def getchunks(im: Image.Image, **params: Any) -> list[tuple[bytes, bytes, bytes]]:
1514
+ """Return a list of PNG chunks representing this image."""
1515
+ from io import BytesIO
1516
+
1517
+ chunks = []
1518
+
1519
+ def append(fp: IO[bytes], cid: bytes, *data: bytes) -> None:
1520
+ byte_data = b"".join(data)
1521
+ crc = o32(_crc32(byte_data, _crc32(cid)))
1522
+ chunks.append((cid, byte_data, crc))
1523
+
1524
+ fp = BytesIO()
1525
+
1526
+ try:
1527
+ im.encoderinfo = params
1528
+ _save(im, fp, "", append)
1529
+ finally:
1530
+ del im.encoderinfo
1531
+
1532
+ return chunks
1533
+
1534
+
1535
+ # --------------------------------------------------------------------
1536
+ # Registry
1537
+
1538
+ Image.register_open(PngImageFile.format, PngImageFile, _accept)
1539
+ Image.register_save(PngImageFile.format, _save)
1540
+ Image.register_save_all(PngImageFile.format, _save_all)
1541
+
1542
+ Image.register_extensions(PngImageFile.format, [".png", ".apng"])
1543
+
1544
+ Image.register_mime(PngImageFile.format, "image/png")
phi4/lib/python3.10/site-packages/PIL/SgiImagePlugin.py ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # SGI image file handling
6
+ #
7
+ # See "The SGI Image File Format (Draft version 0.97)", Paul Haeberli.
8
+ # <ftp://ftp.sgi.com/graphics/SGIIMAGESPEC>
9
+ #
10
+ #
11
+ # History:
12
+ # 2017-22-07 mb Add RLE decompression
13
+ # 2016-16-10 mb Add save method without compression
14
+ # 1995-09-10 fl Created
15
+ #
16
+ # Copyright (c) 2016 by Mickael Bonfill.
17
+ # Copyright (c) 2008 by Karsten Hiddemann.
18
+ # Copyright (c) 1997 by Secret Labs AB.
19
+ # Copyright (c) 1995 by Fredrik Lundh.
20
+ #
21
+ # See the README file for information on usage and redistribution.
22
+ #
23
+ from __future__ import annotations
24
+
25
+ import os
26
+ import struct
27
+ from typing import IO
28
+
29
+ from . import Image, ImageFile
30
+ from ._binary import i16be as i16
31
+ from ._binary import o8
32
+
33
+
34
+ def _accept(prefix: bytes) -> bool:
35
+ return len(prefix) >= 2 and i16(prefix) == 474
36
+
37
+
38
+ MODES = {
39
+ (1, 1, 1): "L",
40
+ (1, 2, 1): "L",
41
+ (2, 1, 1): "L;16B",
42
+ (2, 2, 1): "L;16B",
43
+ (1, 3, 3): "RGB",
44
+ (2, 3, 3): "RGB;16B",
45
+ (1, 3, 4): "RGBA",
46
+ (2, 3, 4): "RGBA;16B",
47
+ }
48
+
49
+
50
+ ##
51
+ # Image plugin for SGI images.
52
+ class SgiImageFile(ImageFile.ImageFile):
53
+ format = "SGI"
54
+ format_description = "SGI Image File Format"
55
+
56
+ def _open(self) -> None:
57
+ # HEAD
58
+ assert self.fp is not None
59
+
60
+ headlen = 512
61
+ s = self.fp.read(headlen)
62
+
63
+ if not _accept(s):
64
+ msg = "Not an SGI image file"
65
+ raise ValueError(msg)
66
+
67
+ # compression : verbatim or RLE
68
+ compression = s[2]
69
+
70
+ # bpc : 1 or 2 bytes (8bits or 16bits)
71
+ bpc = s[3]
72
+
73
+ # dimension : 1, 2 or 3 (depending on xsize, ysize and zsize)
74
+ dimension = i16(s, 4)
75
+
76
+ # xsize : width
77
+ xsize = i16(s, 6)
78
+
79
+ # ysize : height
80
+ ysize = i16(s, 8)
81
+
82
+ # zsize : channels count
83
+ zsize = i16(s, 10)
84
+
85
+ # layout
86
+ layout = bpc, dimension, zsize
87
+
88
+ # determine mode from bits/zsize
89
+ rawmode = ""
90
+ try:
91
+ rawmode = MODES[layout]
92
+ except KeyError:
93
+ pass
94
+
95
+ if rawmode == "":
96
+ msg = "Unsupported SGI image mode"
97
+ raise ValueError(msg)
98
+
99
+ self._size = xsize, ysize
100
+ self._mode = rawmode.split(";")[0]
101
+ if self.mode == "RGB":
102
+ self.custom_mimetype = "image/rgb"
103
+
104
+ # orientation -1 : scanlines begins at the bottom-left corner
105
+ orientation = -1
106
+
107
+ # decoder info
108
+ if compression == 0:
109
+ pagesize = xsize * ysize * bpc
110
+ if bpc == 2:
111
+ self.tile = [
112
+ ImageFile._Tile(
113
+ "SGI16",
114
+ (0, 0) + self.size,
115
+ headlen,
116
+ (self.mode, 0, orientation),
117
+ )
118
+ ]
119
+ else:
120
+ self.tile = []
121
+ offset = headlen
122
+ for layer in self.mode:
123
+ self.tile.append(
124
+ ImageFile._Tile(
125
+ "raw", (0, 0) + self.size, offset, (layer, 0, orientation)
126
+ )
127
+ )
128
+ offset += pagesize
129
+ elif compression == 1:
130
+ self.tile = [
131
+ ImageFile._Tile(
132
+ "sgi_rle", (0, 0) + self.size, headlen, (rawmode, orientation, bpc)
133
+ )
134
+ ]
135
+
136
+
137
+ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
138
+ if im.mode not in {"RGB", "RGBA", "L"}:
139
+ msg = "Unsupported SGI image mode"
140
+ raise ValueError(msg)
141
+
142
+ # Get the keyword arguments
143
+ info = im.encoderinfo
144
+
145
+ # Byte-per-pixel precision, 1 = 8bits per pixel
146
+ bpc = info.get("bpc", 1)
147
+
148
+ if bpc not in (1, 2):
149
+ msg = "Unsupported number of bytes per pixel"
150
+ raise ValueError(msg)
151
+
152
+ # Flip the image, since the origin of SGI file is the bottom-left corner
153
+ orientation = -1
154
+ # Define the file as SGI File Format
155
+ magic_number = 474
156
+ # Run-Length Encoding Compression - Unsupported at this time
157
+ rle = 0
158
+
159
+ # Number of dimensions (x,y,z)
160
+ dim = 3
161
+ # X Dimension = width / Y Dimension = height
162
+ x, y = im.size
163
+ if im.mode == "L" and y == 1:
164
+ dim = 1
165
+ elif im.mode == "L":
166
+ dim = 2
167
+ # Z Dimension: Number of channels
168
+ z = len(im.mode)
169
+
170
+ if dim in {1, 2}:
171
+ z = 1
172
+
173
+ # assert we've got the right number of bands.
174
+ if len(im.getbands()) != z:
175
+ msg = f"incorrect number of bands in SGI write: {z} vs {len(im.getbands())}"
176
+ raise ValueError(msg)
177
+
178
+ # Minimum Byte value
179
+ pinmin = 0
180
+ # Maximum Byte value (255 = 8bits per pixel)
181
+ pinmax = 255
182
+ # Image name (79 characters max, truncated below in write)
183
+ img_name = os.path.splitext(os.path.basename(filename))[0]
184
+ if isinstance(img_name, str):
185
+ img_name = img_name.encode("ascii", "ignore")
186
+ # Standard representation of pixel in the file
187
+ colormap = 0
188
+ fp.write(struct.pack(">h", magic_number))
189
+ fp.write(o8(rle))
190
+ fp.write(o8(bpc))
191
+ fp.write(struct.pack(">H", dim))
192
+ fp.write(struct.pack(">H", x))
193
+ fp.write(struct.pack(">H", y))
194
+ fp.write(struct.pack(">H", z))
195
+ fp.write(struct.pack(">l", pinmin))
196
+ fp.write(struct.pack(">l", pinmax))
197
+ fp.write(struct.pack("4s", b"")) # dummy
198
+ fp.write(struct.pack("79s", img_name)) # truncates to 79 chars
199
+ fp.write(struct.pack("s", b"")) # force null byte after img_name
200
+ fp.write(struct.pack(">l", colormap))
201
+ fp.write(struct.pack("404s", b"")) # dummy
202
+
203
+ rawmode = "L"
204
+ if bpc == 2:
205
+ rawmode = "L;16B"
206
+
207
+ for channel in im.split():
208
+ fp.write(channel.tobytes("raw", rawmode, 0, orientation))
209
+
210
+ if hasattr(fp, "flush"):
211
+ fp.flush()
212
+
213
+
214
+ class SGI16Decoder(ImageFile.PyDecoder):
215
+ _pulls_fd = True
216
+
217
+ def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:
218
+ assert self.fd is not None
219
+ assert self.im is not None
220
+
221
+ rawmode, stride, orientation = self.args
222
+ pagesize = self.state.xsize * self.state.ysize
223
+ zsize = len(self.mode)
224
+ self.fd.seek(512)
225
+
226
+ for band in range(zsize):
227
+ channel = Image.new("L", (self.state.xsize, self.state.ysize))
228
+ channel.frombytes(
229
+ self.fd.read(2 * pagesize), "raw", "L;16B", stride, orientation
230
+ )
231
+ self.im.putband(channel.im, band)
232
+
233
+ return -1, 0
234
+
235
+
236
+ #
237
+ # registry
238
+
239
+
240
+ Image.register_decoder("SGI16", SGI16Decoder)
241
+ Image.register_open(SgiImageFile.format, SgiImageFile, _accept)
242
+ Image.register_save(SgiImageFile.format, _save)
243
+ Image.register_mime(SgiImageFile.format, "image/sgi")
244
+
245
+ Image.register_extensions(SgiImageFile.format, [".bw", ".rgb", ".rgba", ".sgi"])
246
+
247
+ # End of file
phi4/lib/python3.10/site-packages/PIL/SpiderImagePlugin.py ADDED
@@ -0,0 +1,326 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ #
4
+ # SPIDER image file handling
5
+ #
6
+ # History:
7
+ # 2004-08-02 Created BB
8
+ # 2006-03-02 added save method
9
+ # 2006-03-13 added support for stack images
10
+ #
11
+ # Copyright (c) 2004 by Health Research Inc. (HRI) RENSSELAER, NY 12144.
12
+ # Copyright (c) 2004 by William Baxter.
13
+ # Copyright (c) 2004 by Secret Labs AB.
14
+ # Copyright (c) 2004 by Fredrik Lundh.
15
+ #
16
+
17
+ ##
18
+ # Image plugin for the Spider image format. This format is used
19
+ # by the SPIDER software, in processing image data from electron
20
+ # microscopy and tomography.
21
+ ##
22
+
23
+ #
24
+ # SpiderImagePlugin.py
25
+ #
26
+ # The Spider image format is used by SPIDER software, in processing
27
+ # image data from electron microscopy and tomography.
28
+ #
29
+ # Spider home page:
30
+ # https://spider.wadsworth.org/spider_doc/spider/docs/spider.html
31
+ #
32
+ # Details about the Spider image format:
33
+ # https://spider.wadsworth.org/spider_doc/spider/docs/image_doc.html
34
+ #
35
+ from __future__ import annotations
36
+
37
+ import os
38
+ import struct
39
+ import sys
40
+ from typing import IO, TYPE_CHECKING, Any, cast
41
+
42
+ from . import Image, ImageFile
43
+
44
+
45
+ def isInt(f: Any) -> int:
46
+ try:
47
+ i = int(f)
48
+ if f - i == 0:
49
+ return 1
50
+ else:
51
+ return 0
52
+ except (ValueError, OverflowError):
53
+ return 0
54
+
55
+
56
+ iforms = [1, 3, -11, -12, -21, -22]
57
+
58
+
59
+ # There is no magic number to identify Spider files, so just check a
60
+ # series of header locations to see if they have reasonable values.
61
+ # Returns no. of bytes in the header, if it is a valid Spider header,
62
+ # otherwise returns 0
63
+
64
+
65
+ def isSpiderHeader(t: tuple[float, ...]) -> int:
66
+ h = (99,) + t # add 1 value so can use spider header index start=1
67
+ # header values 1,2,5,12,13,22,23 should be integers
68
+ for i in [1, 2, 5, 12, 13, 22, 23]:
69
+ if not isInt(h[i]):
70
+ return 0
71
+ # check iform
72
+ iform = int(h[5])
73
+ if iform not in iforms:
74
+ return 0
75
+ # check other header values
76
+ labrec = int(h[13]) # no. records in file header
77
+ labbyt = int(h[22]) # total no. of bytes in header
78
+ lenbyt = int(h[23]) # record length in bytes
79
+ if labbyt != (labrec * lenbyt):
80
+ return 0
81
+ # looks like a valid header
82
+ return labbyt
83
+
84
+
85
+ def isSpiderImage(filename: str) -> int:
86
+ with open(filename, "rb") as fp:
87
+ f = fp.read(92) # read 23 * 4 bytes
88
+ t = struct.unpack(">23f", f) # try big-endian first
89
+ hdrlen = isSpiderHeader(t)
90
+ if hdrlen == 0:
91
+ t = struct.unpack("<23f", f) # little-endian
92
+ hdrlen = isSpiderHeader(t)
93
+ return hdrlen
94
+
95
+
96
+ class SpiderImageFile(ImageFile.ImageFile):
97
+ format = "SPIDER"
98
+ format_description = "Spider 2D image"
99
+ _close_exclusive_fp_after_loading = False
100
+
101
+ def _open(self) -> None:
102
+ # check header
103
+ n = 27 * 4 # read 27 float values
104
+ f = self.fp.read(n)
105
+
106
+ try:
107
+ self.bigendian = 1
108
+ t = struct.unpack(">27f", f) # try big-endian first
109
+ hdrlen = isSpiderHeader(t)
110
+ if hdrlen == 0:
111
+ self.bigendian = 0
112
+ t = struct.unpack("<27f", f) # little-endian
113
+ hdrlen = isSpiderHeader(t)
114
+ if hdrlen == 0:
115
+ msg = "not a valid Spider file"
116
+ raise SyntaxError(msg)
117
+ except struct.error as e:
118
+ msg = "not a valid Spider file"
119
+ raise SyntaxError(msg) from e
120
+
121
+ h = (99,) + t # add 1 value : spider header index starts at 1
122
+ iform = int(h[5])
123
+ if iform != 1:
124
+ msg = "not a Spider 2D image"
125
+ raise SyntaxError(msg)
126
+
127
+ self._size = int(h[12]), int(h[2]) # size in pixels (width, height)
128
+ self.istack = int(h[24])
129
+ self.imgnumber = int(h[27])
130
+
131
+ if self.istack == 0 and self.imgnumber == 0:
132
+ # stk=0, img=0: a regular 2D image
133
+ offset = hdrlen
134
+ self._nimages = 1
135
+ elif self.istack > 0 and self.imgnumber == 0:
136
+ # stk>0, img=0: Opening the stack for the first time
137
+ self.imgbytes = int(h[12]) * int(h[2]) * 4
138
+ self.hdrlen = hdrlen
139
+ self._nimages = int(h[26])
140
+ # Point to the first image in the stack
141
+ offset = hdrlen * 2
142
+ self.imgnumber = 1
143
+ elif self.istack == 0 and self.imgnumber > 0:
144
+ # stk=0, img>0: an image within the stack
145
+ offset = hdrlen + self.stkoffset
146
+ self.istack = 2 # So Image knows it's still a stack
147
+ else:
148
+ msg = "inconsistent stack header values"
149
+ raise SyntaxError(msg)
150
+
151
+ if self.bigendian:
152
+ self.rawmode = "F;32BF"
153
+ else:
154
+ self.rawmode = "F;32F"
155
+ self._mode = "F"
156
+
157
+ self.tile = [ImageFile._Tile("raw", (0, 0) + self.size, offset, self.rawmode)]
158
+ self._fp = self.fp # FIXME: hack
159
+
160
+ @property
161
+ def n_frames(self) -> int:
162
+ return self._nimages
163
+
164
+ @property
165
+ def is_animated(self) -> bool:
166
+ return self._nimages > 1
167
+
168
+ # 1st image index is zero (although SPIDER imgnumber starts at 1)
169
+ def tell(self) -> int:
170
+ if self.imgnumber < 1:
171
+ return 0
172
+ else:
173
+ return self.imgnumber - 1
174
+
175
+ def seek(self, frame: int) -> None:
176
+ if self.istack == 0:
177
+ msg = "attempt to seek in a non-stack file"
178
+ raise EOFError(msg)
179
+ if not self._seek_check(frame):
180
+ return
181
+ self.stkoffset = self.hdrlen + frame * (self.hdrlen + self.imgbytes)
182
+ self.fp = self._fp
183
+ self.fp.seek(self.stkoffset)
184
+ self._open()
185
+
186
+ # returns a byte image after rescaling to 0..255
187
+ def convert2byte(self, depth: int = 255) -> Image.Image:
188
+ extrema = self.getextrema()
189
+ assert isinstance(extrema[0], float)
190
+ minimum, maximum = cast(tuple[float, float], extrema)
191
+ m: float = 1
192
+ if maximum != minimum:
193
+ m = depth / (maximum - minimum)
194
+ b = -m * minimum
195
+ return self.point(lambda i: i * m + b).convert("L")
196
+
197
+ if TYPE_CHECKING:
198
+ from . import ImageTk
199
+
200
+ # returns a ImageTk.PhotoImage object, after rescaling to 0..255
201
+ def tkPhotoImage(self) -> ImageTk.PhotoImage:
202
+ from . import ImageTk
203
+
204
+ return ImageTk.PhotoImage(self.convert2byte(), palette=256)
205
+
206
+
207
+ # --------------------------------------------------------------------
208
+ # Image series
209
+
210
+
211
+ # given a list of filenames, return a list of images
212
+ def loadImageSeries(filelist: list[str] | None = None) -> list[Image.Image] | None:
213
+ """create a list of :py:class:`~PIL.Image.Image` objects for use in a montage"""
214
+ if filelist is None or len(filelist) < 1:
215
+ return None
216
+
217
+ byte_imgs = []
218
+ for img in filelist:
219
+ if not os.path.exists(img):
220
+ print(f"unable to find {img}")
221
+ continue
222
+ try:
223
+ with Image.open(img) as im:
224
+ assert isinstance(im, SpiderImageFile)
225
+ byte_im = im.convert2byte()
226
+ except Exception:
227
+ if not isSpiderImage(img):
228
+ print(f"{img} is not a Spider image file")
229
+ continue
230
+ byte_im.info["filename"] = img
231
+ byte_imgs.append(byte_im)
232
+ return byte_imgs
233
+
234
+
235
+ # --------------------------------------------------------------------
236
+ # For saving images in Spider format
237
+
238
+
239
+ def makeSpiderHeader(im: Image.Image) -> list[bytes]:
240
+ nsam, nrow = im.size
241
+ lenbyt = nsam * 4 # There are labrec records in the header
242
+ labrec = int(1024 / lenbyt)
243
+ if 1024 % lenbyt != 0:
244
+ labrec += 1
245
+ labbyt = labrec * lenbyt
246
+ nvalues = int(labbyt / 4)
247
+ if nvalues < 23:
248
+ return []
249
+
250
+ hdr = [0.0] * nvalues
251
+
252
+ # NB these are Fortran indices
253
+ hdr[1] = 1.0 # nslice (=1 for an image)
254
+ hdr[2] = float(nrow) # number of rows per slice
255
+ hdr[3] = float(nrow) # number of records in the image
256
+ hdr[5] = 1.0 # iform for 2D image
257
+ hdr[12] = float(nsam) # number of pixels per line
258
+ hdr[13] = float(labrec) # number of records in file header
259
+ hdr[22] = float(labbyt) # total number of bytes in header
260
+ hdr[23] = float(lenbyt) # record length in bytes
261
+
262
+ # adjust for Fortran indexing
263
+ hdr = hdr[1:]
264
+ hdr.append(0.0)
265
+ # pack binary data into a string
266
+ return [struct.pack("f", v) for v in hdr]
267
+
268
+
269
+ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
270
+ if im.mode[0] != "F":
271
+ im = im.convert("F")
272
+
273
+ hdr = makeSpiderHeader(im)
274
+ if len(hdr) < 256:
275
+ msg = "Error creating Spider header"
276
+ raise OSError(msg)
277
+
278
+ # write the SPIDER header
279
+ fp.writelines(hdr)
280
+
281
+ rawmode = "F;32NF" # 32-bit native floating point
282
+ ImageFile._save(im, fp, [ImageFile._Tile("raw", (0, 0) + im.size, 0, rawmode)])
283
+
284
+
285
+ def _save_spider(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
286
+ # get the filename extension and register it with Image
287
+ filename_ext = os.path.splitext(filename)[1]
288
+ ext = filename_ext.decode() if isinstance(filename_ext, bytes) else filename_ext
289
+ Image.register_extension(SpiderImageFile.format, ext)
290
+ _save(im, fp, filename)
291
+
292
+
293
+ # --------------------------------------------------------------------
294
+
295
+
296
+ Image.register_open(SpiderImageFile.format, SpiderImageFile)
297
+ Image.register_save(SpiderImageFile.format, _save_spider)
298
+
299
+ if __name__ == "__main__":
300
+ if len(sys.argv) < 2:
301
+ print("Syntax: python3 SpiderImagePlugin.py [infile] [outfile]")
302
+ sys.exit()
303
+
304
+ filename = sys.argv[1]
305
+ if not isSpiderImage(filename):
306
+ print("input image must be in Spider format")
307
+ sys.exit()
308
+
309
+ with Image.open(filename) as im:
310
+ print(f"image: {im}")
311
+ print(f"format: {im.format}")
312
+ print(f"size: {im.size}")
313
+ print(f"mode: {im.mode}")
314
+ print("max, min: ", end=" ")
315
+ print(im.getextrema())
316
+
317
+ if len(sys.argv) > 2:
318
+ outfile = sys.argv[2]
319
+
320
+ # perform some image operation
321
+ im = im.transpose(Image.Transpose.FLIP_LEFT_RIGHT)
322
+ print(
323
+ f"saving a flipped version of {os.path.basename(filename)} "
324
+ f"as {outfile} "
325
+ )
326
+ im.save(outfile, SpiderImageFile.format)
phi4/lib/python3.10/site-packages/PIL/TgaImagePlugin.py ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # TGA file handling
6
+ #
7
+ # History:
8
+ # 95-09-01 fl created (reads 24-bit files only)
9
+ # 97-01-04 fl support more TGA versions, including compressed images
10
+ # 98-07-04 fl fixed orientation and alpha layer bugs
11
+ # 98-09-11 fl fixed orientation for runlength decoder
12
+ #
13
+ # Copyright (c) Secret Labs AB 1997-98.
14
+ # Copyright (c) Fredrik Lundh 1995-97.
15
+ #
16
+ # See the README file for information on usage and redistribution.
17
+ #
18
+ from __future__ import annotations
19
+
20
+ import warnings
21
+ from typing import IO
22
+
23
+ from . import Image, ImageFile, ImagePalette
24
+ from ._binary import i16le as i16
25
+ from ._binary import o8
26
+ from ._binary import o16le as o16
27
+
28
+ #
29
+ # --------------------------------------------------------------------
30
+ # Read RGA file
31
+
32
+
33
+ MODES = {
34
+ # map imagetype/depth to rawmode
35
+ (1, 8): "P",
36
+ (3, 1): "1",
37
+ (3, 8): "L",
38
+ (3, 16): "LA",
39
+ (2, 16): "BGRA;15Z",
40
+ (2, 24): "BGR",
41
+ (2, 32): "BGRA",
42
+ }
43
+
44
+
45
+ ##
46
+ # Image plugin for Targa files.
47
+
48
+
49
+ class TgaImageFile(ImageFile.ImageFile):
50
+ format = "TGA"
51
+ format_description = "Targa"
52
+
53
+ def _open(self) -> None:
54
+ # process header
55
+ assert self.fp is not None
56
+
57
+ s = self.fp.read(18)
58
+
59
+ id_len = s[0]
60
+
61
+ colormaptype = s[1]
62
+ imagetype = s[2]
63
+
64
+ depth = s[16]
65
+
66
+ flags = s[17]
67
+
68
+ self._size = i16(s, 12), i16(s, 14)
69
+
70
+ # validate header fields
71
+ if (
72
+ colormaptype not in (0, 1)
73
+ or self.size[0] <= 0
74
+ or self.size[1] <= 0
75
+ or depth not in (1, 8, 16, 24, 32)
76
+ ):
77
+ msg = "not a TGA file"
78
+ raise SyntaxError(msg)
79
+
80
+ # image mode
81
+ if imagetype in (3, 11):
82
+ self._mode = "L"
83
+ if depth == 1:
84
+ self._mode = "1" # ???
85
+ elif depth == 16:
86
+ self._mode = "LA"
87
+ elif imagetype in (1, 9):
88
+ self._mode = "P" if colormaptype else "L"
89
+ elif imagetype in (2, 10):
90
+ self._mode = "RGB" if depth == 24 else "RGBA"
91
+ else:
92
+ msg = "unknown TGA mode"
93
+ raise SyntaxError(msg)
94
+
95
+ # orientation
96
+ orientation = flags & 0x30
97
+ self._flip_horizontally = orientation in [0x10, 0x30]
98
+ if orientation in [0x20, 0x30]:
99
+ orientation = 1
100
+ elif orientation in [0, 0x10]:
101
+ orientation = -1
102
+ else:
103
+ msg = "unknown TGA orientation"
104
+ raise SyntaxError(msg)
105
+
106
+ self.info["orientation"] = orientation
107
+
108
+ if imagetype & 8:
109
+ self.info["compression"] = "tga_rle"
110
+
111
+ if id_len:
112
+ self.info["id_section"] = self.fp.read(id_len)
113
+
114
+ if colormaptype:
115
+ # read palette
116
+ start, size, mapdepth = i16(s, 3), i16(s, 5), s[7]
117
+ if mapdepth == 16:
118
+ self.palette = ImagePalette.raw(
119
+ "BGRA;15Z", bytes(2 * start) + self.fp.read(2 * size)
120
+ )
121
+ self.palette.mode = "RGBA"
122
+ elif mapdepth == 24:
123
+ self.palette = ImagePalette.raw(
124
+ "BGR", bytes(3 * start) + self.fp.read(3 * size)
125
+ )
126
+ elif mapdepth == 32:
127
+ self.palette = ImagePalette.raw(
128
+ "BGRA", bytes(4 * start) + self.fp.read(4 * size)
129
+ )
130
+ else:
131
+ msg = "unknown TGA map depth"
132
+ raise SyntaxError(msg)
133
+
134
+ # setup tile descriptor
135
+ try:
136
+ rawmode = MODES[(imagetype & 7, depth)]
137
+ if imagetype & 8:
138
+ # compressed
139
+ self.tile = [
140
+ ImageFile._Tile(
141
+ "tga_rle",
142
+ (0, 0) + self.size,
143
+ self.fp.tell(),
144
+ (rawmode, orientation, depth),
145
+ )
146
+ ]
147
+ else:
148
+ self.tile = [
149
+ ImageFile._Tile(
150
+ "raw",
151
+ (0, 0) + self.size,
152
+ self.fp.tell(),
153
+ (rawmode, 0, orientation),
154
+ )
155
+ ]
156
+ except KeyError:
157
+ pass # cannot decode
158
+
159
+ def load_end(self) -> None:
160
+ if self._flip_horizontally:
161
+ self.im = self.im.transpose(Image.Transpose.FLIP_LEFT_RIGHT)
162
+
163
+
164
+ #
165
+ # --------------------------------------------------------------------
166
+ # Write TGA file
167
+
168
+
169
+ SAVE = {
170
+ "1": ("1", 1, 0, 3),
171
+ "L": ("L", 8, 0, 3),
172
+ "LA": ("LA", 16, 0, 3),
173
+ "P": ("P", 8, 1, 1),
174
+ "RGB": ("BGR", 24, 0, 2),
175
+ "RGBA": ("BGRA", 32, 0, 2),
176
+ }
177
+
178
+
179
+ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
180
+ try:
181
+ rawmode, bits, colormaptype, imagetype = SAVE[im.mode]
182
+ except KeyError as e:
183
+ msg = f"cannot write mode {im.mode} as TGA"
184
+ raise OSError(msg) from e
185
+
186
+ if "rle" in im.encoderinfo:
187
+ rle = im.encoderinfo["rle"]
188
+ else:
189
+ compression = im.encoderinfo.get("compression", im.info.get("compression"))
190
+ rle = compression == "tga_rle"
191
+ if rle:
192
+ imagetype += 8
193
+
194
+ id_section = im.encoderinfo.get("id_section", im.info.get("id_section", ""))
195
+ id_len = len(id_section)
196
+ if id_len > 255:
197
+ id_len = 255
198
+ id_section = id_section[:255]
199
+ warnings.warn("id_section has been trimmed to 255 characters")
200
+
201
+ if colormaptype:
202
+ palette = im.im.getpalette("RGB", "BGR")
203
+ colormaplength, colormapentry = len(palette) // 3, 24
204
+ else:
205
+ colormaplength, colormapentry = 0, 0
206
+
207
+ if im.mode in ("LA", "RGBA"):
208
+ flags = 8
209
+ else:
210
+ flags = 0
211
+
212
+ orientation = im.encoderinfo.get("orientation", im.info.get("orientation", -1))
213
+ if orientation > 0:
214
+ flags = flags | 0x20
215
+
216
+ fp.write(
217
+ o8(id_len)
218
+ + o8(colormaptype)
219
+ + o8(imagetype)
220
+ + o16(0) # colormapfirst
221
+ + o16(colormaplength)
222
+ + o8(colormapentry)
223
+ + o16(0)
224
+ + o16(0)
225
+ + o16(im.size[0])
226
+ + o16(im.size[1])
227
+ + o8(bits)
228
+ + o8(flags)
229
+ )
230
+
231
+ if id_section:
232
+ fp.write(id_section)
233
+
234
+ if colormaptype:
235
+ fp.write(palette)
236
+
237
+ if rle:
238
+ ImageFile._save(
239
+ im,
240
+ fp,
241
+ [ImageFile._Tile("tga_rle", (0, 0) + im.size, 0, (rawmode, orientation))],
242
+ )
243
+ else:
244
+ ImageFile._save(
245
+ im,
246
+ fp,
247
+ [ImageFile._Tile("raw", (0, 0) + im.size, 0, (rawmode, 0, orientation))],
248
+ )
249
+
250
+ # write targa version 2 footer
251
+ fp.write(b"\000" * 8 + b"TRUEVISION-XFILE." + b"\000")
252
+
253
+
254
+ #
255
+ # --------------------------------------------------------------------
256
+ # Registry
257
+
258
+
259
+ Image.register_open(TgaImageFile.format, TgaImageFile)
260
+ Image.register_save(TgaImageFile.format, _save)
261
+
262
+ Image.register_extensions(TgaImageFile.format, [".tga", ".icb", ".vda", ".vst"])
263
+
264
+ Image.register_mime(TgaImageFile.format, "image/x-tga")
phi4/lib/python3.10/site-packages/PIL/TiffTags.py ADDED
@@ -0,0 +1,562 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # TIFF tags
6
+ #
7
+ # This module provides clear-text names for various well-known
8
+ # TIFF tags. the TIFF codec works just fine without it.
9
+ #
10
+ # Copyright (c) Secret Labs AB 1999.
11
+ #
12
+ # See the README file for information on usage and redistribution.
13
+ #
14
+
15
+ ##
16
+ # This module provides constants and clear-text names for various
17
+ # well-known TIFF tags.
18
+ ##
19
+ from __future__ import annotations
20
+
21
+ from typing import NamedTuple
22
+
23
+
24
+ class _TagInfo(NamedTuple):
25
+ value: int | None
26
+ name: str
27
+ type: int | None
28
+ length: int | None
29
+ enum: dict[str, int]
30
+
31
+
32
+ class TagInfo(_TagInfo):
33
+ __slots__: list[str] = []
34
+
35
+ def __new__(
36
+ cls,
37
+ value: int | None = None,
38
+ name: str = "unknown",
39
+ type: int | None = None,
40
+ length: int | None = None,
41
+ enum: dict[str, int] | None = None,
42
+ ) -> TagInfo:
43
+ return super().__new__(cls, value, name, type, length, enum or {})
44
+
45
+ def cvt_enum(self, value: str) -> int | str:
46
+ # Using get will call hash(value), which can be expensive
47
+ # for some types (e.g. Fraction). Since self.enum is rarely
48
+ # used, it's usually better to test it first.
49
+ return self.enum.get(value, value) if self.enum else value
50
+
51
+
52
+ def lookup(tag: int, group: int | None = None) -> TagInfo:
53
+ """
54
+ :param tag: Integer tag number
55
+ :param group: Which :py:data:`~PIL.TiffTags.TAGS_V2_GROUPS` to look in
56
+
57
+ .. versionadded:: 8.3.0
58
+
59
+ :returns: Taginfo namedtuple, From the ``TAGS_V2`` info if possible,
60
+ otherwise just populating the value and name from ``TAGS``.
61
+ If the tag is not recognized, "unknown" is returned for the name
62
+
63
+ """
64
+
65
+ if group is not None:
66
+ info = TAGS_V2_GROUPS[group].get(tag) if group in TAGS_V2_GROUPS else None
67
+ else:
68
+ info = TAGS_V2.get(tag)
69
+ return info or TagInfo(tag, TAGS.get(tag, "unknown"))
70
+
71
+
72
+ ##
73
+ # Map tag numbers to tag info.
74
+ #
75
+ # id: (Name, Type, Length[, enum_values])
76
+ #
77
+ # The length here differs from the length in the tiff spec. For
78
+ # numbers, the tiff spec is for the number of fields returned. We
79
+ # agree here. For string-like types, the tiff spec uses the length of
80
+ # field in bytes. In Pillow, we are using the number of expected
81
+ # fields, in general 1 for string-like types.
82
+
83
+
84
+ BYTE = 1
85
+ ASCII = 2
86
+ SHORT = 3
87
+ LONG = 4
88
+ RATIONAL = 5
89
+ SIGNED_BYTE = 6
90
+ UNDEFINED = 7
91
+ SIGNED_SHORT = 8
92
+ SIGNED_LONG = 9
93
+ SIGNED_RATIONAL = 10
94
+ FLOAT = 11
95
+ DOUBLE = 12
96
+ IFD = 13
97
+ LONG8 = 16
98
+
99
+ _tags_v2: dict[int, tuple[str, int, int] | tuple[str, int, int, dict[str, int]]] = {
100
+ 254: ("NewSubfileType", LONG, 1),
101
+ 255: ("SubfileType", SHORT, 1),
102
+ 256: ("ImageWidth", LONG, 1),
103
+ 257: ("ImageLength", LONG, 1),
104
+ 258: ("BitsPerSample", SHORT, 0),
105
+ 259: (
106
+ "Compression",
107
+ SHORT,
108
+ 1,
109
+ {
110
+ "Uncompressed": 1,
111
+ "CCITT 1d": 2,
112
+ "Group 3 Fax": 3,
113
+ "Group 4 Fax": 4,
114
+ "LZW": 5,
115
+ "JPEG": 6,
116
+ "PackBits": 32773,
117
+ },
118
+ ),
119
+ 262: (
120
+ "PhotometricInterpretation",
121
+ SHORT,
122
+ 1,
123
+ {
124
+ "WhiteIsZero": 0,
125
+ "BlackIsZero": 1,
126
+ "RGB": 2,
127
+ "RGB Palette": 3,
128
+ "Transparency Mask": 4,
129
+ "CMYK": 5,
130
+ "YCbCr": 6,
131
+ "CieLAB": 8,
132
+ "CFA": 32803, # TIFF/EP, Adobe DNG
133
+ "LinearRaw": 32892, # Adobe DNG
134
+ },
135
+ ),
136
+ 263: ("Threshholding", SHORT, 1),
137
+ 264: ("CellWidth", SHORT, 1),
138
+ 265: ("CellLength", SHORT, 1),
139
+ 266: ("FillOrder", SHORT, 1),
140
+ 269: ("DocumentName", ASCII, 1),
141
+ 270: ("ImageDescription", ASCII, 1),
142
+ 271: ("Make", ASCII, 1),
143
+ 272: ("Model", ASCII, 1),
144
+ 273: ("StripOffsets", LONG, 0),
145
+ 274: ("Orientation", SHORT, 1),
146
+ 277: ("SamplesPerPixel", SHORT, 1),
147
+ 278: ("RowsPerStrip", LONG, 1),
148
+ 279: ("StripByteCounts", LONG, 0),
149
+ 280: ("MinSampleValue", SHORT, 0),
150
+ 281: ("MaxSampleValue", SHORT, 0),
151
+ 282: ("XResolution", RATIONAL, 1),
152
+ 283: ("YResolution", RATIONAL, 1),
153
+ 284: ("PlanarConfiguration", SHORT, 1, {"Contiguous": 1, "Separate": 2}),
154
+ 285: ("PageName", ASCII, 1),
155
+ 286: ("XPosition", RATIONAL, 1),
156
+ 287: ("YPosition", RATIONAL, 1),
157
+ 288: ("FreeOffsets", LONG, 1),
158
+ 289: ("FreeByteCounts", LONG, 1),
159
+ 290: ("GrayResponseUnit", SHORT, 1),
160
+ 291: ("GrayResponseCurve", SHORT, 0),
161
+ 292: ("T4Options", LONG, 1),
162
+ 293: ("T6Options", LONG, 1),
163
+ 296: ("ResolutionUnit", SHORT, 1, {"none": 1, "inch": 2, "cm": 3}),
164
+ 297: ("PageNumber", SHORT, 2),
165
+ 301: ("TransferFunction", SHORT, 0),
166
+ 305: ("Software", ASCII, 1),
167
+ 306: ("DateTime", ASCII, 1),
168
+ 315: ("Artist", ASCII, 1),
169
+ 316: ("HostComputer", ASCII, 1),
170
+ 317: ("Predictor", SHORT, 1, {"none": 1, "Horizontal Differencing": 2}),
171
+ 318: ("WhitePoint", RATIONAL, 2),
172
+ 319: ("PrimaryChromaticities", RATIONAL, 6),
173
+ 320: ("ColorMap", SHORT, 0),
174
+ 321: ("HalftoneHints", SHORT, 2),
175
+ 322: ("TileWidth", LONG, 1),
176
+ 323: ("TileLength", LONG, 1),
177
+ 324: ("TileOffsets", LONG, 0),
178
+ 325: ("TileByteCounts", LONG, 0),
179
+ 330: ("SubIFDs", LONG, 0),
180
+ 332: ("InkSet", SHORT, 1),
181
+ 333: ("InkNames", ASCII, 1),
182
+ 334: ("NumberOfInks", SHORT, 1),
183
+ 336: ("DotRange", SHORT, 0),
184
+ 337: ("TargetPrinter", ASCII, 1),
185
+ 338: ("ExtraSamples", SHORT, 0),
186
+ 339: ("SampleFormat", SHORT, 0),
187
+ 340: ("SMinSampleValue", DOUBLE, 0),
188
+ 341: ("SMaxSampleValue", DOUBLE, 0),
189
+ 342: ("TransferRange", SHORT, 6),
190
+ 347: ("JPEGTables", UNDEFINED, 1),
191
+ # obsolete JPEG tags
192
+ 512: ("JPEGProc", SHORT, 1),
193
+ 513: ("JPEGInterchangeFormat", LONG, 1),
194
+ 514: ("JPEGInterchangeFormatLength", LONG, 1),
195
+ 515: ("JPEGRestartInterval", SHORT, 1),
196
+ 517: ("JPEGLosslessPredictors", SHORT, 0),
197
+ 518: ("JPEGPointTransforms", SHORT, 0),
198
+ 519: ("JPEGQTables", LONG, 0),
199
+ 520: ("JPEGDCTables", LONG, 0),
200
+ 521: ("JPEGACTables", LONG, 0),
201
+ 529: ("YCbCrCoefficients", RATIONAL, 3),
202
+ 530: ("YCbCrSubSampling", SHORT, 2),
203
+ 531: ("YCbCrPositioning", SHORT, 1),
204
+ 532: ("ReferenceBlackWhite", RATIONAL, 6),
205
+ 700: ("XMP", BYTE, 0),
206
+ 33432: ("Copyright", ASCII, 1),
207
+ 33723: ("IptcNaaInfo", UNDEFINED, 1),
208
+ 34377: ("PhotoshopInfo", BYTE, 0),
209
+ # FIXME add more tags here
210
+ 34665: ("ExifIFD", LONG, 1),
211
+ 34675: ("ICCProfile", UNDEFINED, 1),
212
+ 34853: ("GPSInfoIFD", LONG, 1),
213
+ 36864: ("ExifVersion", UNDEFINED, 1),
214
+ 37724: ("ImageSourceData", UNDEFINED, 1),
215
+ 40965: ("InteroperabilityIFD", LONG, 1),
216
+ 41730: ("CFAPattern", UNDEFINED, 1),
217
+ # MPInfo
218
+ 45056: ("MPFVersion", UNDEFINED, 1),
219
+ 45057: ("NumberOfImages", LONG, 1),
220
+ 45058: ("MPEntry", UNDEFINED, 1),
221
+ 45059: ("ImageUIDList", UNDEFINED, 0), # UNDONE, check
222
+ 45060: ("TotalFrames", LONG, 1),
223
+ 45313: ("MPIndividualNum", LONG, 1),
224
+ 45569: ("PanOrientation", LONG, 1),
225
+ 45570: ("PanOverlap_H", RATIONAL, 1),
226
+ 45571: ("PanOverlap_V", RATIONAL, 1),
227
+ 45572: ("BaseViewpointNum", LONG, 1),
228
+ 45573: ("ConvergenceAngle", SIGNED_RATIONAL, 1),
229
+ 45574: ("BaselineLength", RATIONAL, 1),
230
+ 45575: ("VerticalDivergence", SIGNED_RATIONAL, 1),
231
+ 45576: ("AxisDistance_X", SIGNED_RATIONAL, 1),
232
+ 45577: ("AxisDistance_Y", SIGNED_RATIONAL, 1),
233
+ 45578: ("AxisDistance_Z", SIGNED_RATIONAL, 1),
234
+ 45579: ("YawAngle", SIGNED_RATIONAL, 1),
235
+ 45580: ("PitchAngle", SIGNED_RATIONAL, 1),
236
+ 45581: ("RollAngle", SIGNED_RATIONAL, 1),
237
+ 40960: ("FlashPixVersion", UNDEFINED, 1),
238
+ 50741: ("MakerNoteSafety", SHORT, 1, {"Unsafe": 0, "Safe": 1}),
239
+ 50780: ("BestQualityScale", RATIONAL, 1),
240
+ 50838: ("ImageJMetaDataByteCounts", LONG, 0), # Can be more than one
241
+ 50839: ("ImageJMetaData", UNDEFINED, 1), # see Issue #2006
242
+ }
243
+ _tags_v2_groups = {
244
+ # ExifIFD
245
+ 34665: {
246
+ 36864: ("ExifVersion", UNDEFINED, 1),
247
+ 40960: ("FlashPixVersion", UNDEFINED, 1),
248
+ 40965: ("InteroperabilityIFD", LONG, 1),
249
+ 41730: ("CFAPattern", UNDEFINED, 1),
250
+ },
251
+ # GPSInfoIFD
252
+ 34853: {
253
+ 0: ("GPSVersionID", BYTE, 4),
254
+ 1: ("GPSLatitudeRef", ASCII, 2),
255
+ 2: ("GPSLatitude", RATIONAL, 3),
256
+ 3: ("GPSLongitudeRef", ASCII, 2),
257
+ 4: ("GPSLongitude", RATIONAL, 3),
258
+ 5: ("GPSAltitudeRef", BYTE, 1),
259
+ 6: ("GPSAltitude", RATIONAL, 1),
260
+ 7: ("GPSTimeStamp", RATIONAL, 3),
261
+ 8: ("GPSSatellites", ASCII, 0),
262
+ 9: ("GPSStatus", ASCII, 2),
263
+ 10: ("GPSMeasureMode", ASCII, 2),
264
+ 11: ("GPSDOP", RATIONAL, 1),
265
+ 12: ("GPSSpeedRef", ASCII, 2),
266
+ 13: ("GPSSpeed", RATIONAL, 1),
267
+ 14: ("GPSTrackRef", ASCII, 2),
268
+ 15: ("GPSTrack", RATIONAL, 1),
269
+ 16: ("GPSImgDirectionRef", ASCII, 2),
270
+ 17: ("GPSImgDirection", RATIONAL, 1),
271
+ 18: ("GPSMapDatum", ASCII, 0),
272
+ 19: ("GPSDestLatitudeRef", ASCII, 2),
273
+ 20: ("GPSDestLatitude", RATIONAL, 3),
274
+ 21: ("GPSDestLongitudeRef", ASCII, 2),
275
+ 22: ("GPSDestLongitude", RATIONAL, 3),
276
+ 23: ("GPSDestBearingRef", ASCII, 2),
277
+ 24: ("GPSDestBearing", RATIONAL, 1),
278
+ 25: ("GPSDestDistanceRef", ASCII, 2),
279
+ 26: ("GPSDestDistance", RATIONAL, 1),
280
+ 27: ("GPSProcessingMethod", UNDEFINED, 0),
281
+ 28: ("GPSAreaInformation", UNDEFINED, 0),
282
+ 29: ("GPSDateStamp", ASCII, 11),
283
+ 30: ("GPSDifferential", SHORT, 1),
284
+ },
285
+ # InteroperabilityIFD
286
+ 40965: {1: ("InteropIndex", ASCII, 1), 2: ("InteropVersion", UNDEFINED, 1)},
287
+ }
288
+
289
+ # Legacy Tags structure
290
+ # these tags aren't included above, but were in the previous versions
291
+ TAGS: dict[int | tuple[int, int], str] = {
292
+ 347: "JPEGTables",
293
+ 700: "XMP",
294
+ # Additional Exif Info
295
+ 32932: "Wang Annotation",
296
+ 33434: "ExposureTime",
297
+ 33437: "FNumber",
298
+ 33445: "MD FileTag",
299
+ 33446: "MD ScalePixel",
300
+ 33447: "MD ColorTable",
301
+ 33448: "MD LabName",
302
+ 33449: "MD SampleInfo",
303
+ 33450: "MD PrepDate",
304
+ 33451: "MD PrepTime",
305
+ 33452: "MD FileUnits",
306
+ 33550: "ModelPixelScaleTag",
307
+ 33723: "IptcNaaInfo",
308
+ 33918: "INGR Packet Data Tag",
309
+ 33919: "INGR Flag Registers",
310
+ 33920: "IrasB Transformation Matrix",
311
+ 33922: "ModelTiepointTag",
312
+ 34264: "ModelTransformationTag",
313
+ 34377: "PhotoshopInfo",
314
+ 34735: "GeoKeyDirectoryTag",
315
+ 34736: "GeoDoubleParamsTag",
316
+ 34737: "GeoAsciiParamsTag",
317
+ 34850: "ExposureProgram",
318
+ 34852: "SpectralSensitivity",
319
+ 34855: "ISOSpeedRatings",
320
+ 34856: "OECF",
321
+ 34864: "SensitivityType",
322
+ 34865: "StandardOutputSensitivity",
323
+ 34866: "RecommendedExposureIndex",
324
+ 34867: "ISOSpeed",
325
+ 34868: "ISOSpeedLatitudeyyy",
326
+ 34869: "ISOSpeedLatitudezzz",
327
+ 34908: "HylaFAX FaxRecvParams",
328
+ 34909: "HylaFAX FaxSubAddress",
329
+ 34910: "HylaFAX FaxRecvTime",
330
+ 36864: "ExifVersion",
331
+ 36867: "DateTimeOriginal",
332
+ 36868: "DateTimeDigitized",
333
+ 37121: "ComponentsConfiguration",
334
+ 37122: "CompressedBitsPerPixel",
335
+ 37724: "ImageSourceData",
336
+ 37377: "ShutterSpeedValue",
337
+ 37378: "ApertureValue",
338
+ 37379: "BrightnessValue",
339
+ 37380: "ExposureBiasValue",
340
+ 37381: "MaxApertureValue",
341
+ 37382: "SubjectDistance",
342
+ 37383: "MeteringMode",
343
+ 37384: "LightSource",
344
+ 37385: "Flash",
345
+ 37386: "FocalLength",
346
+ 37396: "SubjectArea",
347
+ 37500: "MakerNote",
348
+ 37510: "UserComment",
349
+ 37520: "SubSec",
350
+ 37521: "SubSecTimeOriginal",
351
+ 37522: "SubsecTimeDigitized",
352
+ 40960: "FlashPixVersion",
353
+ 40961: "ColorSpace",
354
+ 40962: "PixelXDimension",
355
+ 40963: "PixelYDimension",
356
+ 40964: "RelatedSoundFile",
357
+ 40965: "InteroperabilityIFD",
358
+ 41483: "FlashEnergy",
359
+ 41484: "SpatialFrequencyResponse",
360
+ 41486: "FocalPlaneXResolution",
361
+ 41487: "FocalPlaneYResolution",
362
+ 41488: "FocalPlaneResolutionUnit",
363
+ 41492: "SubjectLocation",
364
+ 41493: "ExposureIndex",
365
+ 41495: "SensingMethod",
366
+ 41728: "FileSource",
367
+ 41729: "SceneType",
368
+ 41730: "CFAPattern",
369
+ 41985: "CustomRendered",
370
+ 41986: "ExposureMode",
371
+ 41987: "WhiteBalance",
372
+ 41988: "DigitalZoomRatio",
373
+ 41989: "FocalLengthIn35mmFilm",
374
+ 41990: "SceneCaptureType",
375
+ 41991: "GainControl",
376
+ 41992: "Contrast",
377
+ 41993: "Saturation",
378
+ 41994: "Sharpness",
379
+ 41995: "DeviceSettingDescription",
380
+ 41996: "SubjectDistanceRange",
381
+ 42016: "ImageUniqueID",
382
+ 42032: "CameraOwnerName",
383
+ 42033: "BodySerialNumber",
384
+ 42034: "LensSpecification",
385
+ 42035: "LensMake",
386
+ 42036: "LensModel",
387
+ 42037: "LensSerialNumber",
388
+ 42112: "GDAL_METADATA",
389
+ 42113: "GDAL_NODATA",
390
+ 42240: "Gamma",
391
+ 50215: "Oce Scanjob Description",
392
+ 50216: "Oce Application Selector",
393
+ 50217: "Oce Identification Number",
394
+ 50218: "Oce ImageLogic Characteristics",
395
+ # Adobe DNG
396
+ 50706: "DNGVersion",
397
+ 50707: "DNGBackwardVersion",
398
+ 50708: "UniqueCameraModel",
399
+ 50709: "LocalizedCameraModel",
400
+ 50710: "CFAPlaneColor",
401
+ 50711: "CFALayout",
402
+ 50712: "LinearizationTable",
403
+ 50713: "BlackLevelRepeatDim",
404
+ 50714: "BlackLevel",
405
+ 50715: "BlackLevelDeltaH",
406
+ 50716: "BlackLevelDeltaV",
407
+ 50717: "WhiteLevel",
408
+ 50718: "DefaultScale",
409
+ 50719: "DefaultCropOrigin",
410
+ 50720: "DefaultCropSize",
411
+ 50721: "ColorMatrix1",
412
+ 50722: "ColorMatrix2",
413
+ 50723: "CameraCalibration1",
414
+ 50724: "CameraCalibration2",
415
+ 50725: "ReductionMatrix1",
416
+ 50726: "ReductionMatrix2",
417
+ 50727: "AnalogBalance",
418
+ 50728: "AsShotNeutral",
419
+ 50729: "AsShotWhiteXY",
420
+ 50730: "BaselineExposure",
421
+ 50731: "BaselineNoise",
422
+ 50732: "BaselineSharpness",
423
+ 50733: "BayerGreenSplit",
424
+ 50734: "LinearResponseLimit",
425
+ 50735: "CameraSerialNumber",
426
+ 50736: "LensInfo",
427
+ 50737: "ChromaBlurRadius",
428
+ 50738: "AntiAliasStrength",
429
+ 50740: "DNGPrivateData",
430
+ 50778: "CalibrationIlluminant1",
431
+ 50779: "CalibrationIlluminant2",
432
+ 50784: "Alias Layer Metadata",
433
+ }
434
+
435
+ TAGS_V2: dict[int, TagInfo] = {}
436
+ TAGS_V2_GROUPS: dict[int, dict[int, TagInfo]] = {}
437
+
438
+
439
+ def _populate() -> None:
440
+ for k, v in _tags_v2.items():
441
+ # Populate legacy structure.
442
+ TAGS[k] = v[0]
443
+ if len(v) == 4:
444
+ for sk, sv in v[3].items():
445
+ TAGS[(k, sv)] = sk
446
+
447
+ TAGS_V2[k] = TagInfo(k, *v)
448
+
449
+ for group, tags in _tags_v2_groups.items():
450
+ TAGS_V2_GROUPS[group] = {k: TagInfo(k, *v) for k, v in tags.items()}
451
+
452
+
453
+ _populate()
454
+ ##
455
+ # Map type numbers to type names -- defined in ImageFileDirectory.
456
+
457
+ TYPES: dict[int, str] = {}
458
+
459
+ #
460
+ # These tags are handled by default in libtiff, without
461
+ # adding to the custom dictionary. From tif_dir.c, searching for
462
+ # case TIFFTAG in the _TIFFVSetField function:
463
+ # Line: item.
464
+ # 148: case TIFFTAG_SUBFILETYPE:
465
+ # 151: case TIFFTAG_IMAGEWIDTH:
466
+ # 154: case TIFFTAG_IMAGELENGTH:
467
+ # 157: case TIFFTAG_BITSPERSAMPLE:
468
+ # 181: case TIFFTAG_COMPRESSION:
469
+ # 202: case TIFFTAG_PHOTOMETRIC:
470
+ # 205: case TIFFTAG_THRESHHOLDING:
471
+ # 208: case TIFFTAG_FILLORDER:
472
+ # 214: case TIFFTAG_ORIENTATION:
473
+ # 221: case TIFFTAG_SAMPLESPERPIXEL:
474
+ # 228: case TIFFTAG_ROWSPERSTRIP:
475
+ # 238: case TIFFTAG_MINSAMPLEVALUE:
476
+ # 241: case TIFFTAG_MAXSAMPLEVALUE:
477
+ # 244: case TIFFTAG_SMINSAMPLEVALUE:
478
+ # 247: case TIFFTAG_SMAXSAMPLEVALUE:
479
+ # 250: case TIFFTAG_XRESOLUTION:
480
+ # 256: case TIFFTAG_YRESOLUTION:
481
+ # 262: case TIFFTAG_PLANARCONFIG:
482
+ # 268: case TIFFTAG_XPOSITION:
483
+ # 271: case TIFFTAG_YPOSITION:
484
+ # 274: case TIFFTAG_RESOLUTIONUNIT:
485
+ # 280: case TIFFTAG_PAGENUMBER:
486
+ # 284: case TIFFTAG_HALFTONEHINTS:
487
+ # 288: case TIFFTAG_COLORMAP:
488
+ # 294: case TIFFTAG_EXTRASAMPLES:
489
+ # 298: case TIFFTAG_MATTEING:
490
+ # 305: case TIFFTAG_TILEWIDTH:
491
+ # 316: case TIFFTAG_TILELENGTH:
492
+ # 327: case TIFFTAG_TILEDEPTH:
493
+ # 333: case TIFFTAG_DATATYPE:
494
+ # 344: case TIFFTAG_SAMPLEFORMAT:
495
+ # 361: case TIFFTAG_IMAGEDEPTH:
496
+ # 364: case TIFFTAG_SUBIFD:
497
+ # 376: case TIFFTAG_YCBCRPOSITIONING:
498
+ # 379: case TIFFTAG_YCBCRSUBSAMPLING:
499
+ # 383: case TIFFTAG_TRANSFERFUNCTION:
500
+ # 389: case TIFFTAG_REFERENCEBLACKWHITE:
501
+ # 393: case TIFFTAG_INKNAMES:
502
+
503
+ # Following pseudo-tags are also handled by default in libtiff:
504
+ # TIFFTAG_JPEGQUALITY 65537
505
+
506
+ # some of these are not in our TAGS_V2 dict and were included from tiff.h
507
+
508
+ # This list also exists in encode.c
509
+ LIBTIFF_CORE = {
510
+ 255,
511
+ 256,
512
+ 257,
513
+ 258,
514
+ 259,
515
+ 262,
516
+ 263,
517
+ 266,
518
+ 274,
519
+ 277,
520
+ 278,
521
+ 280,
522
+ 281,
523
+ 340,
524
+ 341,
525
+ 282,
526
+ 283,
527
+ 284,
528
+ 286,
529
+ 287,
530
+ 296,
531
+ 297,
532
+ 321,
533
+ 320,
534
+ 338,
535
+ 32995,
536
+ 322,
537
+ 323,
538
+ 32998,
539
+ 32996,
540
+ 339,
541
+ 32997,
542
+ 330,
543
+ 531,
544
+ 530,
545
+ 301,
546
+ 532,
547
+ 333,
548
+ # as above
549
+ 269, # this has been in our tests forever, and works
550
+ 65537,
551
+ }
552
+
553
+ LIBTIFF_CORE.remove(255) # We don't have support for subfiletypes
554
+ LIBTIFF_CORE.remove(322) # We don't have support for writing tiled images with libtiff
555
+ LIBTIFF_CORE.remove(323) # Tiled images
556
+ LIBTIFF_CORE.remove(333) # Ink Names either
557
+
558
+ # Note to advanced users: There may be combinations of these
559
+ # parameters and values that when added properly, will work and
560
+ # produce valid tiff images that may work in your application.
561
+ # It is safe to add and remove tags from this set from Pillow's point
562
+ # of view so long as you test against libtiff.
phi4/lib/python3.10/site-packages/PIL/WalImageFile.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # WAL file handling
6
+ #
7
+ # History:
8
+ # 2003-04-23 fl created
9
+ #
10
+ # Copyright (c) 2003 by Fredrik Lundh.
11
+ #
12
+ # See the README file for information on usage and redistribution.
13
+ #
14
+
15
+ """
16
+ This reader is based on the specification available from:
17
+ https://www.flipcode.com/archives/Quake_2_BSP_File_Format.shtml
18
+ and has been tested with a few sample files found using google.
19
+
20
+ .. note::
21
+ This format cannot be automatically recognized, so the reader
22
+ is not registered for use with :py:func:`PIL.Image.open()`.
23
+ To open a WAL file, use the :py:func:`PIL.WalImageFile.open()` function instead.
24
+ """
25
+ from __future__ import annotations
26
+
27
+ from typing import IO
28
+
29
+ from . import Image, ImageFile
30
+ from ._binary import i32le as i32
31
+ from ._typing import StrOrBytesPath
32
+
33
+
34
+ class WalImageFile(ImageFile.ImageFile):
35
+ format = "WAL"
36
+ format_description = "Quake2 Texture"
37
+
38
+ def _open(self) -> None:
39
+ self._mode = "P"
40
+
41
+ # read header fields
42
+ header = self.fp.read(32 + 24 + 32 + 12)
43
+ self._size = i32(header, 32), i32(header, 36)
44
+ Image._decompression_bomb_check(self.size)
45
+
46
+ # load pixel data
47
+ offset = i32(header, 40)
48
+ self.fp.seek(offset)
49
+
50
+ # strings are null-terminated
51
+ self.info["name"] = header[:32].split(b"\0", 1)[0]
52
+ next_name = header[56 : 56 + 32].split(b"\0", 1)[0]
53
+ if next_name:
54
+ self.info["next_name"] = next_name
55
+
56
+ def load(self) -> Image.core.PixelAccess | None:
57
+ if self._im is None:
58
+ self.im = Image.core.new(self.mode, self.size)
59
+ self.frombytes(self.fp.read(self.size[0] * self.size[1]))
60
+ self.putpalette(quake2palette)
61
+ return Image.Image.load(self)
62
+
63
+
64
+ def open(filename: StrOrBytesPath | IO[bytes]) -> WalImageFile:
65
+ """
66
+ Load texture from a Quake2 WAL texture file.
67
+
68
+ By default, a Quake2 standard palette is attached to the texture.
69
+ To override the palette, use the :py:func:`PIL.Image.Image.putpalette()` method.
70
+
71
+ :param filename: WAL file name, or an opened file handle.
72
+ :returns: An image instance.
73
+ """
74
+ return WalImageFile(filename)
75
+
76
+
77
+ quake2palette = (
78
+ # default palette taken from piffo 0.93 by Hans Häggström
79
+ b"\x01\x01\x01\x0b\x0b\x0b\x12\x12\x12\x17\x17\x17\x1b\x1b\x1b\x1e"
80
+ b"\x1e\x1e\x22\x22\x22\x26\x26\x26\x29\x29\x29\x2c\x2c\x2c\x2f\x2f"
81
+ b"\x2f\x32\x32\x32\x35\x35\x35\x37\x37\x37\x3a\x3a\x3a\x3c\x3c\x3c"
82
+ b"\x24\x1e\x13\x22\x1c\x12\x20\x1b\x12\x1f\x1a\x10\x1d\x19\x10\x1b"
83
+ b"\x17\x0f\x1a\x16\x0f\x18\x14\x0d\x17\x13\x0d\x16\x12\x0d\x14\x10"
84
+ b"\x0b\x13\x0f\x0b\x10\x0d\x0a\x0f\x0b\x0a\x0d\x0b\x07\x0b\x0a\x07"
85
+ b"\x23\x23\x26\x22\x22\x25\x22\x20\x23\x21\x1f\x22\x20\x1e\x20\x1f"
86
+ b"\x1d\x1e\x1d\x1b\x1c\x1b\x1a\x1a\x1a\x19\x19\x18\x17\x17\x17\x16"
87
+ b"\x16\x14\x14\x14\x13\x13\x13\x10\x10\x10\x0f\x0f\x0f\x0d\x0d\x0d"
88
+ b"\x2d\x28\x20\x29\x24\x1c\x27\x22\x1a\x25\x1f\x17\x38\x2e\x1e\x31"
89
+ b"\x29\x1a\x2c\x25\x17\x26\x20\x14\x3c\x30\x14\x37\x2c\x13\x33\x28"
90
+ b"\x12\x2d\x24\x10\x28\x1f\x0f\x22\x1a\x0b\x1b\x14\x0a\x13\x0f\x07"
91
+ b"\x31\x1a\x16\x30\x17\x13\x2e\x16\x10\x2c\x14\x0d\x2a\x12\x0b\x27"
92
+ b"\x0f\x0a\x25\x0f\x07\x21\x0d\x01\x1e\x0b\x01\x1c\x0b\x01\x1a\x0b"
93
+ b"\x01\x18\x0a\x01\x16\x0a\x01\x13\x0a\x01\x10\x07\x01\x0d\x07\x01"
94
+ b"\x29\x23\x1e\x27\x21\x1c\x26\x20\x1b\x25\x1f\x1a\x23\x1d\x19\x21"
95
+ b"\x1c\x18\x20\x1b\x17\x1e\x19\x16\x1c\x18\x14\x1b\x17\x13\x19\x14"
96
+ b"\x10\x17\x13\x0f\x14\x10\x0d\x12\x0f\x0b\x0f\x0b\x0a\x0b\x0a\x07"
97
+ b"\x26\x1a\x0f\x23\x19\x0f\x20\x17\x0f\x1c\x16\x0f\x19\x13\x0d\x14"
98
+ b"\x10\x0b\x10\x0d\x0a\x0b\x0a\x07\x33\x22\x1f\x35\x29\x26\x37\x2f"
99
+ b"\x2d\x39\x35\x34\x37\x39\x3a\x33\x37\x39\x30\x34\x36\x2b\x31\x34"
100
+ b"\x27\x2e\x31\x22\x2b\x2f\x1d\x28\x2c\x17\x25\x2a\x0f\x20\x26\x0d"
101
+ b"\x1e\x25\x0b\x1c\x22\x0a\x1b\x20\x07\x19\x1e\x07\x17\x1b\x07\x14"
102
+ b"\x18\x01\x12\x16\x01\x0f\x12\x01\x0b\x0d\x01\x07\x0a\x01\x01\x01"
103
+ b"\x2c\x21\x21\x2a\x1f\x1f\x29\x1d\x1d\x27\x1c\x1c\x26\x1a\x1a\x24"
104
+ b"\x18\x18\x22\x17\x17\x21\x16\x16\x1e\x13\x13\x1b\x12\x12\x18\x10"
105
+ b"\x10\x16\x0d\x0d\x12\x0b\x0b\x0d\x0a\x0a\x0a\x07\x07\x01\x01\x01"
106
+ b"\x2e\x30\x29\x2d\x2e\x27\x2b\x2c\x26\x2a\x2a\x24\x28\x29\x23\x27"
107
+ b"\x27\x21\x26\x26\x1f\x24\x24\x1d\x22\x22\x1c\x1f\x1f\x1a\x1c\x1c"
108
+ b"\x18\x19\x19\x16\x17\x17\x13\x13\x13\x10\x0f\x0f\x0d\x0b\x0b\x0a"
109
+ b"\x30\x1e\x1b\x2d\x1c\x19\x2c\x1a\x17\x2a\x19\x14\x28\x17\x13\x26"
110
+ b"\x16\x10\x24\x13\x0f\x21\x12\x0d\x1f\x10\x0b\x1c\x0f\x0a\x19\x0d"
111
+ b"\x0a\x16\x0b\x07\x12\x0a\x07\x0f\x07\x01\x0a\x01\x01\x01\x01\x01"
112
+ b"\x28\x29\x38\x26\x27\x36\x25\x26\x34\x24\x24\x31\x22\x22\x2f\x20"
113
+ b"\x21\x2d\x1e\x1f\x2a\x1d\x1d\x27\x1b\x1b\x25\x19\x19\x21\x17\x17"
114
+ b"\x1e\x14\x14\x1b\x13\x12\x17\x10\x0f\x13\x0d\x0b\x0f\x0a\x07\x07"
115
+ b"\x2f\x32\x29\x2d\x30\x26\x2b\x2e\x24\x29\x2c\x21\x27\x2a\x1e\x25"
116
+ b"\x28\x1c\x23\x26\x1a\x21\x25\x18\x1e\x22\x14\x1b\x1f\x10\x19\x1c"
117
+ b"\x0d\x17\x1a\x0a\x13\x17\x07\x10\x13\x01\x0d\x0f\x01\x0a\x0b\x01"
118
+ b"\x01\x3f\x01\x13\x3c\x0b\x1b\x39\x10\x20\x35\x14\x23\x31\x17\x23"
119
+ b"\x2d\x18\x23\x29\x18\x3f\x3f\x3f\x3f\x3f\x39\x3f\x3f\x31\x3f\x3f"
120
+ b"\x2a\x3f\x3f\x20\x3f\x3f\x14\x3f\x3c\x12\x3f\x39\x0f\x3f\x35\x0b"
121
+ b"\x3f\x32\x07\x3f\x2d\x01\x3d\x2a\x01\x3b\x26\x01\x39\x21\x01\x37"
122
+ b"\x1d\x01\x34\x1a\x01\x32\x16\x01\x2f\x12\x01\x2d\x0f\x01\x2a\x0b"
123
+ b"\x01\x27\x07\x01\x23\x01\x01\x1d\x01\x01\x17\x01\x01\x10\x01\x01"
124
+ b"\x3d\x01\x01\x19\x19\x3f\x3f\x01\x01\x01\x01\x3f\x16\x16\x13\x10"
125
+ b"\x10\x0f\x0d\x0d\x0b\x3c\x2e\x2a\x36\x27\x20\x30\x21\x18\x29\x1b"
126
+ b"\x10\x3c\x39\x37\x37\x32\x2f\x31\x2c\x28\x2b\x26\x21\x30\x22\x20"
127
+ )
phi4/lib/python3.10/site-packages/PIL/_binary.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # Binary input/output support routines.
6
+ #
7
+ # Copyright (c) 1997-2003 by Secret Labs AB
8
+ # Copyright (c) 1995-2003 by Fredrik Lundh
9
+ # Copyright (c) 2012 by Brian Crowell
10
+ #
11
+ # See the README file for information on usage and redistribution.
12
+ #
13
+
14
+
15
+ """Binary input/output support routines."""
16
+ from __future__ import annotations
17
+
18
+ from struct import pack, unpack_from
19
+
20
+
21
+ def i8(c: bytes) -> int:
22
+ return c[0]
23
+
24
+
25
+ def o8(i: int) -> bytes:
26
+ return bytes((i & 255,))
27
+
28
+
29
+ # Input, le = little endian, be = big endian
30
+ def i16le(c: bytes, o: int = 0) -> int:
31
+ """
32
+ Converts a 2-bytes (16 bits) string to an unsigned integer.
33
+
34
+ :param c: string containing bytes to convert
35
+ :param o: offset of bytes to convert in string
36
+ """
37
+ return unpack_from("<H", c, o)[0]
38
+
39
+
40
+ def si16le(c: bytes, o: int = 0) -> int:
41
+ """
42
+ Converts a 2-bytes (16 bits) string to a signed integer.
43
+
44
+ :param c: string containing bytes to convert
45
+ :param o: offset of bytes to convert in string
46
+ """
47
+ return unpack_from("<h", c, o)[0]
48
+
49
+
50
+ def si16be(c: bytes, o: int = 0) -> int:
51
+ """
52
+ Converts a 2-bytes (16 bits) string to a signed integer, big endian.
53
+
54
+ :param c: string containing bytes to convert
55
+ :param o: offset of bytes to convert in string
56
+ """
57
+ return unpack_from(">h", c, o)[0]
58
+
59
+
60
+ def i32le(c: bytes, o: int = 0) -> int:
61
+ """
62
+ Converts a 4-bytes (32 bits) string to an unsigned integer.
63
+
64
+ :param c: string containing bytes to convert
65
+ :param o: offset of bytes to convert in string
66
+ """
67
+ return unpack_from("<I", c, o)[0]
68
+
69
+
70
+ def si32le(c: bytes, o: int = 0) -> int:
71
+ """
72
+ Converts a 4-bytes (32 bits) string to a signed integer.
73
+
74
+ :param c: string containing bytes to convert
75
+ :param o: offset of bytes to convert in string
76
+ """
77
+ return unpack_from("<i", c, o)[0]
78
+
79
+
80
+ def si32be(c: bytes, o: int = 0) -> int:
81
+ """
82
+ Converts a 4-bytes (32 bits) string to a signed integer, big endian.
83
+
84
+ :param c: string containing bytes to convert
85
+ :param o: offset of bytes to convert in string
86
+ """
87
+ return unpack_from(">i", c, o)[0]
88
+
89
+
90
+ def i16be(c: bytes, o: int = 0) -> int:
91
+ return unpack_from(">H", c, o)[0]
92
+
93
+
94
+ def i32be(c: bytes, o: int = 0) -> int:
95
+ return unpack_from(">I", c, o)[0]
96
+
97
+
98
+ # Output, le = little endian, be = big endian
99
+ def o16le(i: int) -> bytes:
100
+ return pack("<H", i)
101
+
102
+
103
+ def o32le(i: int) -> bytes:
104
+ return pack("<I", i)
105
+
106
+
107
+ def o16be(i: int) -> bytes:
108
+ return pack(">H", i)
109
+
110
+
111
+ def o32be(i: int) -> bytes:
112
+ return pack(">I", i)
phi4/lib/python3.10/site-packages/PIL/_imaging.pyi ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any
2
+
3
+ class ImagingCore:
4
+ def __getitem__(self, index: int) -> float: ...
5
+ def __getattr__(self, name: str) -> Any: ...
6
+
7
+ class ImagingFont:
8
+ def __getattr__(self, name: str) -> Any: ...
9
+
10
+ class ImagingDraw:
11
+ def __getattr__(self, name: str) -> Any: ...
12
+
13
+ class PixelAccess:
14
+ def __getitem__(self, xy: tuple[int, int]) -> float | tuple[int, ...]: ...
15
+ def __setitem__(
16
+ self, xy: tuple[int, int], color: float | tuple[int, ...]
17
+ ) -> None: ...
18
+
19
+ class ImagingDecoder:
20
+ def __getattr__(self, name: str) -> Any: ...
21
+
22
+ class ImagingEncoder:
23
+ def __getattr__(self, name: str) -> Any: ...
24
+
25
+ class _Outline:
26
+ def close(self) -> None: ...
27
+ def __getattr__(self, name: str) -> Any: ...
28
+
29
+ def font(image: ImagingCore, glyphdata: bytes) -> ImagingFont: ...
30
+ def outline() -> _Outline: ...
31
+ def __getattr__(name: str) -> Any: ...
phi4/lib/python3.10/site-packages/PIL/_imagingft.pyi ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Callable
2
+
3
+ from . import ImageFont, _imaging
4
+
5
+ class Font:
6
+ @property
7
+ def family(self) -> str | None: ...
8
+ @property
9
+ def style(self) -> str | None: ...
10
+ @property
11
+ def ascent(self) -> int: ...
12
+ @property
13
+ def descent(self) -> int: ...
14
+ @property
15
+ def height(self) -> int: ...
16
+ @property
17
+ def x_ppem(self) -> int: ...
18
+ @property
19
+ def y_ppem(self) -> int: ...
20
+ @property
21
+ def glyphs(self) -> int: ...
22
+ def render(
23
+ self,
24
+ string: str | bytes,
25
+ fill: Callable[[int, int], _imaging.ImagingCore],
26
+ mode: str,
27
+ dir: str | None,
28
+ features: list[str] | None,
29
+ lang: str | None,
30
+ stroke_width: float,
31
+ anchor: str | None,
32
+ foreground_ink_long: int,
33
+ x_start: float,
34
+ y_start: float,
35
+ /,
36
+ ) -> tuple[_imaging.ImagingCore, tuple[int, int]]: ...
37
+ def getsize(
38
+ self,
39
+ string: str | bytes | bytearray,
40
+ mode: str,
41
+ dir: str | None,
42
+ features: list[str] | None,
43
+ lang: str | None,
44
+ anchor: str | None,
45
+ /,
46
+ ) -> tuple[tuple[int, int], tuple[int, int]]: ...
47
+ def getlength(
48
+ self,
49
+ string: str | bytes,
50
+ mode: str,
51
+ dir: str | None,
52
+ features: list[str] | None,
53
+ lang: str | None,
54
+ /,
55
+ ) -> float: ...
56
+ def getvarnames(self) -> list[bytes]: ...
57
+ def getvaraxes(self) -> list[ImageFont.Axis]: ...
58
+ def setvarname(self, instance_index: int, /) -> None: ...
59
+ def setvaraxes(self, axes: list[float], /) -> None: ...
60
+
61
+ def getfont(
62
+ filename: str | bytes,
63
+ size: float,
64
+ index: int,
65
+ encoding: str,
66
+ font_bytes: bytes,
67
+ layout_engine: int,
68
+ ) -> Font: ...
69
+ def __getattr__(name: str) -> Any: ...
phi4/lib/python3.10/site-packages/flash_attn/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (486 Bytes). View file
 
phi4/lib/python3.10/site-packages/flash_attn/__pycache__/bert_padding.cpython-310.pyc ADDED
Binary file (7.23 kB). View file
 
phi4/lib/python3.10/site-packages/flash_attn/__pycache__/flash_attn_interface.cpython-310.pyc ADDED
Binary file (44.6 kB). View file
 
phi4/lib/python3.10/site-packages/flash_attn/__pycache__/flash_attn_triton.cpython-310.pyc ADDED
Binary file (21 kB). View file
 
phi4/lib/python3.10/site-packages/flash_attn/__pycache__/flash_attn_triton_og.cpython-310.pyc ADDED
Binary file (6.7 kB). View file
 
phi4/lib/python3.10/site-packages/flash_attn/__pycache__/flash_blocksparse_attention.cpython-310.pyc ADDED
Binary file (5.01 kB). View file
 
phi4/lib/python3.10/site-packages/flash_attn/__pycache__/flash_blocksparse_attn_interface.cpython-310.pyc ADDED
Binary file (4.52 kB). View file
 
phi4/lib/python3.10/site-packages/flash_attn/__pycache__/fused_softmax.cpython-310.pyc ADDED
Binary file (5.75 kB). View file
 
phi4/lib/python3.10/site-packages/flash_attn/losses/__init__.py ADDED
File without changes
phi4/lib/python3.10/site-packages/flash_attn/losses/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (167 Bytes). View file
 
phi4/lib/python3.10/site-packages/flash_attn/losses/__pycache__/cross_entropy.cpython-310.pyc ADDED
Binary file (2.78 kB). View file
 
phi4/lib/python3.10/site-packages/flash_attn/losses/cross_entropy.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2024, Tri Dao.
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+
6
+ from flash_attn.ops.triton.cross_entropy import cross_entropy_loss
7
+
8
+
9
+ class CrossEntropyLoss(nn.Module):
10
+ def __init__(
11
+ self,
12
+ ignore_index=-100,
13
+ reduction="mean",
14
+ label_smoothing=0.0,
15
+ logit_scale=1.0,
16
+ lse_square_scale=0.0,
17
+ inplace_backward=False,
18
+ process_group=None,
19
+ return_z_loss=False,
20
+ ):
21
+ """
22
+ Arguments:
23
+ ignore_index: int. If labels == ignore_index, the loss is set to 0.0.
24
+ label_smoothing: float
25
+ lse_square_scale: float. If > 0, we add lse_square_scale * lse(logits) ^ 2 to the loss.
26
+ This is also referred to as "z-loss".
27
+ inplace_backward: bool. If True, we do the backward pass in-place by modifying the logits.
28
+ This saves memory.
29
+ process_group: if not None, we're doing Tensor Parallel: each process is responsible for
30
+ one part of the vocab. The loss will be aggregated across processes.
31
+ return_z_loss: bool. If True, we return the component of the loss contributed by
32
+ the lse_square_scale value. This value is only for logging and does not support
33
+ backprop.
34
+ """
35
+ super().__init__()
36
+ if reduction not in ["mean", "none", "sum"]:
37
+ raise NotImplementedError("Only support reduction = 'mean' or 'none' or 'sum'")
38
+ self.ignore_index = ignore_index
39
+ self.reduction = reduction
40
+ self.label_smoothing = label_smoothing
41
+ self.logit_scale = logit_scale
42
+ self.lse_square_scale = lse_square_scale
43
+ self.inplace_backward = inplace_backward
44
+ self.process_group = process_group
45
+ self.return_z_loss = return_z_loss
46
+
47
+ def forward(self, input, target, precomputed_lse=None):
48
+ """
49
+ Arguments:
50
+ input: (batch, vocab_size)
51
+ target: (batch,)
52
+ Returns:
53
+ losses: (batch,) if reduction is 'none', else (1,), dtype float
54
+ z_loss: (batch,) if reduction is 'none', else (1,), dtype float (if self.return_z_loss)
55
+ """
56
+ assert input.is_cuda and target.is_cuda, "Only support CUDA tensors"
57
+ loss, z_loss = cross_entropy_loss(
58
+ input,
59
+ target,
60
+ precomputed_lse=precomputed_lse,
61
+ label_smoothing=self.label_smoothing,
62
+ logit_scale=self.logit_scale,
63
+ lse_square_scale=self.lse_square_scale,
64
+ ignore_index=self.ignore_index,
65
+ inplace_backward=self.inplace_backward,
66
+ process_group=self.process_group,
67
+ )
68
+ if self.reduction == "mean":
69
+ loss = loss.sum() / (target != self.ignore_index).sum()
70
+ elif self.reduction == "sum":
71
+ loss = loss.sum()
72
+ else:
73
+ loss = loss
74
+
75
+ if not self.return_z_loss:
76
+ return loss
77
+
78
+ if self.reduction == "mean":
79
+ z_loss = z_loss.sum() / (target != self.ignore_index).sum()
80
+ elif self.reduction == "sum":
81
+ z_loss = z_loss.sum()
82
+ else:
83
+ z_loss = z_loss
84
+
85
+ return loss, z_loss
phi4/lib/python3.10/site-packages/flash_attn/models/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (167 Bytes). View file
 
phi4/lib/python3.10/site-packages/flash_attn/models/__pycache__/baichuan.cpython-310.pyc ADDED
Binary file (4.56 kB). View file
 
phi4/lib/python3.10/site-packages/flash_attn/models/__pycache__/bert.cpython-310.pyc ADDED
Binary file (22.6 kB). View file
 
phi4/lib/python3.10/site-packages/flash_attn/models/__pycache__/bigcode.cpython-310.pyc ADDED
Binary file (7.09 kB). View file
 
phi4/lib/python3.10/site-packages/flash_attn/models/__pycache__/btlm.cpython-310.pyc ADDED
Binary file (4.51 kB). View file
 
phi4/lib/python3.10/site-packages/flash_attn/models/__pycache__/falcon.cpython-310.pyc ADDED
Binary file (4.78 kB). View file
 
phi4/lib/python3.10/site-packages/flash_attn/models/__pycache__/gpt.cpython-310.pyc ADDED
Binary file (29.3 kB). View file
 
phi4/lib/python3.10/site-packages/flash_attn/models/__pycache__/gpt_neox.cpython-310.pyc ADDED
Binary file (4.53 kB). View file
 
phi4/lib/python3.10/site-packages/flash_attn/models/__pycache__/gptj.cpython-310.pyc ADDED
Binary file (4.01 kB). View file
 
phi4/lib/python3.10/site-packages/flash_attn/models/__pycache__/llama.cpython-310.pyc ADDED
Binary file (12.1 kB). View file