jonghanko commited on
Commit
fbabff9
·
verified ·
1 Parent(s): 6881eaa

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. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/AvifImagePlugin.py +291 -0
  2. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/BdfFontFile.py +122 -0
  3. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/BlpImagePlugin.py +497 -0
  4. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/BmpImagePlugin.py +515 -0
  5. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/BufrStubImagePlugin.py +75 -0
  6. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/ContainerIO.py +173 -0
  7. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/CurImagePlugin.py +75 -0
  8. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/DcxImagePlugin.py +83 -0
  9. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/DdsImagePlugin.py +624 -0
  10. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/EpsImagePlugin.py +476 -0
  11. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/ExifTags.py +382 -0
  12. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/FitsImagePlugin.py +152 -0
  13. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/FliImagePlugin.py +178 -0
  14. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/FontFile.py +134 -0
  15. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/FpxImagePlugin.py +257 -0
  16. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/FtexImagePlugin.py +114 -0
  17. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/GbrImagePlugin.py +103 -0
  18. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/GdImageFile.py +102 -0
  19. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/GifImagePlugin.py +1213 -0
  20. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/GimpGradientFile.py +149 -0
  21. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/GimpPaletteFile.py +72 -0
  22. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/GribStubImagePlugin.py +75 -0
  23. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/Hdf5StubImagePlugin.py +75 -0
  24. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/IcnsImagePlugin.py +411 -0
  25. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/IcoImagePlugin.py +381 -0
  26. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/ImImagePlugin.py +389 -0
  27. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/Image.py +0 -0
  28. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/ImageChops.py +311 -0
  29. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/ImageCms.py +1123 -0
  30. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/ImageColor.py +320 -0
  31. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/ImageDraw.py +1232 -0
  32. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/ImageDraw2.py +243 -0
  33. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/ImageEnhance.py +113 -0
  34. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/ImageFile.py +922 -0
  35. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/ImageFilter.py +604 -0
  36. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/ImageFont.py +1339 -0
  37. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/ImageGrab.py +196 -0
  38. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/ImageMath.py +368 -0
  39. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/ImageMode.py +92 -0
  40. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/ImageMorph.py +265 -0
  41. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/ImageOps.py +745 -0
  42. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/ImagePalette.py +286 -0
  43. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/ImagePath.py +20 -0
  44. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/ImageQt.py +220 -0
  45. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/ImageSequence.py +86 -0
  46. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/ImageShow.py +362 -0
  47. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/ImageStat.py +160 -0
  48. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/ImageTk.py +266 -0
  49. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/ImageTransform.py +136 -0
  50. Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/ImageWin.py +247 -0
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/AvifImagePlugin.py ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ from io import BytesIO
5
+ from typing import IO
6
+
7
+ from . import ExifTags, Image, ImageFile
8
+
9
+ try:
10
+ from . import _avif
11
+
12
+ SUPPORTED = True
13
+ except ImportError:
14
+ SUPPORTED = False
15
+
16
+ # Decoder options as module globals, until there is a way to pass parameters
17
+ # to Image.open (see https://github.com/python-pillow/Pillow/issues/569)
18
+ DECODE_CODEC_CHOICE = "auto"
19
+ DEFAULT_MAX_THREADS = 0
20
+
21
+
22
+ def get_codec_version(codec_name: str) -> str | None:
23
+ versions = _avif.codec_versions()
24
+ for version in versions.split(", "):
25
+ if version.split(" [")[0] == codec_name:
26
+ return version.split(":")[-1].split(" ")[0]
27
+ return None
28
+
29
+
30
+ def _accept(prefix: bytes) -> bool | str:
31
+ if prefix[4:8] != b"ftyp":
32
+ return False
33
+ major_brand = prefix[8:12]
34
+ if major_brand in (
35
+ # coding brands
36
+ b"avif",
37
+ b"avis",
38
+ # We accept files with AVIF container brands; we can't yet know if
39
+ # the ftyp box has the correct compatible brands, but if it doesn't
40
+ # then the plugin will raise a SyntaxError which Pillow will catch
41
+ # before moving on to the next plugin that accepts the file.
42
+ #
43
+ # Also, because this file might not actually be an AVIF file, we
44
+ # don't raise an error if AVIF support isn't properly compiled.
45
+ b"mif1",
46
+ b"msf1",
47
+ ):
48
+ if not SUPPORTED:
49
+ return (
50
+ "image file could not be identified because AVIF support not installed"
51
+ )
52
+ return True
53
+ return False
54
+
55
+
56
+ def _get_default_max_threads() -> int:
57
+ if DEFAULT_MAX_THREADS:
58
+ return DEFAULT_MAX_THREADS
59
+ if hasattr(os, "sched_getaffinity"):
60
+ return len(os.sched_getaffinity(0))
61
+ else:
62
+ return os.cpu_count() or 1
63
+
64
+
65
+ class AvifImageFile(ImageFile.ImageFile):
66
+ format = "AVIF"
67
+ format_description = "AVIF image"
68
+ __frame = -1
69
+
70
+ def _open(self) -> None:
71
+ if not SUPPORTED:
72
+ msg = "image file could not be opened because AVIF support not installed"
73
+ raise SyntaxError(msg)
74
+
75
+ if DECODE_CODEC_CHOICE != "auto" and not _avif.decoder_codec_available(
76
+ DECODE_CODEC_CHOICE
77
+ ):
78
+ msg = "Invalid opening codec"
79
+ raise ValueError(msg)
80
+ self._decoder = _avif.AvifDecoder(
81
+ self.fp.read(),
82
+ DECODE_CODEC_CHOICE,
83
+ _get_default_max_threads(),
84
+ )
85
+
86
+ # Get info from decoder
87
+ self._size, self.n_frames, self._mode, icc, exif, exif_orientation, xmp = (
88
+ self._decoder.get_info()
89
+ )
90
+ self.is_animated = self.n_frames > 1
91
+
92
+ if icc:
93
+ self.info["icc_profile"] = icc
94
+ if xmp:
95
+ self.info["xmp"] = xmp
96
+
97
+ if exif_orientation != 1 or exif:
98
+ exif_data = Image.Exif()
99
+ if exif:
100
+ exif_data.load(exif)
101
+ original_orientation = exif_data.get(ExifTags.Base.Orientation, 1)
102
+ else:
103
+ original_orientation = 1
104
+ if exif_orientation != original_orientation:
105
+ exif_data[ExifTags.Base.Orientation] = exif_orientation
106
+ exif = exif_data.tobytes()
107
+ if exif:
108
+ self.info["exif"] = exif
109
+ self.seek(0)
110
+
111
+ def seek(self, frame: int) -> None:
112
+ if not self._seek_check(frame):
113
+ return
114
+
115
+ # Set tile
116
+ self.__frame = frame
117
+ self.tile = [ImageFile._Tile("raw", (0, 0) + self.size, 0, self.mode)]
118
+
119
+ def load(self) -> Image.core.PixelAccess | None:
120
+ if self.tile:
121
+ # We need to load the image data for this frame
122
+ data, timescale, pts_in_timescales, duration_in_timescales = (
123
+ self._decoder.get_frame(self.__frame)
124
+ )
125
+ self.info["timestamp"] = round(1000 * (pts_in_timescales / timescale))
126
+ self.info["duration"] = round(1000 * (duration_in_timescales / timescale))
127
+
128
+ if self.fp and self._exclusive_fp:
129
+ self.fp.close()
130
+ self.fp = BytesIO(data)
131
+
132
+ return super().load()
133
+
134
+ def load_seek(self, pos: int) -> None:
135
+ pass
136
+
137
+ def tell(self) -> int:
138
+ return self.__frame
139
+
140
+
141
+ def _save_all(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
142
+ _save(im, fp, filename, save_all=True)
143
+
144
+
145
+ def _save(
146
+ im: Image.Image, fp: IO[bytes], filename: str | bytes, save_all: bool = False
147
+ ) -> None:
148
+ info = im.encoderinfo.copy()
149
+ if save_all:
150
+ append_images = list(info.get("append_images", []))
151
+ else:
152
+ append_images = []
153
+
154
+ total = 0
155
+ for ims in [im] + append_images:
156
+ total += getattr(ims, "n_frames", 1)
157
+
158
+ quality = info.get("quality", 75)
159
+ if not isinstance(quality, int) or quality < 0 or quality > 100:
160
+ msg = "Invalid quality setting"
161
+ raise ValueError(msg)
162
+
163
+ duration = info.get("duration", 0)
164
+ subsampling = info.get("subsampling", "4:2:0")
165
+ speed = info.get("speed", 6)
166
+ max_threads = info.get("max_threads", _get_default_max_threads())
167
+ codec = info.get("codec", "auto")
168
+ if codec != "auto" and not _avif.encoder_codec_available(codec):
169
+ msg = "Invalid saving codec"
170
+ raise ValueError(msg)
171
+ range_ = info.get("range", "full")
172
+ tile_rows_log2 = info.get("tile_rows", 0)
173
+ tile_cols_log2 = info.get("tile_cols", 0)
174
+ alpha_premultiplied = bool(info.get("alpha_premultiplied", False))
175
+ autotiling = bool(info.get("autotiling", tile_rows_log2 == tile_cols_log2 == 0))
176
+
177
+ icc_profile = info.get("icc_profile", im.info.get("icc_profile"))
178
+ exif_orientation = 1
179
+ if exif := info.get("exif"):
180
+ if isinstance(exif, Image.Exif):
181
+ exif_data = exif
182
+ else:
183
+ exif_data = Image.Exif()
184
+ exif_data.load(exif)
185
+ if ExifTags.Base.Orientation in exif_data:
186
+ exif_orientation = exif_data.pop(ExifTags.Base.Orientation)
187
+ exif = exif_data.tobytes() if exif_data else b""
188
+ elif isinstance(exif, Image.Exif):
189
+ exif = exif_data.tobytes()
190
+
191
+ xmp = info.get("xmp")
192
+
193
+ if isinstance(xmp, str):
194
+ xmp = xmp.encode("utf-8")
195
+
196
+ advanced = info.get("advanced")
197
+ if advanced is not None:
198
+ if isinstance(advanced, dict):
199
+ advanced = advanced.items()
200
+ try:
201
+ advanced = tuple(advanced)
202
+ except TypeError:
203
+ invalid = True
204
+ else:
205
+ invalid = any(not isinstance(v, tuple) or len(v) != 2 for v in advanced)
206
+ if invalid:
207
+ msg = (
208
+ "advanced codec options must be a dict of key-value string "
209
+ "pairs or a series of key-value two-tuples"
210
+ )
211
+ raise ValueError(msg)
212
+
213
+ # Setup the AVIF encoder
214
+ enc = _avif.AvifEncoder(
215
+ im.size,
216
+ subsampling,
217
+ quality,
218
+ speed,
219
+ max_threads,
220
+ codec,
221
+ range_,
222
+ tile_rows_log2,
223
+ tile_cols_log2,
224
+ alpha_premultiplied,
225
+ autotiling,
226
+ icc_profile or b"",
227
+ exif or b"",
228
+ exif_orientation,
229
+ xmp or b"",
230
+ advanced,
231
+ )
232
+
233
+ # Add each frame
234
+ frame_idx = 0
235
+ frame_duration = 0
236
+ cur_idx = im.tell()
237
+ is_single_frame = total == 1
238
+ try:
239
+ for ims in [im] + append_images:
240
+ # Get number of frames in this image
241
+ nfr = getattr(ims, "n_frames", 1)
242
+
243
+ for idx in range(nfr):
244
+ ims.seek(idx)
245
+
246
+ # Make sure image mode is supported
247
+ frame = ims
248
+ rawmode = ims.mode
249
+ if ims.mode not in {"RGB", "RGBA"}:
250
+ rawmode = "RGBA" if ims.has_transparency_data else "RGB"
251
+ frame = ims.convert(rawmode)
252
+
253
+ # Update frame duration
254
+ if isinstance(duration, (list, tuple)):
255
+ frame_duration = duration[frame_idx]
256
+ else:
257
+ frame_duration = duration
258
+
259
+ # Append the frame to the animation encoder
260
+ enc.add(
261
+ frame.tobytes("raw", rawmode),
262
+ frame_duration,
263
+ frame.size,
264
+ rawmode,
265
+ is_single_frame,
266
+ )
267
+
268
+ # Update frame index
269
+ frame_idx += 1
270
+
271
+ if not save_all:
272
+ break
273
+
274
+ finally:
275
+ im.seek(cur_idx)
276
+
277
+ # Get the final output from the encoder
278
+ data = enc.finish()
279
+ if data is None:
280
+ msg = "cannot write file as AVIF (encoder returned None)"
281
+ raise OSError(msg)
282
+
283
+ fp.write(data)
284
+
285
+
286
+ Image.register_open(AvifImageFile.format, AvifImageFile, _accept)
287
+ if SUPPORTED:
288
+ Image.register_save(AvifImageFile.format, _save)
289
+ Image.register_save_all(AvifImageFile.format, _save_all)
290
+ Image.register_extensions(AvifImageFile.format, [".avif", ".avifs"])
291
+ Image.register_mime(AvifImageFile.format, "image/avif")
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/BdfFontFile.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library
3
+ # $Id$
4
+ #
5
+ # bitmap distribution font (bdf) file parser
6
+ #
7
+ # history:
8
+ # 1996-05-16 fl created (as bdf2pil)
9
+ # 1997-08-25 fl converted to FontFile driver
10
+ # 2001-05-25 fl removed bogus __init__ call
11
+ # 2002-11-20 fl robustification (from Kevin Cazabon, Dmitry Vasiliev)
12
+ # 2003-04-22 fl more robustification (from Graham Dumpleton)
13
+ #
14
+ # Copyright (c) 1997-2003 by Secret Labs AB.
15
+ # Copyright (c) 1997-2003 by Fredrik Lundh.
16
+ #
17
+ # See the README file for information on usage and redistribution.
18
+ #
19
+
20
+ """
21
+ Parse X Bitmap Distribution Format (BDF)
22
+ """
23
+ from __future__ import annotations
24
+
25
+ from typing import BinaryIO
26
+
27
+ from . import FontFile, Image
28
+
29
+
30
+ def bdf_char(
31
+ f: BinaryIO,
32
+ ) -> (
33
+ tuple[
34
+ str,
35
+ int,
36
+ tuple[tuple[int, int], tuple[int, int, int, int], tuple[int, int, int, int]],
37
+ Image.Image,
38
+ ]
39
+ | None
40
+ ):
41
+ # skip to STARTCHAR
42
+ while True:
43
+ s = f.readline()
44
+ if not s:
45
+ return None
46
+ if s.startswith(b"STARTCHAR"):
47
+ break
48
+ id = s[9:].strip().decode("ascii")
49
+
50
+ # load symbol properties
51
+ props = {}
52
+ while True:
53
+ s = f.readline()
54
+ if not s or s.startswith(b"BITMAP"):
55
+ break
56
+ i = s.find(b" ")
57
+ props[s[:i].decode("ascii")] = s[i + 1 : -1].decode("ascii")
58
+
59
+ # load bitmap
60
+ bitmap = bytearray()
61
+ while True:
62
+ s = f.readline()
63
+ if not s or s.startswith(b"ENDCHAR"):
64
+ break
65
+ bitmap += s[:-1]
66
+
67
+ # The word BBX
68
+ # followed by the width in x (BBw), height in y (BBh),
69
+ # and x and y displacement (BBxoff0, BByoff0)
70
+ # of the lower left corner from the origin of the character.
71
+ width, height, x_disp, y_disp = (int(p) for p in props["BBX"].split())
72
+
73
+ # The word DWIDTH
74
+ # followed by the width in x and y of the character in device pixels.
75
+ dwx, dwy = (int(p) for p in props["DWIDTH"].split())
76
+
77
+ bbox = (
78
+ (dwx, dwy),
79
+ (x_disp, -y_disp - height, width + x_disp, -y_disp),
80
+ (0, 0, width, height),
81
+ )
82
+
83
+ try:
84
+ im = Image.frombytes("1", (width, height), bitmap, "hex", "1")
85
+ except ValueError:
86
+ # deal with zero-width characters
87
+ im = Image.new("1", (width, height))
88
+
89
+ return id, int(props["ENCODING"]), bbox, im
90
+
91
+
92
+ class BdfFontFile(FontFile.FontFile):
93
+ """Font file plugin for the X11 BDF format."""
94
+
95
+ def __init__(self, fp: BinaryIO) -> None:
96
+ super().__init__()
97
+
98
+ s = fp.readline()
99
+ if not s.startswith(b"STARTFONT 2.1"):
100
+ msg = "not a valid BDF file"
101
+ raise SyntaxError(msg)
102
+
103
+ props = {}
104
+ comments = []
105
+
106
+ while True:
107
+ s = fp.readline()
108
+ if not s or s.startswith(b"ENDPROPERTIES"):
109
+ break
110
+ i = s.find(b" ")
111
+ props[s[:i].decode("ascii")] = s[i + 1 : -1].decode("ascii")
112
+ if s[:i] in [b"COMMENT", b"COPYRIGHT"]:
113
+ if s.find(b"LogicalFontDescription") < 0:
114
+ comments.append(s[i + 1 : -1].decode("ascii"))
115
+
116
+ while True:
117
+ c = bdf_char(fp)
118
+ if not c:
119
+ break
120
+ id, ch, (xy, dst, src), im = c
121
+ if 0 <= ch < len(self.glyph):
122
+ self.glyph[ch] = xy, dst, src, im
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/BlpImagePlugin.py ADDED
@@ -0,0 +1,497 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Blizzard Mipmap Format (.blp)
3
+ Jerome Leclanche <jerome@leclan.ch>
4
+
5
+ The contents of this file are hereby released in the public domain (CC0)
6
+ Full text of the CC0 license:
7
+ https://creativecommons.org/publicdomain/zero/1.0/
8
+
9
+ BLP1 files, used mostly in Warcraft III, are not fully supported.
10
+ All types of BLP2 files used in World of Warcraft are supported.
11
+
12
+ The BLP file structure consists of a header, up to 16 mipmaps of the
13
+ texture
14
+
15
+ Texture sizes must be powers of two, though the two dimensions do
16
+ not have to be equal; 512x256 is valid, but 512x200 is not.
17
+ The first mipmap (mipmap #0) is the full size image; each subsequent
18
+ mipmap halves both dimensions. The final mipmap should be 1x1.
19
+
20
+ BLP files come in many different flavours:
21
+ * JPEG-compressed (type == 0) - only supported for BLP1.
22
+ * RAW images (type == 1, encoding == 1). Each mipmap is stored as an
23
+ array of 8-bit values, one per pixel, left to right, top to bottom.
24
+ Each value is an index to the palette.
25
+ * DXT-compressed (type == 1, encoding == 2):
26
+ - DXT1 compression is used if alpha_encoding == 0.
27
+ - An additional alpha bit is used if alpha_depth == 1.
28
+ - DXT3 compression is used if alpha_encoding == 1.
29
+ - DXT5 compression is used if alpha_encoding == 7.
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ import abc
35
+ import os
36
+ import struct
37
+ from enum import IntEnum
38
+ from io import BytesIO
39
+ from typing import IO
40
+
41
+ from . import Image, ImageFile
42
+
43
+
44
+ class Format(IntEnum):
45
+ JPEG = 0
46
+
47
+
48
+ class Encoding(IntEnum):
49
+ UNCOMPRESSED = 1
50
+ DXT = 2
51
+ UNCOMPRESSED_RAW_BGRA = 3
52
+
53
+
54
+ class AlphaEncoding(IntEnum):
55
+ DXT1 = 0
56
+ DXT3 = 1
57
+ DXT5 = 7
58
+
59
+
60
+ def unpack_565(i: int) -> tuple[int, int, int]:
61
+ return ((i >> 11) & 0x1F) << 3, ((i >> 5) & 0x3F) << 2, (i & 0x1F) << 3
62
+
63
+
64
+ def decode_dxt1(
65
+ data: bytes, alpha: bool = False
66
+ ) -> tuple[bytearray, bytearray, bytearray, bytearray]:
67
+ """
68
+ input: one "row" of data (i.e. will produce 4*width pixels)
69
+ """
70
+
71
+ blocks = len(data) // 8 # number of blocks in row
72
+ ret = (bytearray(), bytearray(), bytearray(), bytearray())
73
+
74
+ for block_index in range(blocks):
75
+ # Decode next 8-byte block.
76
+ idx = block_index * 8
77
+ color0, color1, bits = struct.unpack_from("<HHI", data, idx)
78
+
79
+ r0, g0, b0 = unpack_565(color0)
80
+ r1, g1, b1 = unpack_565(color1)
81
+
82
+ # Decode this block into 4x4 pixels
83
+ # Accumulate the results onto our 4 row accumulators
84
+ for j in range(4):
85
+ for i in range(4):
86
+ # get next control op and generate a pixel
87
+
88
+ control = bits & 3
89
+ bits = bits >> 2
90
+
91
+ a = 0xFF
92
+ if control == 0:
93
+ r, g, b = r0, g0, b0
94
+ elif control == 1:
95
+ r, g, b = r1, g1, b1
96
+ elif control == 2:
97
+ if color0 > color1:
98
+ r = (2 * r0 + r1) // 3
99
+ g = (2 * g0 + g1) // 3
100
+ b = (2 * b0 + b1) // 3
101
+ else:
102
+ r = (r0 + r1) // 2
103
+ g = (g0 + g1) // 2
104
+ b = (b0 + b1) // 2
105
+ elif control == 3:
106
+ if color0 > color1:
107
+ r = (2 * r1 + r0) // 3
108
+ g = (2 * g1 + g0) // 3
109
+ b = (2 * b1 + b0) // 3
110
+ else:
111
+ r, g, b, a = 0, 0, 0, 0
112
+
113
+ if alpha:
114
+ ret[j].extend([r, g, b, a])
115
+ else:
116
+ ret[j].extend([r, g, b])
117
+
118
+ return ret
119
+
120
+
121
+ def decode_dxt3(data: bytes) -> tuple[bytearray, bytearray, bytearray, bytearray]:
122
+ """
123
+ input: one "row" of data (i.e. will produce 4*width pixels)
124
+ """
125
+
126
+ blocks = len(data) // 16 # number of blocks in row
127
+ ret = (bytearray(), bytearray(), bytearray(), bytearray())
128
+
129
+ for block_index in range(blocks):
130
+ idx = block_index * 16
131
+ block = data[idx : idx + 16]
132
+ # Decode next 16-byte block.
133
+ bits = struct.unpack_from("<8B", block)
134
+ color0, color1 = struct.unpack_from("<HH", block, 8)
135
+
136
+ (code,) = struct.unpack_from("<I", block, 12)
137
+
138
+ r0, g0, b0 = unpack_565(color0)
139
+ r1, g1, b1 = unpack_565(color1)
140
+
141
+ for j in range(4):
142
+ high = False # Do we want the higher bits?
143
+ for i in range(4):
144
+ alphacode_index = (4 * j + i) // 2
145
+ a = bits[alphacode_index]
146
+ if high:
147
+ high = False
148
+ a >>= 4
149
+ else:
150
+ high = True
151
+ a &= 0xF
152
+ a *= 17 # We get a value between 0 and 15
153
+
154
+ color_code = (code >> 2 * (4 * j + i)) & 0x03
155
+
156
+ if color_code == 0:
157
+ r, g, b = r0, g0, b0
158
+ elif color_code == 1:
159
+ r, g, b = r1, g1, b1
160
+ elif color_code == 2:
161
+ r = (2 * r0 + r1) // 3
162
+ g = (2 * g0 + g1) // 3
163
+ b = (2 * b0 + b1) // 3
164
+ elif color_code == 3:
165
+ r = (2 * r1 + r0) // 3
166
+ g = (2 * g1 + g0) // 3
167
+ b = (2 * b1 + b0) // 3
168
+
169
+ ret[j].extend([r, g, b, a])
170
+
171
+ return ret
172
+
173
+
174
+ def decode_dxt5(data: bytes) -> tuple[bytearray, bytearray, bytearray, bytearray]:
175
+ """
176
+ input: one "row" of data (i.e. will produce 4 * width pixels)
177
+ """
178
+
179
+ blocks = len(data) // 16 # number of blocks in row
180
+ ret = (bytearray(), bytearray(), bytearray(), bytearray())
181
+
182
+ for block_index in range(blocks):
183
+ idx = block_index * 16
184
+ block = data[idx : idx + 16]
185
+ # Decode next 16-byte block.
186
+ a0, a1 = struct.unpack_from("<BB", block)
187
+
188
+ bits = struct.unpack_from("<6B", block, 2)
189
+ alphacode1 = bits[2] | (bits[3] << 8) | (bits[4] << 16) | (bits[5] << 24)
190
+ alphacode2 = bits[0] | (bits[1] << 8)
191
+
192
+ color0, color1 = struct.unpack_from("<HH", block, 8)
193
+
194
+ (code,) = struct.unpack_from("<I", block, 12)
195
+
196
+ r0, g0, b0 = unpack_565(color0)
197
+ r1, g1, b1 = unpack_565(color1)
198
+
199
+ for j in range(4):
200
+ for i in range(4):
201
+ # get next control op and generate a pixel
202
+ alphacode_index = 3 * (4 * j + i)
203
+
204
+ if alphacode_index <= 12:
205
+ alphacode = (alphacode2 >> alphacode_index) & 0x07
206
+ elif alphacode_index == 15:
207
+ alphacode = (alphacode2 >> 15) | ((alphacode1 << 1) & 0x06)
208
+ else: # alphacode_index >= 18 and alphacode_index <= 45
209
+ alphacode = (alphacode1 >> (alphacode_index - 16)) & 0x07
210
+
211
+ if alphacode == 0:
212
+ a = a0
213
+ elif alphacode == 1:
214
+ a = a1
215
+ elif a0 > a1:
216
+ a = ((8 - alphacode) * a0 + (alphacode - 1) * a1) // 7
217
+ elif alphacode == 6:
218
+ a = 0
219
+ elif alphacode == 7:
220
+ a = 255
221
+ else:
222
+ a = ((6 - alphacode) * a0 + (alphacode - 1) * a1) // 5
223
+
224
+ color_code = (code >> 2 * (4 * j + i)) & 0x03
225
+
226
+ if color_code == 0:
227
+ r, g, b = r0, g0, b0
228
+ elif color_code == 1:
229
+ r, g, b = r1, g1, b1
230
+ elif color_code == 2:
231
+ r = (2 * r0 + r1) // 3
232
+ g = (2 * g0 + g1) // 3
233
+ b = (2 * b0 + b1) // 3
234
+ elif color_code == 3:
235
+ r = (2 * r1 + r0) // 3
236
+ g = (2 * g1 + g0) // 3
237
+ b = (2 * b1 + b0) // 3
238
+
239
+ ret[j].extend([r, g, b, a])
240
+
241
+ return ret
242
+
243
+
244
+ class BLPFormatError(NotImplementedError):
245
+ pass
246
+
247
+
248
+ def _accept(prefix: bytes) -> bool:
249
+ return prefix.startswith((b"BLP1", b"BLP2"))
250
+
251
+
252
+ class BlpImageFile(ImageFile.ImageFile):
253
+ """
254
+ Blizzard Mipmap Format
255
+ """
256
+
257
+ format = "BLP"
258
+ format_description = "Blizzard Mipmap Format"
259
+
260
+ def _open(self) -> None:
261
+ self.magic = self.fp.read(4)
262
+ if not _accept(self.magic):
263
+ msg = f"Bad BLP magic {repr(self.magic)}"
264
+ raise BLPFormatError(msg)
265
+
266
+ compression = struct.unpack("<i", self.fp.read(4))[0]
267
+ if self.magic == b"BLP1":
268
+ alpha = struct.unpack("<I", self.fp.read(4))[0] != 0
269
+ else:
270
+ encoding = struct.unpack("<b", self.fp.read(1))[0]
271
+ alpha = struct.unpack("<b", self.fp.read(1))[0] != 0
272
+ alpha_encoding = struct.unpack("<b", self.fp.read(1))[0]
273
+ self.fp.seek(1, os.SEEK_CUR) # mips
274
+
275
+ self._size = struct.unpack("<II", self.fp.read(8))
276
+
277
+ args: tuple[int, int, bool] | tuple[int, int, bool, int]
278
+ if self.magic == b"BLP1":
279
+ encoding = struct.unpack("<i", self.fp.read(4))[0]
280
+ self.fp.seek(4, os.SEEK_CUR) # subtype
281
+
282
+ args = (compression, encoding, alpha)
283
+ offset = 28
284
+ else:
285
+ args = (compression, encoding, alpha, alpha_encoding)
286
+ offset = 20
287
+
288
+ decoder = self.magic.decode()
289
+
290
+ self._mode = "RGBA" if alpha else "RGB"
291
+ self.tile = [ImageFile._Tile(decoder, (0, 0) + self.size, offset, args)]
292
+
293
+
294
+ class _BLPBaseDecoder(abc.ABC, ImageFile.PyDecoder):
295
+ _pulls_fd = True
296
+
297
+ def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:
298
+ try:
299
+ self._read_header()
300
+ self._load()
301
+ except struct.error as e:
302
+ msg = "Truncated BLP file"
303
+ raise OSError(msg) from e
304
+ return -1, 0
305
+
306
+ @abc.abstractmethod
307
+ def _load(self) -> None:
308
+ pass
309
+
310
+ def _read_header(self) -> None:
311
+ self._offsets = struct.unpack("<16I", self._safe_read(16 * 4))
312
+ self._lengths = struct.unpack("<16I", self._safe_read(16 * 4))
313
+
314
+ def _safe_read(self, length: int) -> bytes:
315
+ assert self.fd is not None
316
+ return ImageFile._safe_read(self.fd, length)
317
+
318
+ def _read_palette(self) -> list[tuple[int, int, int, int]]:
319
+ ret = []
320
+ for i in range(256):
321
+ try:
322
+ b, g, r, a = struct.unpack("<4B", self._safe_read(4))
323
+ except struct.error:
324
+ break
325
+ ret.append((b, g, r, a))
326
+ return ret
327
+
328
+ def _read_bgra(
329
+ self, palette: list[tuple[int, int, int, int]], alpha: bool
330
+ ) -> bytearray:
331
+ data = bytearray()
332
+ _data = BytesIO(self._safe_read(self._lengths[0]))
333
+ while True:
334
+ try:
335
+ (offset,) = struct.unpack("<B", _data.read(1))
336
+ except struct.error:
337
+ break
338
+ b, g, r, a = palette[offset]
339
+ d: tuple[int, ...] = (r, g, b)
340
+ if alpha:
341
+ d += (a,)
342
+ data.extend(d)
343
+ return data
344
+
345
+
346
+ class BLP1Decoder(_BLPBaseDecoder):
347
+ def _load(self) -> None:
348
+ self._compression, self._encoding, alpha = self.args
349
+
350
+ if self._compression == Format.JPEG:
351
+ self._decode_jpeg_stream()
352
+
353
+ elif self._compression == 1:
354
+ if self._encoding in (4, 5):
355
+ palette = self._read_palette()
356
+ data = self._read_bgra(palette, alpha)
357
+ self.set_as_raw(data)
358
+ else:
359
+ msg = f"Unsupported BLP encoding {repr(self._encoding)}"
360
+ raise BLPFormatError(msg)
361
+ else:
362
+ msg = f"Unsupported BLP compression {repr(self._encoding)}"
363
+ raise BLPFormatError(msg)
364
+
365
+ def _decode_jpeg_stream(self) -> None:
366
+ from .JpegImagePlugin import JpegImageFile
367
+
368
+ (jpeg_header_size,) = struct.unpack("<I", self._safe_read(4))
369
+ jpeg_header = self._safe_read(jpeg_header_size)
370
+ assert self.fd is not None
371
+ self._safe_read(self._offsets[0] - self.fd.tell()) # What IS this?
372
+ data = self._safe_read(self._lengths[0])
373
+ data = jpeg_header + data
374
+ image = JpegImageFile(BytesIO(data))
375
+ Image._decompression_bomb_check(image.size)
376
+ if image.mode == "CMYK":
377
+ args = image.tile[0].args
378
+ assert isinstance(args, tuple)
379
+ image.tile = [image.tile[0]._replace(args=(args[0], "CMYK"))]
380
+ self.set_as_raw(image.convert("RGB").tobytes(), "BGR")
381
+
382
+
383
+ class BLP2Decoder(_BLPBaseDecoder):
384
+ def _load(self) -> None:
385
+ self._compression, self._encoding, alpha, self._alpha_encoding = self.args
386
+
387
+ palette = self._read_palette()
388
+
389
+ assert self.fd is not None
390
+ self.fd.seek(self._offsets[0])
391
+
392
+ if self._compression == 1:
393
+ # Uncompressed or DirectX compression
394
+
395
+ if self._encoding == Encoding.UNCOMPRESSED:
396
+ data = self._read_bgra(palette, alpha)
397
+
398
+ elif self._encoding == Encoding.DXT:
399
+ data = bytearray()
400
+ if self._alpha_encoding == AlphaEncoding.DXT1:
401
+ linesize = (self.state.xsize + 3) // 4 * 8
402
+ for yb in range((self.state.ysize + 3) // 4):
403
+ for d in decode_dxt1(self._safe_read(linesize), alpha):
404
+ data += d
405
+
406
+ elif self._alpha_encoding == AlphaEncoding.DXT3:
407
+ linesize = (self.state.xsize + 3) // 4 * 16
408
+ for yb in range((self.state.ysize + 3) // 4):
409
+ for d in decode_dxt3(self._safe_read(linesize)):
410
+ data += d
411
+
412
+ elif self._alpha_encoding == AlphaEncoding.DXT5:
413
+ linesize = (self.state.xsize + 3) // 4 * 16
414
+ for yb in range((self.state.ysize + 3) // 4):
415
+ for d in decode_dxt5(self._safe_read(linesize)):
416
+ data += d
417
+ else:
418
+ msg = f"Unsupported alpha encoding {repr(self._alpha_encoding)}"
419
+ raise BLPFormatError(msg)
420
+ else:
421
+ msg = f"Unknown BLP encoding {repr(self._encoding)}"
422
+ raise BLPFormatError(msg)
423
+
424
+ else:
425
+ msg = f"Unknown BLP compression {repr(self._compression)}"
426
+ raise BLPFormatError(msg)
427
+
428
+ self.set_as_raw(data)
429
+
430
+
431
+ class BLPEncoder(ImageFile.PyEncoder):
432
+ _pushes_fd = True
433
+
434
+ def _write_palette(self) -> bytes:
435
+ data = b""
436
+ assert self.im is not None
437
+ palette = self.im.getpalette("RGBA", "RGBA")
438
+ for i in range(len(palette) // 4):
439
+ r, g, b, a = palette[i * 4 : (i + 1) * 4]
440
+ data += struct.pack("<4B", b, g, r, a)
441
+ while len(data) < 256 * 4:
442
+ data += b"\x00" * 4
443
+ return data
444
+
445
+ def encode(self, bufsize: int) -> tuple[int, int, bytes]:
446
+ palette_data = self._write_palette()
447
+
448
+ offset = 20 + 16 * 4 * 2 + len(palette_data)
449
+ data = struct.pack("<16I", offset, *((0,) * 15))
450
+
451
+ assert self.im is not None
452
+ w, h = self.im.size
453
+ data += struct.pack("<16I", w * h, *((0,) * 15))
454
+
455
+ data += palette_data
456
+
457
+ for y in range(h):
458
+ for x in range(w):
459
+ data += struct.pack("<B", self.im.getpixel((x, y)))
460
+
461
+ return len(data), 0, data
462
+
463
+
464
+ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
465
+ if im.mode != "P":
466
+ msg = "Unsupported BLP image mode"
467
+ raise ValueError(msg)
468
+
469
+ magic = b"BLP1" if im.encoderinfo.get("blp_version") == "BLP1" else b"BLP2"
470
+ fp.write(magic)
471
+
472
+ assert im.palette is not None
473
+ fp.write(struct.pack("<i", 1)) # Uncompressed or DirectX compression
474
+
475
+ alpha_depth = 1 if im.palette.mode == "RGBA" else 0
476
+ if magic == b"BLP1":
477
+ fp.write(struct.pack("<L", alpha_depth))
478
+ else:
479
+ fp.write(struct.pack("<b", Encoding.UNCOMPRESSED))
480
+ fp.write(struct.pack("<b", alpha_depth))
481
+ fp.write(struct.pack("<b", 0)) # alpha encoding
482
+ fp.write(struct.pack("<b", 0)) # mips
483
+ fp.write(struct.pack("<II", *im.size))
484
+ if magic == b"BLP1":
485
+ fp.write(struct.pack("<i", 5))
486
+ fp.write(struct.pack("<i", 0))
487
+
488
+ ImageFile._save(im, fp, [ImageFile._Tile("BLP", (0, 0) + im.size, 0, im.mode)])
489
+
490
+
491
+ Image.register_open(BlpImageFile.format, BlpImageFile, _accept)
492
+ Image.register_extension(BlpImageFile.format, ".blp")
493
+ Image.register_decoder("BLP1", BLP1Decoder)
494
+ Image.register_decoder("BLP2", BLP2Decoder)
495
+
496
+ Image.register_save(BlpImageFile.format, _save)
497
+ Image.register_encoder("BLP", BLPEncoder)
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/BmpImagePlugin.py ADDED
@@ -0,0 +1,515 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # BMP file handler
6
+ #
7
+ # Windows (and OS/2) native bitmap storage format.
8
+ #
9
+ # history:
10
+ # 1995-09-01 fl Created
11
+ # 1996-04-30 fl Added save
12
+ # 1997-08-27 fl Fixed save of 1-bit images
13
+ # 1998-03-06 fl Load P images as L where possible
14
+ # 1998-07-03 fl Load P images as 1 where possible
15
+ # 1998-12-29 fl Handle small palettes
16
+ # 2002-12-30 fl Fixed load of 1-bit palette images
17
+ # 2003-04-21 fl Fixed load of 1-bit monochrome images
18
+ # 2003-04-23 fl Added limited support for BI_BITFIELDS compression
19
+ #
20
+ # Copyright (c) 1997-2003 by Secret Labs AB
21
+ # Copyright (c) 1995-2003 by Fredrik Lundh
22
+ #
23
+ # See the README file for information on usage and redistribution.
24
+ #
25
+ from __future__ import annotations
26
+
27
+ import os
28
+ from typing import IO, Any
29
+
30
+ from . import Image, ImageFile, ImagePalette
31
+ from ._binary import i16le as i16
32
+ from ._binary import i32le as i32
33
+ from ._binary import o8
34
+ from ._binary import o16le as o16
35
+ from ._binary import o32le as o32
36
+
37
+ #
38
+ # --------------------------------------------------------------------
39
+ # Read BMP file
40
+
41
+ BIT2MODE = {
42
+ # bits => mode, rawmode
43
+ 1: ("P", "P;1"),
44
+ 4: ("P", "P;4"),
45
+ 8: ("P", "P"),
46
+ 16: ("RGB", "BGR;15"),
47
+ 24: ("RGB", "BGR"),
48
+ 32: ("RGB", "BGRX"),
49
+ }
50
+
51
+ USE_RAW_ALPHA = False
52
+
53
+
54
+ def _accept(prefix: bytes) -> bool:
55
+ return prefix.startswith(b"BM")
56
+
57
+
58
+ def _dib_accept(prefix: bytes) -> bool:
59
+ return i32(prefix) in [12, 40, 52, 56, 64, 108, 124]
60
+
61
+
62
+ # =============================================================================
63
+ # Image plugin for the Windows BMP format.
64
+ # =============================================================================
65
+ class BmpImageFile(ImageFile.ImageFile):
66
+ """Image plugin for the Windows Bitmap format (BMP)"""
67
+
68
+ # ------------------------------------------------------------- Description
69
+ format_description = "Windows Bitmap"
70
+ format = "BMP"
71
+
72
+ # -------------------------------------------------- BMP Compression values
73
+ COMPRESSIONS = {"RAW": 0, "RLE8": 1, "RLE4": 2, "BITFIELDS": 3, "JPEG": 4, "PNG": 5}
74
+ for k, v in COMPRESSIONS.items():
75
+ vars()[k] = v
76
+
77
+ def _bitmap(self, header: int = 0, offset: int = 0) -> None:
78
+ """Read relevant info about the BMP"""
79
+ read, seek = self.fp.read, self.fp.seek
80
+ if header:
81
+ seek(header)
82
+ # read bmp header size @offset 14 (this is part of the header size)
83
+ file_info: dict[str, bool | int | tuple[int, ...]] = {
84
+ "header_size": i32(read(4)),
85
+ "direction": -1,
86
+ }
87
+
88
+ # -------------------- If requested, read header at a specific position
89
+ # read the rest of the bmp header, without its size
90
+ assert isinstance(file_info["header_size"], int)
91
+ header_data = ImageFile._safe_read(self.fp, file_info["header_size"] - 4)
92
+
93
+ # ------------------------------- Windows Bitmap v2, IBM OS/2 Bitmap v1
94
+ # ----- This format has different offsets because of width/height types
95
+ # 12: BITMAPCOREHEADER/OS21XBITMAPHEADER
96
+ if file_info["header_size"] == 12:
97
+ file_info["width"] = i16(header_data, 0)
98
+ file_info["height"] = i16(header_data, 2)
99
+ file_info["planes"] = i16(header_data, 4)
100
+ file_info["bits"] = i16(header_data, 6)
101
+ file_info["compression"] = self.COMPRESSIONS["RAW"]
102
+ file_info["palette_padding"] = 3
103
+
104
+ # --------------------------------------------- Windows Bitmap v3 to v5
105
+ # 40: BITMAPINFOHEADER
106
+ # 52: BITMAPV2HEADER
107
+ # 56: BITMAPV3HEADER
108
+ # 64: BITMAPCOREHEADER2/OS22XBITMAPHEADER
109
+ # 108: BITMAPV4HEADER
110
+ # 124: BITMAPV5HEADER
111
+ elif file_info["header_size"] in (40, 52, 56, 64, 108, 124):
112
+ file_info["y_flip"] = header_data[7] == 0xFF
113
+ file_info["direction"] = 1 if file_info["y_flip"] else -1
114
+ file_info["width"] = i32(header_data, 0)
115
+ file_info["height"] = (
116
+ i32(header_data, 4)
117
+ if not file_info["y_flip"]
118
+ else 2**32 - i32(header_data, 4)
119
+ )
120
+ file_info["planes"] = i16(header_data, 8)
121
+ file_info["bits"] = i16(header_data, 10)
122
+ file_info["compression"] = i32(header_data, 12)
123
+ # byte size of pixel data
124
+ file_info["data_size"] = i32(header_data, 16)
125
+ file_info["pixels_per_meter"] = (
126
+ i32(header_data, 20),
127
+ i32(header_data, 24),
128
+ )
129
+ file_info["colors"] = i32(header_data, 28)
130
+ file_info["palette_padding"] = 4
131
+ assert isinstance(file_info["pixels_per_meter"], tuple)
132
+ self.info["dpi"] = tuple(x / 39.3701 for x in file_info["pixels_per_meter"])
133
+ if file_info["compression"] == self.COMPRESSIONS["BITFIELDS"]:
134
+ masks = ["r_mask", "g_mask", "b_mask"]
135
+ if len(header_data) >= 48:
136
+ if len(header_data) >= 52:
137
+ masks.append("a_mask")
138
+ else:
139
+ file_info["a_mask"] = 0x0
140
+ for idx, mask in enumerate(masks):
141
+ file_info[mask] = i32(header_data, 36 + idx * 4)
142
+ else:
143
+ # 40 byte headers only have the three components in the
144
+ # bitfields masks, ref:
145
+ # https://msdn.microsoft.com/en-us/library/windows/desktop/dd183376(v=vs.85).aspx
146
+ # See also
147
+ # https://github.com/python-pillow/Pillow/issues/1293
148
+ # There is a 4th component in the RGBQuad, in the alpha
149
+ # location, but it is listed as a reserved component,
150
+ # and it is not generally an alpha channel
151
+ file_info["a_mask"] = 0x0
152
+ for mask in masks:
153
+ file_info[mask] = i32(read(4))
154
+ assert isinstance(file_info["r_mask"], int)
155
+ assert isinstance(file_info["g_mask"], int)
156
+ assert isinstance(file_info["b_mask"], int)
157
+ assert isinstance(file_info["a_mask"], int)
158
+ file_info["rgb_mask"] = (
159
+ file_info["r_mask"],
160
+ file_info["g_mask"],
161
+ file_info["b_mask"],
162
+ )
163
+ file_info["rgba_mask"] = (
164
+ file_info["r_mask"],
165
+ file_info["g_mask"],
166
+ file_info["b_mask"],
167
+ file_info["a_mask"],
168
+ )
169
+ else:
170
+ msg = f"Unsupported BMP header type ({file_info['header_size']})"
171
+ raise OSError(msg)
172
+
173
+ # ------------------ Special case : header is reported 40, which
174
+ # ---------------------- is shorter than real size for bpp >= 16
175
+ assert isinstance(file_info["width"], int)
176
+ assert isinstance(file_info["height"], int)
177
+ self._size = file_info["width"], file_info["height"]
178
+
179
+ # ------- If color count was not found in the header, compute from bits
180
+ assert isinstance(file_info["bits"], int)
181
+ file_info["colors"] = (
182
+ file_info["colors"]
183
+ if file_info.get("colors", 0)
184
+ else (1 << file_info["bits"])
185
+ )
186
+ assert isinstance(file_info["colors"], int)
187
+ if offset == 14 + file_info["header_size"] and file_info["bits"] <= 8:
188
+ offset += 4 * file_info["colors"]
189
+
190
+ # ---------------------- Check bit depth for unusual unsupported values
191
+ self._mode, raw_mode = BIT2MODE.get(file_info["bits"], ("", ""))
192
+ if not self.mode:
193
+ msg = f"Unsupported BMP pixel depth ({file_info['bits']})"
194
+ raise OSError(msg)
195
+
196
+ # ---------------- Process BMP with Bitfields compression (not palette)
197
+ decoder_name = "raw"
198
+ if file_info["compression"] == self.COMPRESSIONS["BITFIELDS"]:
199
+ SUPPORTED: dict[int, list[tuple[int, ...]]] = {
200
+ 32: [
201
+ (0xFF0000, 0xFF00, 0xFF, 0x0),
202
+ (0xFF000000, 0xFF0000, 0xFF00, 0x0),
203
+ (0xFF000000, 0xFF00, 0xFF, 0x0),
204
+ (0xFF000000, 0xFF0000, 0xFF00, 0xFF),
205
+ (0xFF, 0xFF00, 0xFF0000, 0xFF000000),
206
+ (0xFF0000, 0xFF00, 0xFF, 0xFF000000),
207
+ (0xFF000000, 0xFF00, 0xFF, 0xFF0000),
208
+ (0x0, 0x0, 0x0, 0x0),
209
+ ],
210
+ 24: [(0xFF0000, 0xFF00, 0xFF)],
211
+ 16: [(0xF800, 0x7E0, 0x1F), (0x7C00, 0x3E0, 0x1F)],
212
+ }
213
+ MASK_MODES = {
214
+ (32, (0xFF0000, 0xFF00, 0xFF, 0x0)): "BGRX",
215
+ (32, (0xFF000000, 0xFF0000, 0xFF00, 0x0)): "XBGR",
216
+ (32, (0xFF000000, 0xFF00, 0xFF, 0x0)): "BGXR",
217
+ (32, (0xFF000000, 0xFF0000, 0xFF00, 0xFF)): "ABGR",
218
+ (32, (0xFF, 0xFF00, 0xFF0000, 0xFF000000)): "RGBA",
219
+ (32, (0xFF0000, 0xFF00, 0xFF, 0xFF000000)): "BGRA",
220
+ (32, (0xFF000000, 0xFF00, 0xFF, 0xFF0000)): "BGAR",
221
+ (32, (0x0, 0x0, 0x0, 0x0)): "BGRA",
222
+ (24, (0xFF0000, 0xFF00, 0xFF)): "BGR",
223
+ (16, (0xF800, 0x7E0, 0x1F)): "BGR;16",
224
+ (16, (0x7C00, 0x3E0, 0x1F)): "BGR;15",
225
+ }
226
+ if file_info["bits"] in SUPPORTED:
227
+ if (
228
+ file_info["bits"] == 32
229
+ and file_info["rgba_mask"] in SUPPORTED[file_info["bits"]]
230
+ ):
231
+ assert isinstance(file_info["rgba_mask"], tuple)
232
+ raw_mode = MASK_MODES[(file_info["bits"], file_info["rgba_mask"])]
233
+ self._mode = "RGBA" if "A" in raw_mode else self.mode
234
+ elif (
235
+ file_info["bits"] in (24, 16)
236
+ and file_info["rgb_mask"] in SUPPORTED[file_info["bits"]]
237
+ ):
238
+ assert isinstance(file_info["rgb_mask"], tuple)
239
+ raw_mode = MASK_MODES[(file_info["bits"], file_info["rgb_mask"])]
240
+ else:
241
+ msg = "Unsupported BMP bitfields layout"
242
+ raise OSError(msg)
243
+ else:
244
+ msg = "Unsupported BMP bitfields layout"
245
+ raise OSError(msg)
246
+ elif file_info["compression"] == self.COMPRESSIONS["RAW"]:
247
+ if file_info["bits"] == 32 and (
248
+ header == 22 or USE_RAW_ALPHA # 32-bit .cur offset
249
+ ):
250
+ raw_mode, self._mode = "BGRA", "RGBA"
251
+ elif file_info["compression"] in (
252
+ self.COMPRESSIONS["RLE8"],
253
+ self.COMPRESSIONS["RLE4"],
254
+ ):
255
+ decoder_name = "bmp_rle"
256
+ else:
257
+ msg = f"Unsupported BMP compression ({file_info['compression']})"
258
+ raise OSError(msg)
259
+
260
+ # --------------- Once the header is processed, process the palette/LUT
261
+ if self.mode == "P": # Paletted for 1, 4 and 8 bit images
262
+ # ---------------------------------------------------- 1-bit images
263
+ if not (0 < file_info["colors"] <= 65536):
264
+ msg = f"Unsupported BMP Palette size ({file_info['colors']})"
265
+ raise OSError(msg)
266
+ else:
267
+ assert isinstance(file_info["palette_padding"], int)
268
+ padding = file_info["palette_padding"]
269
+ palette = read(padding * file_info["colors"])
270
+ grayscale = True
271
+ indices = (
272
+ (0, 255)
273
+ if file_info["colors"] == 2
274
+ else list(range(file_info["colors"]))
275
+ )
276
+
277
+ # ----------------- Check if grayscale and ignore palette if so
278
+ for ind, val in enumerate(indices):
279
+ rgb = palette[ind * padding : ind * padding + 3]
280
+ if rgb != o8(val) * 3:
281
+ grayscale = False
282
+
283
+ # ------- If all colors are gray, white or black, ditch palette
284
+ if grayscale:
285
+ self._mode = "1" if file_info["colors"] == 2 else "L"
286
+ raw_mode = self.mode
287
+ else:
288
+ self._mode = "P"
289
+ self.palette = ImagePalette.raw(
290
+ "BGRX" if padding == 4 else "BGR", palette
291
+ )
292
+
293
+ # ---------------------------- Finally set the tile data for the plugin
294
+ self.info["compression"] = file_info["compression"]
295
+ args: list[Any] = [raw_mode]
296
+ if decoder_name == "bmp_rle":
297
+ args.append(file_info["compression"] == self.COMPRESSIONS["RLE4"])
298
+ else:
299
+ assert isinstance(file_info["width"], int)
300
+ args.append(((file_info["width"] * file_info["bits"] + 31) >> 3) & (~3))
301
+ args.append(file_info["direction"])
302
+ self.tile = [
303
+ ImageFile._Tile(
304
+ decoder_name,
305
+ (0, 0, file_info["width"], file_info["height"]),
306
+ offset or self.fp.tell(),
307
+ tuple(args),
308
+ )
309
+ ]
310
+
311
+ def _open(self) -> None:
312
+ """Open file, check magic number and read header"""
313
+ # read 14 bytes: magic number, filesize, reserved, header final offset
314
+ head_data = self.fp.read(14)
315
+ # choke if the file does not have the required magic bytes
316
+ if not _accept(head_data):
317
+ msg = "Not a BMP file"
318
+ raise SyntaxError(msg)
319
+ # read the start position of the BMP image data (u32)
320
+ offset = i32(head_data, 10)
321
+ # load bitmap information (offset=raster info)
322
+ self._bitmap(offset=offset)
323
+
324
+
325
+ class BmpRleDecoder(ImageFile.PyDecoder):
326
+ _pulls_fd = True
327
+
328
+ def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:
329
+ assert self.fd is not None
330
+ rle4 = self.args[1]
331
+ data = bytearray()
332
+ x = 0
333
+ dest_length = self.state.xsize * self.state.ysize
334
+ while len(data) < dest_length:
335
+ pixels = self.fd.read(1)
336
+ byte = self.fd.read(1)
337
+ if not pixels or not byte:
338
+ break
339
+ num_pixels = pixels[0]
340
+ if num_pixels:
341
+ # encoded mode
342
+ if x + num_pixels > self.state.xsize:
343
+ # Too much data for row
344
+ num_pixels = max(0, self.state.xsize - x)
345
+ if rle4:
346
+ first_pixel = o8(byte[0] >> 4)
347
+ second_pixel = o8(byte[0] & 0x0F)
348
+ for index in range(num_pixels):
349
+ if index % 2 == 0:
350
+ data += first_pixel
351
+ else:
352
+ data += second_pixel
353
+ else:
354
+ data += byte * num_pixels
355
+ x += num_pixels
356
+ else:
357
+ if byte[0] == 0:
358
+ # end of line
359
+ while len(data) % self.state.xsize != 0:
360
+ data += b"\x00"
361
+ x = 0
362
+ elif byte[0] == 1:
363
+ # end of bitmap
364
+ break
365
+ elif byte[0] == 2:
366
+ # delta
367
+ bytes_read = self.fd.read(2)
368
+ if len(bytes_read) < 2:
369
+ break
370
+ right, up = self.fd.read(2)
371
+ data += b"\x00" * (right + up * self.state.xsize)
372
+ x = len(data) % self.state.xsize
373
+ else:
374
+ # absolute mode
375
+ if rle4:
376
+ # 2 pixels per byte
377
+ byte_count = byte[0] // 2
378
+ bytes_read = self.fd.read(byte_count)
379
+ for byte_read in bytes_read:
380
+ data += o8(byte_read >> 4)
381
+ data += o8(byte_read & 0x0F)
382
+ else:
383
+ byte_count = byte[0]
384
+ bytes_read = self.fd.read(byte_count)
385
+ data += bytes_read
386
+ if len(bytes_read) < byte_count:
387
+ break
388
+ x += byte[0]
389
+
390
+ # align to 16-bit word boundary
391
+ if self.fd.tell() % 2 != 0:
392
+ self.fd.seek(1, os.SEEK_CUR)
393
+ rawmode = "L" if self.mode == "L" else "P"
394
+ self.set_as_raw(bytes(data), rawmode, (0, self.args[-1]))
395
+ return -1, 0
396
+
397
+
398
+ # =============================================================================
399
+ # Image plugin for the DIB format (BMP alias)
400
+ # =============================================================================
401
+ class DibImageFile(BmpImageFile):
402
+ format = "DIB"
403
+ format_description = "Windows Bitmap"
404
+
405
+ def _open(self) -> None:
406
+ self._bitmap()
407
+
408
+
409
+ #
410
+ # --------------------------------------------------------------------
411
+ # Write BMP file
412
+
413
+
414
+ SAVE = {
415
+ "1": ("1", 1, 2),
416
+ "L": ("L", 8, 256),
417
+ "P": ("P", 8, 256),
418
+ "RGB": ("BGR", 24, 0),
419
+ "RGBA": ("BGRA", 32, 0),
420
+ }
421
+
422
+
423
+ def _dib_save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
424
+ _save(im, fp, filename, False)
425
+
426
+
427
+ def _save(
428
+ im: Image.Image, fp: IO[bytes], filename: str | bytes, bitmap_header: bool = True
429
+ ) -> None:
430
+ try:
431
+ rawmode, bits, colors = SAVE[im.mode]
432
+ except KeyError as e:
433
+ msg = f"cannot write mode {im.mode} as BMP"
434
+ raise OSError(msg) from e
435
+
436
+ info = im.encoderinfo
437
+
438
+ dpi = info.get("dpi", (96, 96))
439
+
440
+ # 1 meter == 39.3701 inches
441
+ ppm = tuple(int(x * 39.3701 + 0.5) for x in dpi)
442
+
443
+ stride = ((im.size[0] * bits + 7) // 8 + 3) & (~3)
444
+ header = 40 # or 64 for OS/2 version 2
445
+ image = stride * im.size[1]
446
+
447
+ if im.mode == "1":
448
+ palette = b"".join(o8(i) * 3 + b"\x00" for i in (0, 255))
449
+ elif im.mode == "L":
450
+ palette = b"".join(o8(i) * 3 + b"\x00" for i in range(256))
451
+ elif im.mode == "P":
452
+ palette = im.im.getpalette("RGB", "BGRX")
453
+ colors = len(palette) // 4
454
+ else:
455
+ palette = None
456
+
457
+ # bitmap header
458
+ if bitmap_header:
459
+ offset = 14 + header + colors * 4
460
+ file_size = offset + image
461
+ if file_size > 2**32 - 1:
462
+ msg = "File size is too large for the BMP format"
463
+ raise ValueError(msg)
464
+ fp.write(
465
+ b"BM" # file type (magic)
466
+ + o32(file_size) # file size
467
+ + o32(0) # reserved
468
+ + o32(offset) # image data offset
469
+ )
470
+
471
+ # bitmap info header
472
+ fp.write(
473
+ o32(header) # info header size
474
+ + o32(im.size[0]) # width
475
+ + o32(im.size[1]) # height
476
+ + o16(1) # planes
477
+ + o16(bits) # depth
478
+ + o32(0) # compression (0=uncompressed)
479
+ + o32(image) # size of bitmap
480
+ + o32(ppm[0]) # resolution
481
+ + o32(ppm[1]) # resolution
482
+ + o32(colors) # colors used
483
+ + o32(colors) # colors important
484
+ )
485
+
486
+ fp.write(b"\0" * (header - 40)) # padding (for OS/2 format)
487
+
488
+ if palette:
489
+ fp.write(palette)
490
+
491
+ ImageFile._save(
492
+ im, fp, [ImageFile._Tile("raw", (0, 0) + im.size, 0, (rawmode, stride, -1))]
493
+ )
494
+
495
+
496
+ #
497
+ # --------------------------------------------------------------------
498
+ # Registry
499
+
500
+
501
+ Image.register_open(BmpImageFile.format, BmpImageFile, _accept)
502
+ Image.register_save(BmpImageFile.format, _save)
503
+
504
+ Image.register_extension(BmpImageFile.format, ".bmp")
505
+
506
+ Image.register_mime(BmpImageFile.format, "image/bmp")
507
+
508
+ Image.register_decoder("bmp_rle", BmpRleDecoder)
509
+
510
+ Image.register_open(DibImageFile.format, DibImageFile, _dib_accept)
511
+ Image.register_save(DibImageFile.format, _dib_save)
512
+
513
+ Image.register_extension(DibImageFile.format, ".dib")
514
+
515
+ Image.register_mime(DibImageFile.format, "image/bmp")
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/BufrStubImagePlugin.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library
3
+ # $Id$
4
+ #
5
+ # BUFR stub adapter
6
+ #
7
+ # Copyright (c) 1996-2003 by Fredrik Lundh
8
+ #
9
+ # See the README file for information on usage and redistribution.
10
+ #
11
+ from __future__ import annotations
12
+
13
+ import os
14
+ from typing import IO
15
+
16
+ from . import Image, ImageFile
17
+
18
+ _handler = None
19
+
20
+
21
+ def register_handler(handler: ImageFile.StubHandler | None) -> None:
22
+ """
23
+ Install application-specific BUFR image handler.
24
+
25
+ :param handler: Handler object.
26
+ """
27
+ global _handler
28
+ _handler = handler
29
+
30
+
31
+ # --------------------------------------------------------------------
32
+ # Image adapter
33
+
34
+
35
+ def _accept(prefix: bytes) -> bool:
36
+ return prefix.startswith((b"BUFR", b"ZCZC"))
37
+
38
+
39
+ class BufrStubImageFile(ImageFile.StubImageFile):
40
+ format = "BUFR"
41
+ format_description = "BUFR"
42
+
43
+ def _open(self) -> None:
44
+ if not _accept(self.fp.read(4)):
45
+ msg = "Not a BUFR file"
46
+ raise SyntaxError(msg)
47
+
48
+ self.fp.seek(-4, os.SEEK_CUR)
49
+
50
+ # make something up
51
+ self._mode = "F"
52
+ self._size = 1, 1
53
+
54
+ loader = self._load()
55
+ if loader:
56
+ loader.open(self)
57
+
58
+ def _load(self) -> ImageFile.StubHandler | None:
59
+ return _handler
60
+
61
+
62
+ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
63
+ if _handler is None or not hasattr(_handler, "save"):
64
+ msg = "BUFR save handler not installed"
65
+ raise OSError(msg)
66
+ _handler.save(im, fp, filename)
67
+
68
+
69
+ # --------------------------------------------------------------------
70
+ # Registry
71
+
72
+ Image.register_open(BufrStubImageFile.format, BufrStubImageFile, _accept)
73
+ Image.register_save(BufrStubImageFile.format, _save)
74
+
75
+ Image.register_extension(BufrStubImageFile.format, ".bufr")
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/ContainerIO.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # a class to read from a container file
6
+ #
7
+ # History:
8
+ # 1995-06-18 fl Created
9
+ # 1995-09-07 fl Added readline(), readlines()
10
+ #
11
+ # Copyright (c) 1997-2001 by Secret Labs AB
12
+ # Copyright (c) 1995 by Fredrik Lundh
13
+ #
14
+ # See the README file for information on usage and redistribution.
15
+ #
16
+ from __future__ import annotations
17
+
18
+ import io
19
+ from collections.abc import Iterable
20
+ from typing import IO, AnyStr, NoReturn
21
+
22
+
23
+ class ContainerIO(IO[AnyStr]):
24
+ """
25
+ A file object that provides read access to a part of an existing
26
+ file (for example a TAR file).
27
+ """
28
+
29
+ def __init__(self, file: IO[AnyStr], offset: int, length: int) -> None:
30
+ """
31
+ Create file object.
32
+
33
+ :param file: Existing file.
34
+ :param offset: Start of region, in bytes.
35
+ :param length: Size of region, in bytes.
36
+ """
37
+ self.fh: IO[AnyStr] = file
38
+ self.pos = 0
39
+ self.offset = offset
40
+ self.length = length
41
+ self.fh.seek(offset)
42
+
43
+ ##
44
+ # Always false.
45
+
46
+ def isatty(self) -> bool:
47
+ return False
48
+
49
+ def seekable(self) -> bool:
50
+ return True
51
+
52
+ def seek(self, offset: int, mode: int = io.SEEK_SET) -> int:
53
+ """
54
+ Move file pointer.
55
+
56
+ :param offset: Offset in bytes.
57
+ :param mode: Starting position. Use 0 for beginning of region, 1
58
+ for current offset, and 2 for end of region. You cannot move
59
+ the pointer outside the defined region.
60
+ :returns: Offset from start of region, in bytes.
61
+ """
62
+ if mode == 1:
63
+ self.pos = self.pos + offset
64
+ elif mode == 2:
65
+ self.pos = self.length + offset
66
+ else:
67
+ self.pos = offset
68
+ # clamp
69
+ self.pos = max(0, min(self.pos, self.length))
70
+ self.fh.seek(self.offset + self.pos)
71
+ return self.pos
72
+
73
+ def tell(self) -> int:
74
+ """
75
+ Get current file pointer.
76
+
77
+ :returns: Offset from start of region, in bytes.
78
+ """
79
+ return self.pos
80
+
81
+ def readable(self) -> bool:
82
+ return True
83
+
84
+ def read(self, n: int = -1) -> AnyStr:
85
+ """
86
+ Read data.
87
+
88
+ :param n: Number of bytes to read. If omitted, zero or negative,
89
+ read until end of region.
90
+ :returns: An 8-bit string.
91
+ """
92
+ if n > 0:
93
+ n = min(n, self.length - self.pos)
94
+ else:
95
+ n = self.length - self.pos
96
+ if n <= 0: # EOF
97
+ return b"" if "b" in self.fh.mode else "" # type: ignore[return-value]
98
+ self.pos = self.pos + n
99
+ return self.fh.read(n)
100
+
101
+ def readline(self, n: int = -1) -> AnyStr:
102
+ """
103
+ Read a line of text.
104
+
105
+ :param n: Number of bytes to read. If omitted, zero or negative,
106
+ read until end of line.
107
+ :returns: An 8-bit string.
108
+ """
109
+ s: AnyStr = b"" if "b" in self.fh.mode else "" # type: ignore[assignment]
110
+ newline_character = b"\n" if "b" in self.fh.mode else "\n"
111
+ while True:
112
+ c = self.read(1)
113
+ if not c:
114
+ break
115
+ s = s + c
116
+ if c == newline_character or len(s) == n:
117
+ break
118
+ return s
119
+
120
+ def readlines(self, n: int | None = -1) -> list[AnyStr]:
121
+ """
122
+ Read multiple lines of text.
123
+
124
+ :param n: Number of lines to read. If omitted, zero, negative or None,
125
+ read until end of region.
126
+ :returns: A list of 8-bit strings.
127
+ """
128
+ lines = []
129
+ while True:
130
+ s = self.readline()
131
+ if not s:
132
+ break
133
+ lines.append(s)
134
+ if len(lines) == n:
135
+ break
136
+ return lines
137
+
138
+ def writable(self) -> bool:
139
+ return False
140
+
141
+ def write(self, b: AnyStr) -> NoReturn:
142
+ raise NotImplementedError()
143
+
144
+ def writelines(self, lines: Iterable[AnyStr]) -> NoReturn:
145
+ raise NotImplementedError()
146
+
147
+ def truncate(self, size: int | None = None) -> int:
148
+ raise NotImplementedError()
149
+
150
+ def __enter__(self) -> ContainerIO[AnyStr]:
151
+ return self
152
+
153
+ def __exit__(self, *args: object) -> None:
154
+ self.close()
155
+
156
+ def __iter__(self) -> ContainerIO[AnyStr]:
157
+ return self
158
+
159
+ def __next__(self) -> AnyStr:
160
+ line = self.readline()
161
+ if not line:
162
+ msg = "end of region"
163
+ raise StopIteration(msg)
164
+ return line
165
+
166
+ def fileno(self) -> int:
167
+ return self.fh.fileno()
168
+
169
+ def flush(self) -> None:
170
+ self.fh.flush()
171
+
172
+ def close(self) -> None:
173
+ self.fh.close()
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/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.startswith(b"\0\0\2\0")
30
+
31
+
32
+ ##
33
+ # Image plugin for Windows Cursor files.
34
+
35
+
36
+ class CurImageFile(BmpImagePlugin.BmpImageFile):
37
+ format = "CUR"
38
+ format_description = "Windows Cursor"
39
+
40
+ def _open(self) -> None:
41
+ 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")
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/DcxImagePlugin.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # DCX file handling
6
+ #
7
+ # DCX is a container file format defined by Intel, commonly used
8
+ # for fax applications. Each DCX file consists of a directory
9
+ # (a list of file offsets) followed by a set of (usually 1-bit)
10
+ # PCX files.
11
+ #
12
+ # History:
13
+ # 1995-09-09 fl Created
14
+ # 1996-03-20 fl Properly derived from PcxImageFile.
15
+ # 1998-07-15 fl Renamed offset attribute to avoid name clash
16
+ # 2002-07-30 fl Fixed file handling
17
+ #
18
+ # Copyright (c) 1997-98 by Secret Labs AB.
19
+ # Copyright (c) 1995-96 by Fredrik Lundh.
20
+ #
21
+ # See the README file for information on usage and redistribution.
22
+ #
23
+ from __future__ import annotations
24
+
25
+ from . import Image
26
+ from ._binary import i32le as i32
27
+ from ._util import DeferredError
28
+ from .PcxImagePlugin import PcxImageFile
29
+
30
+ MAGIC = 0x3ADE68B1 # QUIZ: what's this value, then?
31
+
32
+
33
+ def _accept(prefix: bytes) -> bool:
34
+ return len(prefix) >= 4 and i32(prefix) == MAGIC
35
+
36
+
37
+ ##
38
+ # Image plugin for the Intel DCX format.
39
+
40
+
41
+ class DcxImageFile(PcxImageFile):
42
+ format = "DCX"
43
+ format_description = "Intel DCX"
44
+ _close_exclusive_fp_after_loading = False
45
+
46
+ def _open(self) -> None:
47
+ # Header
48
+ s = self.fp.read(4)
49
+ if not _accept(s):
50
+ msg = "not a DCX file"
51
+ raise SyntaxError(msg)
52
+
53
+ # Component directory
54
+ self._offset = []
55
+ for i in range(1024):
56
+ offset = i32(self.fp.read(4))
57
+ if not offset:
58
+ break
59
+ self._offset.append(offset)
60
+
61
+ self._fp = self.fp
62
+ self.frame = -1
63
+ self.n_frames = len(self._offset)
64
+ self.is_animated = self.n_frames > 1
65
+ self.seek(0)
66
+
67
+ def seek(self, frame: int) -> None:
68
+ if not self._seek_check(frame):
69
+ return
70
+ if isinstance(self._fp, DeferredError):
71
+ raise self._fp.ex
72
+ self.frame = frame
73
+ self.fp = self._fp
74
+ self.fp.seek(self._offset[frame])
75
+ PcxImageFile._open(self)
76
+
77
+ def tell(self) -> int:
78
+ return self.frame
79
+
80
+
81
+ Image.register_open(DcxImageFile.format, DcxImageFile, _accept)
82
+
83
+ Image.register_extension(DcxImageFile.format, ".dcx")
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/DdsImagePlugin.py ADDED
@@ -0,0 +1,624 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A Pillow plugin for .dds files (S3TC-compressed aka DXTC)
3
+ Jerome Leclanche <jerome@leclan.ch>
4
+
5
+ Documentation:
6
+ https://web.archive.org/web/20170802060935/http://oss.sgi.com/projects/ogl-sample/registry/EXT/texture_compression_s3tc.txt
7
+
8
+ The contents of this file are hereby released in the public domain (CC0)
9
+ Full text of the CC0 license:
10
+ https://creativecommons.org/publicdomain/zero/1.0/
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import io
16
+ import struct
17
+ import sys
18
+ from enum import IntEnum, IntFlag
19
+ from typing import IO
20
+
21
+ from . import Image, ImageFile, ImagePalette
22
+ from ._binary import i32le as i32
23
+ from ._binary import o8
24
+ from ._binary import o32le as o32
25
+
26
+ # Magic ("DDS ")
27
+ DDS_MAGIC = 0x20534444
28
+
29
+
30
+ # DDS flags
31
+ class DDSD(IntFlag):
32
+ CAPS = 0x1
33
+ HEIGHT = 0x2
34
+ WIDTH = 0x4
35
+ PITCH = 0x8
36
+ PIXELFORMAT = 0x1000
37
+ MIPMAPCOUNT = 0x20000
38
+ LINEARSIZE = 0x80000
39
+ DEPTH = 0x800000
40
+
41
+
42
+ # DDS caps
43
+ class DDSCAPS(IntFlag):
44
+ COMPLEX = 0x8
45
+ TEXTURE = 0x1000
46
+ MIPMAP = 0x400000
47
+
48
+
49
+ class DDSCAPS2(IntFlag):
50
+ CUBEMAP = 0x200
51
+ CUBEMAP_POSITIVEX = 0x400
52
+ CUBEMAP_NEGATIVEX = 0x800
53
+ CUBEMAP_POSITIVEY = 0x1000
54
+ CUBEMAP_NEGATIVEY = 0x2000
55
+ CUBEMAP_POSITIVEZ = 0x4000
56
+ CUBEMAP_NEGATIVEZ = 0x8000
57
+ VOLUME = 0x200000
58
+
59
+
60
+ # Pixel Format
61
+ class DDPF(IntFlag):
62
+ ALPHAPIXELS = 0x1
63
+ ALPHA = 0x2
64
+ FOURCC = 0x4
65
+ PALETTEINDEXED8 = 0x20
66
+ RGB = 0x40
67
+ LUMINANCE = 0x20000
68
+
69
+
70
+ # dxgiformat.h
71
+ class DXGI_FORMAT(IntEnum):
72
+ UNKNOWN = 0
73
+ R32G32B32A32_TYPELESS = 1
74
+ R32G32B32A32_FLOAT = 2
75
+ R32G32B32A32_UINT = 3
76
+ R32G32B32A32_SINT = 4
77
+ R32G32B32_TYPELESS = 5
78
+ R32G32B32_FLOAT = 6
79
+ R32G32B32_UINT = 7
80
+ R32G32B32_SINT = 8
81
+ R16G16B16A16_TYPELESS = 9
82
+ R16G16B16A16_FLOAT = 10
83
+ R16G16B16A16_UNORM = 11
84
+ R16G16B16A16_UINT = 12
85
+ R16G16B16A16_SNORM = 13
86
+ R16G16B16A16_SINT = 14
87
+ R32G32_TYPELESS = 15
88
+ R32G32_FLOAT = 16
89
+ R32G32_UINT = 17
90
+ R32G32_SINT = 18
91
+ R32G8X24_TYPELESS = 19
92
+ D32_FLOAT_S8X24_UINT = 20
93
+ R32_FLOAT_X8X24_TYPELESS = 21
94
+ X32_TYPELESS_G8X24_UINT = 22
95
+ R10G10B10A2_TYPELESS = 23
96
+ R10G10B10A2_UNORM = 24
97
+ R10G10B10A2_UINT = 25
98
+ R11G11B10_FLOAT = 26
99
+ R8G8B8A8_TYPELESS = 27
100
+ R8G8B8A8_UNORM = 28
101
+ R8G8B8A8_UNORM_SRGB = 29
102
+ R8G8B8A8_UINT = 30
103
+ R8G8B8A8_SNORM = 31
104
+ R8G8B8A8_SINT = 32
105
+ R16G16_TYPELESS = 33
106
+ R16G16_FLOAT = 34
107
+ R16G16_UNORM = 35
108
+ R16G16_UINT = 36
109
+ R16G16_SNORM = 37
110
+ R16G16_SINT = 38
111
+ R32_TYPELESS = 39
112
+ D32_FLOAT = 40
113
+ R32_FLOAT = 41
114
+ R32_UINT = 42
115
+ R32_SINT = 43
116
+ R24G8_TYPELESS = 44
117
+ D24_UNORM_S8_UINT = 45
118
+ R24_UNORM_X8_TYPELESS = 46
119
+ X24_TYPELESS_G8_UINT = 47
120
+ R8G8_TYPELESS = 48
121
+ R8G8_UNORM = 49
122
+ R8G8_UINT = 50
123
+ R8G8_SNORM = 51
124
+ R8G8_SINT = 52
125
+ R16_TYPELESS = 53
126
+ R16_FLOAT = 54
127
+ D16_UNORM = 55
128
+ R16_UNORM = 56
129
+ R16_UINT = 57
130
+ R16_SNORM = 58
131
+ R16_SINT = 59
132
+ R8_TYPELESS = 60
133
+ R8_UNORM = 61
134
+ R8_UINT = 62
135
+ R8_SNORM = 63
136
+ R8_SINT = 64
137
+ A8_UNORM = 65
138
+ R1_UNORM = 66
139
+ R9G9B9E5_SHAREDEXP = 67
140
+ R8G8_B8G8_UNORM = 68
141
+ G8R8_G8B8_UNORM = 69
142
+ BC1_TYPELESS = 70
143
+ BC1_UNORM = 71
144
+ BC1_UNORM_SRGB = 72
145
+ BC2_TYPELESS = 73
146
+ BC2_UNORM = 74
147
+ BC2_UNORM_SRGB = 75
148
+ BC3_TYPELESS = 76
149
+ BC3_UNORM = 77
150
+ BC3_UNORM_SRGB = 78
151
+ BC4_TYPELESS = 79
152
+ BC4_UNORM = 80
153
+ BC4_SNORM = 81
154
+ BC5_TYPELESS = 82
155
+ BC5_UNORM = 83
156
+ BC5_SNORM = 84
157
+ B5G6R5_UNORM = 85
158
+ B5G5R5A1_UNORM = 86
159
+ B8G8R8A8_UNORM = 87
160
+ B8G8R8X8_UNORM = 88
161
+ R10G10B10_XR_BIAS_A2_UNORM = 89
162
+ B8G8R8A8_TYPELESS = 90
163
+ B8G8R8A8_UNORM_SRGB = 91
164
+ B8G8R8X8_TYPELESS = 92
165
+ B8G8R8X8_UNORM_SRGB = 93
166
+ BC6H_TYPELESS = 94
167
+ BC6H_UF16 = 95
168
+ BC6H_SF16 = 96
169
+ BC7_TYPELESS = 97
170
+ BC7_UNORM = 98
171
+ BC7_UNORM_SRGB = 99
172
+ AYUV = 100
173
+ Y410 = 101
174
+ Y416 = 102
175
+ NV12 = 103
176
+ P010 = 104
177
+ P016 = 105
178
+ OPAQUE_420 = 106
179
+ YUY2 = 107
180
+ Y210 = 108
181
+ Y216 = 109
182
+ NV11 = 110
183
+ AI44 = 111
184
+ IA44 = 112
185
+ P8 = 113
186
+ A8P8 = 114
187
+ B4G4R4A4_UNORM = 115
188
+ P208 = 130
189
+ V208 = 131
190
+ V408 = 132
191
+ SAMPLER_FEEDBACK_MIN_MIP_OPAQUE = 189
192
+ SAMPLER_FEEDBACK_MIP_REGION_USED_OPAQUE = 190
193
+
194
+
195
+ class D3DFMT(IntEnum):
196
+ UNKNOWN = 0
197
+ R8G8B8 = 20
198
+ A8R8G8B8 = 21
199
+ X8R8G8B8 = 22
200
+ R5G6B5 = 23
201
+ X1R5G5B5 = 24
202
+ A1R5G5B5 = 25
203
+ A4R4G4B4 = 26
204
+ R3G3B2 = 27
205
+ A8 = 28
206
+ A8R3G3B2 = 29
207
+ X4R4G4B4 = 30
208
+ A2B10G10R10 = 31
209
+ A8B8G8R8 = 32
210
+ X8B8G8R8 = 33
211
+ G16R16 = 34
212
+ A2R10G10B10 = 35
213
+ A16B16G16R16 = 36
214
+ A8P8 = 40
215
+ P8 = 41
216
+ L8 = 50
217
+ A8L8 = 51
218
+ A4L4 = 52
219
+ V8U8 = 60
220
+ L6V5U5 = 61
221
+ X8L8V8U8 = 62
222
+ Q8W8V8U8 = 63
223
+ V16U16 = 64
224
+ A2W10V10U10 = 67
225
+ D16_LOCKABLE = 70
226
+ D32 = 71
227
+ D15S1 = 73
228
+ D24S8 = 75
229
+ D24X8 = 77
230
+ D24X4S4 = 79
231
+ D16 = 80
232
+ D32F_LOCKABLE = 82
233
+ D24FS8 = 83
234
+ D32_LOCKABLE = 84
235
+ S8_LOCKABLE = 85
236
+ L16 = 81
237
+ VERTEXDATA = 100
238
+ INDEX16 = 101
239
+ INDEX32 = 102
240
+ Q16W16V16U16 = 110
241
+ R16F = 111
242
+ G16R16F = 112
243
+ A16B16G16R16F = 113
244
+ R32F = 114
245
+ G32R32F = 115
246
+ A32B32G32R32F = 116
247
+ CxV8U8 = 117
248
+ A1 = 118
249
+ A2B10G10R10_XR_BIAS = 119
250
+ BINARYBUFFER = 199
251
+
252
+ UYVY = i32(b"UYVY")
253
+ R8G8_B8G8 = i32(b"RGBG")
254
+ YUY2 = i32(b"YUY2")
255
+ G8R8_G8B8 = i32(b"GRGB")
256
+ DXT1 = i32(b"DXT1")
257
+ DXT2 = i32(b"DXT2")
258
+ DXT3 = i32(b"DXT3")
259
+ DXT4 = i32(b"DXT4")
260
+ DXT5 = i32(b"DXT5")
261
+ DX10 = i32(b"DX10")
262
+ BC4S = i32(b"BC4S")
263
+ BC4U = i32(b"BC4U")
264
+ BC5S = i32(b"BC5S")
265
+ BC5U = i32(b"BC5U")
266
+ ATI1 = i32(b"ATI1")
267
+ ATI2 = i32(b"ATI2")
268
+ MULTI2_ARGB8 = i32(b"MET1")
269
+
270
+
271
+ # Backward compatibility layer
272
+ module = sys.modules[__name__]
273
+ for item in DDSD:
274
+ assert item.name is not None
275
+ setattr(module, f"DDSD_{item.name}", item.value)
276
+ for item1 in DDSCAPS:
277
+ assert item1.name is not None
278
+ setattr(module, f"DDSCAPS_{item1.name}", item1.value)
279
+ for item2 in DDSCAPS2:
280
+ assert item2.name is not None
281
+ setattr(module, f"DDSCAPS2_{item2.name}", item2.value)
282
+ for item3 in DDPF:
283
+ assert item3.name is not None
284
+ setattr(module, f"DDPF_{item3.name}", item3.value)
285
+
286
+ DDS_FOURCC = DDPF.FOURCC
287
+ DDS_RGB = DDPF.RGB
288
+ DDS_RGBA = DDPF.RGB | DDPF.ALPHAPIXELS
289
+ DDS_LUMINANCE = DDPF.LUMINANCE
290
+ DDS_LUMINANCEA = DDPF.LUMINANCE | DDPF.ALPHAPIXELS
291
+ DDS_ALPHA = DDPF.ALPHA
292
+ DDS_PAL8 = DDPF.PALETTEINDEXED8
293
+
294
+ DDS_HEADER_FLAGS_TEXTURE = DDSD.CAPS | DDSD.HEIGHT | DDSD.WIDTH | DDSD.PIXELFORMAT
295
+ DDS_HEADER_FLAGS_MIPMAP = DDSD.MIPMAPCOUNT
296
+ DDS_HEADER_FLAGS_VOLUME = DDSD.DEPTH
297
+ DDS_HEADER_FLAGS_PITCH = DDSD.PITCH
298
+ DDS_HEADER_FLAGS_LINEARSIZE = DDSD.LINEARSIZE
299
+
300
+ DDS_HEIGHT = DDSD.HEIGHT
301
+ DDS_WIDTH = DDSD.WIDTH
302
+
303
+ DDS_SURFACE_FLAGS_TEXTURE = DDSCAPS.TEXTURE
304
+ DDS_SURFACE_FLAGS_MIPMAP = DDSCAPS.COMPLEX | DDSCAPS.MIPMAP
305
+ DDS_SURFACE_FLAGS_CUBEMAP = DDSCAPS.COMPLEX
306
+
307
+ DDS_CUBEMAP_POSITIVEX = DDSCAPS2.CUBEMAP | DDSCAPS2.CUBEMAP_POSITIVEX
308
+ DDS_CUBEMAP_NEGATIVEX = DDSCAPS2.CUBEMAP | DDSCAPS2.CUBEMAP_NEGATIVEX
309
+ DDS_CUBEMAP_POSITIVEY = DDSCAPS2.CUBEMAP | DDSCAPS2.CUBEMAP_POSITIVEY
310
+ DDS_CUBEMAP_NEGATIVEY = DDSCAPS2.CUBEMAP | DDSCAPS2.CUBEMAP_NEGATIVEY
311
+ DDS_CUBEMAP_POSITIVEZ = DDSCAPS2.CUBEMAP | DDSCAPS2.CUBEMAP_POSITIVEZ
312
+ DDS_CUBEMAP_NEGATIVEZ = DDSCAPS2.CUBEMAP | DDSCAPS2.CUBEMAP_NEGATIVEZ
313
+
314
+ DXT1_FOURCC = D3DFMT.DXT1
315
+ DXT3_FOURCC = D3DFMT.DXT3
316
+ DXT5_FOURCC = D3DFMT.DXT5
317
+
318
+ DXGI_FORMAT_R8G8B8A8_TYPELESS = DXGI_FORMAT.R8G8B8A8_TYPELESS
319
+ DXGI_FORMAT_R8G8B8A8_UNORM = DXGI_FORMAT.R8G8B8A8_UNORM
320
+ DXGI_FORMAT_R8G8B8A8_UNORM_SRGB = DXGI_FORMAT.R8G8B8A8_UNORM_SRGB
321
+ DXGI_FORMAT_BC5_TYPELESS = DXGI_FORMAT.BC5_TYPELESS
322
+ DXGI_FORMAT_BC5_UNORM = DXGI_FORMAT.BC5_UNORM
323
+ DXGI_FORMAT_BC5_SNORM = DXGI_FORMAT.BC5_SNORM
324
+ DXGI_FORMAT_BC6H_UF16 = DXGI_FORMAT.BC6H_UF16
325
+ DXGI_FORMAT_BC6H_SF16 = DXGI_FORMAT.BC6H_SF16
326
+ DXGI_FORMAT_BC7_TYPELESS = DXGI_FORMAT.BC7_TYPELESS
327
+ DXGI_FORMAT_BC7_UNORM = DXGI_FORMAT.BC7_UNORM
328
+ DXGI_FORMAT_BC7_UNORM_SRGB = DXGI_FORMAT.BC7_UNORM_SRGB
329
+
330
+
331
+ class DdsImageFile(ImageFile.ImageFile):
332
+ format = "DDS"
333
+ format_description = "DirectDraw Surface"
334
+
335
+ def _open(self) -> None:
336
+ if not _accept(self.fp.read(4)):
337
+ msg = "not a DDS file"
338
+ raise SyntaxError(msg)
339
+ (header_size,) = struct.unpack("<I", self.fp.read(4))
340
+ if header_size != 124:
341
+ msg = f"Unsupported header size {repr(header_size)}"
342
+ raise OSError(msg)
343
+ header_bytes = self.fp.read(header_size - 4)
344
+ if len(header_bytes) != 120:
345
+ msg = f"Incomplete header: {len(header_bytes)} bytes"
346
+ raise OSError(msg)
347
+ header = io.BytesIO(header_bytes)
348
+
349
+ flags, height, width = struct.unpack("<3I", header.read(12))
350
+ self._size = (width, height)
351
+ extents = (0, 0) + self.size
352
+
353
+ pitch, depth, mipmaps = struct.unpack("<3I", header.read(12))
354
+ struct.unpack("<11I", header.read(44)) # reserved
355
+
356
+ # pixel format
357
+ pfsize, pfflags, fourcc, bitcount = struct.unpack("<4I", header.read(16))
358
+ n = 0
359
+ rawmode = None
360
+ if pfflags & DDPF.RGB:
361
+ # Texture contains uncompressed RGB data
362
+ if pfflags & DDPF.ALPHAPIXELS:
363
+ self._mode = "RGBA"
364
+ mask_count = 4
365
+ else:
366
+ self._mode = "RGB"
367
+ mask_count = 3
368
+
369
+ masks = struct.unpack(f"<{mask_count}I", header.read(mask_count * 4))
370
+ self.tile = [ImageFile._Tile("dds_rgb", extents, 0, (bitcount, masks))]
371
+ return
372
+ elif pfflags & DDPF.LUMINANCE:
373
+ if bitcount == 8:
374
+ self._mode = "L"
375
+ elif bitcount == 16 and pfflags & DDPF.ALPHAPIXELS:
376
+ self._mode = "LA"
377
+ else:
378
+ msg = f"Unsupported bitcount {bitcount} for {pfflags}"
379
+ raise OSError(msg)
380
+ elif pfflags & DDPF.PALETTEINDEXED8:
381
+ self._mode = "P"
382
+ self.palette = ImagePalette.raw("RGBA", self.fp.read(1024))
383
+ self.palette.mode = "RGBA"
384
+ elif pfflags & DDPF.FOURCC:
385
+ offset = header_size + 4
386
+ if fourcc == D3DFMT.DXT1:
387
+ self._mode = "RGBA"
388
+ self.pixel_format = "DXT1"
389
+ n = 1
390
+ elif fourcc == D3DFMT.DXT3:
391
+ self._mode = "RGBA"
392
+ self.pixel_format = "DXT3"
393
+ n = 2
394
+ elif fourcc == D3DFMT.DXT5:
395
+ self._mode = "RGBA"
396
+ self.pixel_format = "DXT5"
397
+ n = 3
398
+ elif fourcc in (D3DFMT.BC4U, D3DFMT.ATI1):
399
+ self._mode = "L"
400
+ self.pixel_format = "BC4"
401
+ n = 4
402
+ elif fourcc == D3DFMT.BC5S:
403
+ self._mode = "RGB"
404
+ self.pixel_format = "BC5S"
405
+ n = 5
406
+ elif fourcc in (D3DFMT.BC5U, D3DFMT.ATI2):
407
+ self._mode = "RGB"
408
+ self.pixel_format = "BC5"
409
+ n = 5
410
+ elif fourcc == D3DFMT.DX10:
411
+ offset += 20
412
+ # ignoring flags which pertain to volume textures and cubemaps
413
+ (dxgi_format,) = struct.unpack("<I", self.fp.read(4))
414
+ self.fp.read(16)
415
+ if dxgi_format in (
416
+ DXGI_FORMAT.BC1_UNORM,
417
+ DXGI_FORMAT.BC1_TYPELESS,
418
+ ):
419
+ self._mode = "RGBA"
420
+ self.pixel_format = "BC1"
421
+ n = 1
422
+ elif dxgi_format in (DXGI_FORMAT.BC2_TYPELESS, DXGI_FORMAT.BC2_UNORM):
423
+ self._mode = "RGBA"
424
+ self.pixel_format = "BC2"
425
+ n = 2
426
+ elif dxgi_format in (DXGI_FORMAT.BC3_TYPELESS, DXGI_FORMAT.BC3_UNORM):
427
+ self._mode = "RGBA"
428
+ self.pixel_format = "BC3"
429
+ n = 3
430
+ elif dxgi_format in (DXGI_FORMAT.BC4_TYPELESS, DXGI_FORMAT.BC4_UNORM):
431
+ self._mode = "L"
432
+ self.pixel_format = "BC4"
433
+ n = 4
434
+ elif dxgi_format in (DXGI_FORMAT.BC5_TYPELESS, DXGI_FORMAT.BC5_UNORM):
435
+ self._mode = "RGB"
436
+ self.pixel_format = "BC5"
437
+ n = 5
438
+ elif dxgi_format == DXGI_FORMAT.BC5_SNORM:
439
+ self._mode = "RGB"
440
+ self.pixel_format = "BC5S"
441
+ n = 5
442
+ elif dxgi_format == DXGI_FORMAT.BC6H_UF16:
443
+ self._mode = "RGB"
444
+ self.pixel_format = "BC6H"
445
+ n = 6
446
+ elif dxgi_format == DXGI_FORMAT.BC6H_SF16:
447
+ self._mode = "RGB"
448
+ self.pixel_format = "BC6HS"
449
+ n = 6
450
+ elif dxgi_format in (
451
+ DXGI_FORMAT.BC7_TYPELESS,
452
+ DXGI_FORMAT.BC7_UNORM,
453
+ DXGI_FORMAT.BC7_UNORM_SRGB,
454
+ ):
455
+ self._mode = "RGBA"
456
+ self.pixel_format = "BC7"
457
+ n = 7
458
+ if dxgi_format == DXGI_FORMAT.BC7_UNORM_SRGB:
459
+ self.info["gamma"] = 1 / 2.2
460
+ elif dxgi_format in (
461
+ DXGI_FORMAT.R8G8B8A8_TYPELESS,
462
+ DXGI_FORMAT.R8G8B8A8_UNORM,
463
+ DXGI_FORMAT.R8G8B8A8_UNORM_SRGB,
464
+ ):
465
+ self._mode = "RGBA"
466
+ if dxgi_format == DXGI_FORMAT.R8G8B8A8_UNORM_SRGB:
467
+ self.info["gamma"] = 1 / 2.2
468
+ else:
469
+ msg = f"Unimplemented DXGI format {dxgi_format}"
470
+ raise NotImplementedError(msg)
471
+ else:
472
+ msg = f"Unimplemented pixel format {repr(fourcc)}"
473
+ raise NotImplementedError(msg)
474
+ else:
475
+ msg = f"Unknown pixel format flags {pfflags}"
476
+ raise NotImplementedError(msg)
477
+
478
+ if n:
479
+ self.tile = [
480
+ ImageFile._Tile("bcn", extents, offset, (n, self.pixel_format))
481
+ ]
482
+ else:
483
+ self.tile = [ImageFile._Tile("raw", extents, 0, rawmode or self.mode)]
484
+
485
+ def load_seek(self, pos: int) -> None:
486
+ pass
487
+
488
+
489
+ class DdsRgbDecoder(ImageFile.PyDecoder):
490
+ _pulls_fd = True
491
+
492
+ def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:
493
+ assert self.fd is not None
494
+ bitcount, masks = self.args
495
+
496
+ # Some masks will be padded with zeros, e.g. R 0b11 G 0b1100
497
+ # Calculate how many zeros each mask is padded with
498
+ mask_offsets = []
499
+ # And the maximum value of each channel without the padding
500
+ mask_totals = []
501
+ for mask in masks:
502
+ offset = 0
503
+ if mask != 0:
504
+ while mask >> (offset + 1) << (offset + 1) == mask:
505
+ offset += 1
506
+ mask_offsets.append(offset)
507
+ mask_totals.append(mask >> offset)
508
+
509
+ data = bytearray()
510
+ bytecount = bitcount // 8
511
+ dest_length = self.state.xsize * self.state.ysize * len(masks)
512
+ while len(data) < dest_length:
513
+ value = int.from_bytes(self.fd.read(bytecount), "little")
514
+ for i, mask in enumerate(masks):
515
+ masked_value = value & mask
516
+ # Remove the zero padding, and scale it to 8 bits
517
+ data += o8(
518
+ int(((masked_value >> mask_offsets[i]) / mask_totals[i]) * 255)
519
+ )
520
+ self.set_as_raw(data)
521
+ return -1, 0
522
+
523
+
524
+ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
525
+ if im.mode not in ("RGB", "RGBA", "L", "LA"):
526
+ msg = f"cannot write mode {im.mode} as DDS"
527
+ raise OSError(msg)
528
+
529
+ flags = DDSD.CAPS | DDSD.HEIGHT | DDSD.WIDTH | DDSD.PIXELFORMAT
530
+ bitcount = len(im.getbands()) * 8
531
+ pixel_format = im.encoderinfo.get("pixel_format")
532
+ args: tuple[int] | str
533
+ if pixel_format:
534
+ codec_name = "bcn"
535
+ flags |= DDSD.LINEARSIZE
536
+ pitch = (im.width + 3) * 4
537
+ rgba_mask = [0, 0, 0, 0]
538
+ pixel_flags = DDPF.FOURCC
539
+ if pixel_format == "DXT1":
540
+ fourcc = D3DFMT.DXT1
541
+ args = (1,)
542
+ elif pixel_format == "DXT3":
543
+ fourcc = D3DFMT.DXT3
544
+ args = (2,)
545
+ elif pixel_format == "DXT5":
546
+ fourcc = D3DFMT.DXT5
547
+ args = (3,)
548
+ else:
549
+ fourcc = D3DFMT.DX10
550
+ if pixel_format == "BC2":
551
+ args = (2,)
552
+ dxgi_format = DXGI_FORMAT.BC2_TYPELESS
553
+ elif pixel_format == "BC3":
554
+ args = (3,)
555
+ dxgi_format = DXGI_FORMAT.BC3_TYPELESS
556
+ elif pixel_format == "BC5":
557
+ args = (5,)
558
+ dxgi_format = DXGI_FORMAT.BC5_TYPELESS
559
+ if im.mode != "RGB":
560
+ msg = "only RGB mode can be written as BC5"
561
+ raise OSError(msg)
562
+ else:
563
+ msg = f"cannot write pixel format {pixel_format}"
564
+ raise OSError(msg)
565
+ else:
566
+ codec_name = "raw"
567
+ flags |= DDSD.PITCH
568
+ pitch = (im.width * bitcount + 7) // 8
569
+
570
+ alpha = im.mode[-1] == "A"
571
+ if im.mode[0] == "L":
572
+ pixel_flags = DDPF.LUMINANCE
573
+ args = im.mode
574
+ if alpha:
575
+ rgba_mask = [0x000000FF, 0x000000FF, 0x000000FF]
576
+ else:
577
+ rgba_mask = [0xFF000000, 0xFF000000, 0xFF000000]
578
+ else:
579
+ pixel_flags = DDPF.RGB
580
+ args = im.mode[::-1]
581
+ rgba_mask = [0x00FF0000, 0x0000FF00, 0x000000FF]
582
+
583
+ if alpha:
584
+ r, g, b, a = im.split()
585
+ im = Image.merge("RGBA", (a, r, g, b))
586
+ if alpha:
587
+ pixel_flags |= DDPF.ALPHAPIXELS
588
+ rgba_mask.append(0xFF000000 if alpha else 0)
589
+
590
+ fourcc = D3DFMT.UNKNOWN
591
+ fp.write(
592
+ o32(DDS_MAGIC)
593
+ + struct.pack(
594
+ "<7I",
595
+ 124, # header size
596
+ flags, # flags
597
+ im.height,
598
+ im.width,
599
+ pitch,
600
+ 0, # depth
601
+ 0, # mipmaps
602
+ )
603
+ + struct.pack("11I", *((0,) * 11)) # reserved
604
+ # pfsize, pfflags, fourcc, bitcount
605
+ + struct.pack("<4I", 32, pixel_flags, fourcc, bitcount)
606
+ + struct.pack("<4I", *rgba_mask) # dwRGBABitMask
607
+ + struct.pack("<5I", DDSCAPS.TEXTURE, 0, 0, 0, 0)
608
+ )
609
+ if fourcc == D3DFMT.DX10:
610
+ fp.write(
611
+ # dxgi_format, 2D resource, misc, array size, straight alpha
612
+ struct.pack("<5I", dxgi_format, 3, 0, 0, 1)
613
+ )
614
+ ImageFile._save(im, fp, [ImageFile._Tile(codec_name, (0, 0) + im.size, 0, args)])
615
+
616
+
617
+ def _accept(prefix: bytes) -> bool:
618
+ return prefix.startswith(b"DDS ")
619
+
620
+
621
+ Image.register_open(DdsImageFile.format, DdsImageFile, _accept)
622
+ Image.register_decoder("dds_rgb", DdsRgbDecoder)
623
+ Image.register_save(DdsImageFile.format, _save)
624
+ Image.register_extension(DdsImageFile.format, ".dds")
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/EpsImagePlugin.py ADDED
@@ -0,0 +1,476 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # EPS file handling
6
+ #
7
+ # History:
8
+ # 1995-09-01 fl Created (0.1)
9
+ # 1996-05-18 fl Don't choke on "atend" fields, Ghostscript interface (0.2)
10
+ # 1996-08-22 fl Don't choke on floating point BoundingBox values
11
+ # 1996-08-23 fl Handle files from Macintosh (0.3)
12
+ # 2001-02-17 fl Use 're' instead of 'regex' (Python 2.1) (0.4)
13
+ # 2003-09-07 fl Check gs.close status (from Federico Di Gregorio) (0.5)
14
+ # 2014-05-07 e Handling of EPS with binary preview and fixed resolution
15
+ # resizing
16
+ #
17
+ # Copyright (c) 1997-2003 by Secret Labs AB.
18
+ # Copyright (c) 1995-2003 by Fredrik Lundh
19
+ #
20
+ # See the README file for information on usage and redistribution.
21
+ #
22
+ from __future__ import annotations
23
+
24
+ import io
25
+ import os
26
+ import re
27
+ import subprocess
28
+ import sys
29
+ import tempfile
30
+ from typing import IO
31
+
32
+ from . import Image, ImageFile
33
+ from ._binary import i32le as i32
34
+
35
+ # --------------------------------------------------------------------
36
+
37
+
38
+ split = re.compile(r"^%%([^:]*):[ \t]*(.*)[ \t]*$")
39
+ field = re.compile(r"^%[%!\w]([^:]*)[ \t]*$")
40
+
41
+ gs_binary: str | bool | None = None
42
+ gs_windows_binary = None
43
+
44
+
45
+ def has_ghostscript() -> bool:
46
+ global gs_binary, gs_windows_binary
47
+ if gs_binary is None:
48
+ if sys.platform.startswith("win"):
49
+ if gs_windows_binary is None:
50
+ import shutil
51
+
52
+ for binary in ("gswin32c", "gswin64c", "gs"):
53
+ if shutil.which(binary) is not None:
54
+ gs_windows_binary = binary
55
+ break
56
+ else:
57
+ gs_windows_binary = False
58
+ gs_binary = gs_windows_binary
59
+ else:
60
+ try:
61
+ subprocess.check_call(["gs", "--version"], stdout=subprocess.DEVNULL)
62
+ gs_binary = "gs"
63
+ except OSError:
64
+ gs_binary = False
65
+ return gs_binary is not False
66
+
67
+
68
+ def Ghostscript(
69
+ tile: list[ImageFile._Tile],
70
+ size: tuple[int, int],
71
+ fp: IO[bytes],
72
+ scale: int = 1,
73
+ transparency: bool = False,
74
+ ) -> Image.core.ImagingCore:
75
+ """Render an image using Ghostscript"""
76
+ global gs_binary
77
+ if not has_ghostscript():
78
+ msg = "Unable to locate Ghostscript on paths"
79
+ raise OSError(msg)
80
+ assert isinstance(gs_binary, str)
81
+
82
+ # Unpack decoder tile
83
+ args = tile[0].args
84
+ assert isinstance(args, tuple)
85
+ length, bbox = args
86
+
87
+ # Hack to support hi-res rendering
88
+ scale = int(scale) or 1
89
+ width = size[0] * scale
90
+ height = size[1] * scale
91
+ # resolution is dependent on bbox and size
92
+ res_x = 72.0 * width / (bbox[2] - bbox[0])
93
+ res_y = 72.0 * height / (bbox[3] - bbox[1])
94
+
95
+ out_fd, outfile = tempfile.mkstemp()
96
+ os.close(out_fd)
97
+
98
+ infile_temp = None
99
+ if hasattr(fp, "name") and os.path.exists(fp.name):
100
+ infile = fp.name
101
+ else:
102
+ in_fd, infile_temp = tempfile.mkstemp()
103
+ os.close(in_fd)
104
+ infile = infile_temp
105
+
106
+ # Ignore length and offset!
107
+ # Ghostscript can read it
108
+ # Copy whole file to read in Ghostscript
109
+ with open(infile_temp, "wb") as f:
110
+ # fetch length of fp
111
+ fp.seek(0, io.SEEK_END)
112
+ fsize = fp.tell()
113
+ # ensure start position
114
+ # go back
115
+ fp.seek(0)
116
+ lengthfile = fsize
117
+ while lengthfile > 0:
118
+ s = fp.read(min(lengthfile, 100 * 1024))
119
+ if not s:
120
+ break
121
+ lengthfile -= len(s)
122
+ f.write(s)
123
+
124
+ if transparency:
125
+ # "RGBA"
126
+ device = "pngalpha"
127
+ else:
128
+ # "pnmraw" automatically chooses between
129
+ # PBM ("1"), PGM ("L"), and PPM ("RGB").
130
+ device = "pnmraw"
131
+
132
+ # Build Ghostscript command
133
+ command = [
134
+ gs_binary,
135
+ "-q", # quiet mode
136
+ f"-g{width:d}x{height:d}", # set output geometry (pixels)
137
+ f"-r{res_x:f}x{res_y:f}", # set input DPI (dots per inch)
138
+ "-dBATCH", # exit after processing
139
+ "-dNOPAUSE", # don't pause between pages
140
+ "-dSAFER", # safe mode
141
+ f"-sDEVICE={device}",
142
+ f"-sOutputFile={outfile}", # output file
143
+ # adjust for image origin
144
+ "-c",
145
+ f"{-bbox[0]} {-bbox[1]} translate",
146
+ "-f",
147
+ infile, # input file
148
+ # showpage (see https://bugs.ghostscript.com/show_bug.cgi?id=698272)
149
+ "-c",
150
+ "showpage",
151
+ ]
152
+
153
+ # push data through Ghostscript
154
+ try:
155
+ startupinfo = None
156
+ if sys.platform.startswith("win"):
157
+ startupinfo = subprocess.STARTUPINFO()
158
+ startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
159
+ subprocess.check_call(command, startupinfo=startupinfo)
160
+ with Image.open(outfile) as out_im:
161
+ out_im.load()
162
+ return out_im.im.copy()
163
+ finally:
164
+ try:
165
+ os.unlink(outfile)
166
+ if infile_temp:
167
+ os.unlink(infile_temp)
168
+ except OSError:
169
+ pass
170
+
171
+
172
+ def _accept(prefix: bytes) -> bool:
173
+ return prefix.startswith(b"%!PS") or (
174
+ len(prefix) >= 4 and i32(prefix) == 0xC6D3D0C5
175
+ )
176
+
177
+
178
+ ##
179
+ # Image plugin for Encapsulated PostScript. This plugin supports only
180
+ # a few variants of this format.
181
+
182
+
183
+ class EpsImageFile(ImageFile.ImageFile):
184
+ """EPS File Parser for the Python Imaging Library"""
185
+
186
+ format = "EPS"
187
+ format_description = "Encapsulated Postscript"
188
+
189
+ mode_map = {1: "L", 2: "LAB", 3: "RGB", 4: "CMYK"}
190
+
191
+ def _open(self) -> None:
192
+ (length, offset) = self._find_offset(self.fp)
193
+
194
+ # go to offset - start of "%!PS"
195
+ self.fp.seek(offset)
196
+
197
+ self._mode = "RGB"
198
+
199
+ # When reading header comments, the first comment is used.
200
+ # When reading trailer comments, the last comment is used.
201
+ bounding_box: list[int] | None = None
202
+ imagedata_size: tuple[int, int] | None = None
203
+
204
+ byte_arr = bytearray(255)
205
+ bytes_mv = memoryview(byte_arr)
206
+ bytes_read = 0
207
+ reading_header_comments = True
208
+ reading_trailer_comments = False
209
+ trailer_reached = False
210
+
211
+ def check_required_header_comments() -> None:
212
+ """
213
+ The EPS specification requires that some headers exist.
214
+ This should be checked when the header comments formally end,
215
+ when image data starts, or when the file ends, whichever comes first.
216
+ """
217
+ if "PS-Adobe" not in self.info:
218
+ msg = 'EPS header missing "%!PS-Adobe" comment'
219
+ raise SyntaxError(msg)
220
+ if "BoundingBox" not in self.info:
221
+ msg = 'EPS header missing "%%BoundingBox" comment'
222
+ raise SyntaxError(msg)
223
+
224
+ def read_comment(s: str) -> bool:
225
+ nonlocal bounding_box, reading_trailer_comments
226
+ try:
227
+ m = split.match(s)
228
+ except re.error as e:
229
+ msg = "not an EPS file"
230
+ raise SyntaxError(msg) from e
231
+
232
+ if not m:
233
+ return False
234
+
235
+ k, v = m.group(1, 2)
236
+ self.info[k] = v
237
+ if k == "BoundingBox":
238
+ if v == "(atend)":
239
+ reading_trailer_comments = True
240
+ elif not bounding_box or (trailer_reached and reading_trailer_comments):
241
+ try:
242
+ # Note: The DSC spec says that BoundingBox
243
+ # fields should be integers, but some drivers
244
+ # put floating point values there anyway.
245
+ bounding_box = [int(float(i)) for i in v.split()]
246
+ except Exception:
247
+ pass
248
+ return True
249
+
250
+ while True:
251
+ byte = self.fp.read(1)
252
+ if byte == b"":
253
+ # if we didn't read a byte we must be at the end of the file
254
+ if bytes_read == 0:
255
+ if reading_header_comments:
256
+ check_required_header_comments()
257
+ break
258
+ elif byte in b"\r\n":
259
+ # if we read a line ending character, ignore it and parse what
260
+ # we have already read. if we haven't read any other characters,
261
+ # continue reading
262
+ if bytes_read == 0:
263
+ continue
264
+ else:
265
+ # ASCII/hexadecimal lines in an EPS file must not exceed
266
+ # 255 characters, not including line ending characters
267
+ if bytes_read >= 255:
268
+ # only enforce this for lines starting with a "%",
269
+ # otherwise assume it's binary data
270
+ if byte_arr[0] == ord("%"):
271
+ msg = "not an EPS file"
272
+ raise SyntaxError(msg)
273
+ else:
274
+ if reading_header_comments:
275
+ check_required_header_comments()
276
+ reading_header_comments = False
277
+ # reset bytes_read so we can keep reading
278
+ # data until the end of the line
279
+ bytes_read = 0
280
+ byte_arr[bytes_read] = byte[0]
281
+ bytes_read += 1
282
+ continue
283
+
284
+ if reading_header_comments:
285
+ # Load EPS header
286
+
287
+ # if this line doesn't start with a "%",
288
+ # or does start with "%%EndComments",
289
+ # then we've reached the end of the header/comments
290
+ if byte_arr[0] != ord("%") or bytes_mv[:13] == b"%%EndComments":
291
+ check_required_header_comments()
292
+ reading_header_comments = False
293
+ continue
294
+
295
+ s = str(bytes_mv[:bytes_read], "latin-1")
296
+ if not read_comment(s):
297
+ m = field.match(s)
298
+ if m:
299
+ k = m.group(1)
300
+ if k.startswith("PS-Adobe"):
301
+ self.info["PS-Adobe"] = k[9:]
302
+ else:
303
+ self.info[k] = ""
304
+ elif s[0] == "%":
305
+ # handle non-DSC PostScript comments that some
306
+ # tools mistakenly put in the Comments section
307
+ pass
308
+ else:
309
+ msg = "bad EPS header"
310
+ raise OSError(msg)
311
+ elif bytes_mv[:11] == b"%ImageData:":
312
+ # Check for an "ImageData" descriptor
313
+ # https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#50577413_pgfId-1035096
314
+
315
+ # If we've already read an "ImageData" descriptor,
316
+ # don't read another one.
317
+ if imagedata_size:
318
+ bytes_read = 0
319
+ continue
320
+
321
+ # Values:
322
+ # columns
323
+ # rows
324
+ # bit depth (1 or 8)
325
+ # mode (1: L, 2: LAB, 3: RGB, 4: CMYK)
326
+ # number of padding channels
327
+ # block size (number of bytes per row per channel)
328
+ # binary/ascii (1: binary, 2: ascii)
329
+ # data start identifier (the image data follows after a single line
330
+ # consisting only of this quoted value)
331
+ image_data_values = byte_arr[11:bytes_read].split(None, 7)
332
+ columns, rows, bit_depth, mode_id = (
333
+ int(value) for value in image_data_values[:4]
334
+ )
335
+
336
+ if bit_depth == 1:
337
+ self._mode = "1"
338
+ elif bit_depth == 8:
339
+ try:
340
+ self._mode = self.mode_map[mode_id]
341
+ except ValueError:
342
+ break
343
+ else:
344
+ break
345
+
346
+ # Parse the columns and rows after checking the bit depth and mode
347
+ # in case the bit depth and/or mode are invalid.
348
+ imagedata_size = columns, rows
349
+ elif bytes_mv[:5] == b"%%EOF":
350
+ break
351
+ elif trailer_reached and reading_trailer_comments:
352
+ # Load EPS trailer
353
+ s = str(bytes_mv[:bytes_read], "latin-1")
354
+ read_comment(s)
355
+ elif bytes_mv[:9] == b"%%Trailer":
356
+ trailer_reached = True
357
+ bytes_read = 0
358
+
359
+ # A "BoundingBox" is always required,
360
+ # even if an "ImageData" descriptor size exists.
361
+ if not bounding_box:
362
+ msg = "cannot determine EPS bounding box"
363
+ raise OSError(msg)
364
+
365
+ # An "ImageData" size takes precedence over the "BoundingBox".
366
+ self._size = imagedata_size or (
367
+ bounding_box[2] - bounding_box[0],
368
+ bounding_box[3] - bounding_box[1],
369
+ )
370
+
371
+ self.tile = [
372
+ ImageFile._Tile("eps", (0, 0) + self.size, offset, (length, bounding_box))
373
+ ]
374
+
375
+ def _find_offset(self, fp: IO[bytes]) -> tuple[int, int]:
376
+ s = fp.read(4)
377
+
378
+ if s == b"%!PS":
379
+ # for HEAD without binary preview
380
+ fp.seek(0, io.SEEK_END)
381
+ length = fp.tell()
382
+ offset = 0
383
+ elif i32(s) == 0xC6D3D0C5:
384
+ # FIX for: Some EPS file not handled correctly / issue #302
385
+ # EPS can contain binary data
386
+ # or start directly with latin coding
387
+ # more info see:
388
+ # https://web.archive.org/web/20160528181353/http://partners.adobe.com/public/developer/en/ps/5002.EPSF_Spec.pdf
389
+ s = fp.read(8)
390
+ offset = i32(s)
391
+ length = i32(s, 4)
392
+ else:
393
+ msg = "not an EPS file"
394
+ raise SyntaxError(msg)
395
+
396
+ return length, offset
397
+
398
+ def load(
399
+ self, scale: int = 1, transparency: bool = False
400
+ ) -> Image.core.PixelAccess | None:
401
+ # Load EPS via Ghostscript
402
+ if self.tile:
403
+ self.im = Ghostscript(self.tile, self.size, self.fp, scale, transparency)
404
+ self._mode = self.im.mode
405
+ self._size = self.im.size
406
+ self.tile = []
407
+ return Image.Image.load(self)
408
+
409
+ def load_seek(self, pos: int) -> None:
410
+ # we can't incrementally load, so force ImageFile.parser to
411
+ # use our custom load method by defining this method.
412
+ pass
413
+
414
+
415
+ # --------------------------------------------------------------------
416
+
417
+
418
+ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes, eps: int = 1) -> None:
419
+ """EPS Writer for the Python Imaging Library."""
420
+
421
+ # make sure image data is available
422
+ im.load()
423
+
424
+ # determine PostScript image mode
425
+ if im.mode == "L":
426
+ operator = (8, 1, b"image")
427
+ elif im.mode == "RGB":
428
+ operator = (8, 3, b"false 3 colorimage")
429
+ elif im.mode == "CMYK":
430
+ operator = (8, 4, b"false 4 colorimage")
431
+ else:
432
+ msg = "image mode is not supported"
433
+ raise ValueError(msg)
434
+
435
+ if eps:
436
+ # write EPS header
437
+ fp.write(b"%!PS-Adobe-3.0 EPSF-3.0\n")
438
+ fp.write(b"%%Creator: PIL 0.1 EpsEncode\n")
439
+ # fp.write("%%CreationDate: %s"...)
440
+ fp.write(b"%%%%BoundingBox: 0 0 %d %d\n" % im.size)
441
+ fp.write(b"%%Pages: 1\n")
442
+ fp.write(b"%%EndComments\n")
443
+ fp.write(b"%%Page: 1 1\n")
444
+ fp.write(b"%%ImageData: %d %d " % im.size)
445
+ fp.write(b'%d %d 0 1 1 "%s"\n' % operator)
446
+
447
+ # image header
448
+ fp.write(b"gsave\n")
449
+ fp.write(b"10 dict begin\n")
450
+ fp.write(b"/buf %d string def\n" % (im.size[0] * operator[1]))
451
+ fp.write(b"%d %d scale\n" % im.size)
452
+ fp.write(b"%d %d 8\n" % im.size) # <= bits
453
+ fp.write(b"[%d 0 0 -%d 0 %d]\n" % (im.size[0], im.size[1], im.size[1]))
454
+ fp.write(b"{ currentfile buf readhexstring pop } bind\n")
455
+ fp.write(operator[2] + b"\n")
456
+ if hasattr(fp, "flush"):
457
+ fp.flush()
458
+
459
+ ImageFile._save(im, fp, [ImageFile._Tile("eps", (0, 0) + im.size)])
460
+
461
+ fp.write(b"\n%%%%EndBinary\n")
462
+ fp.write(b"grestore end\n")
463
+ if hasattr(fp, "flush"):
464
+ fp.flush()
465
+
466
+
467
+ # --------------------------------------------------------------------
468
+
469
+
470
+ Image.register_open(EpsImageFile.format, EpsImageFile, _accept)
471
+
472
+ Image.register_save(EpsImageFile.format, _save)
473
+
474
+ Image.register_extensions(EpsImageFile.format, [".ps", ".eps"])
475
+
476
+ Image.register_mime(EpsImageFile.format, "application/postscript")
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/ExifTags.py ADDED
@@ -0,0 +1,382 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # EXIF tags
6
+ #
7
+ # Copyright (c) 2003 by Secret Labs AB
8
+ #
9
+ # See the README file for information on usage and redistribution.
10
+ #
11
+
12
+ """
13
+ This module provides constants and clear-text names for various
14
+ well-known EXIF tags.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ from enum import IntEnum
19
+
20
+
21
+ class Base(IntEnum):
22
+ # possibly incomplete
23
+ InteropIndex = 0x0001
24
+ ProcessingSoftware = 0x000B
25
+ NewSubfileType = 0x00FE
26
+ SubfileType = 0x00FF
27
+ ImageWidth = 0x0100
28
+ ImageLength = 0x0101
29
+ BitsPerSample = 0x0102
30
+ Compression = 0x0103
31
+ PhotometricInterpretation = 0x0106
32
+ Thresholding = 0x0107
33
+ CellWidth = 0x0108
34
+ CellLength = 0x0109
35
+ FillOrder = 0x010A
36
+ DocumentName = 0x010D
37
+ ImageDescription = 0x010E
38
+ Make = 0x010F
39
+ Model = 0x0110
40
+ StripOffsets = 0x0111
41
+ Orientation = 0x0112
42
+ SamplesPerPixel = 0x0115
43
+ RowsPerStrip = 0x0116
44
+ StripByteCounts = 0x0117
45
+ MinSampleValue = 0x0118
46
+ MaxSampleValue = 0x0119
47
+ XResolution = 0x011A
48
+ YResolution = 0x011B
49
+ PlanarConfiguration = 0x011C
50
+ PageName = 0x011D
51
+ FreeOffsets = 0x0120
52
+ FreeByteCounts = 0x0121
53
+ GrayResponseUnit = 0x0122
54
+ GrayResponseCurve = 0x0123
55
+ T4Options = 0x0124
56
+ T6Options = 0x0125
57
+ ResolutionUnit = 0x0128
58
+ PageNumber = 0x0129
59
+ TransferFunction = 0x012D
60
+ Software = 0x0131
61
+ DateTime = 0x0132
62
+ Artist = 0x013B
63
+ HostComputer = 0x013C
64
+ Predictor = 0x013D
65
+ WhitePoint = 0x013E
66
+ PrimaryChromaticities = 0x013F
67
+ ColorMap = 0x0140
68
+ HalftoneHints = 0x0141
69
+ TileWidth = 0x0142
70
+ TileLength = 0x0143
71
+ TileOffsets = 0x0144
72
+ TileByteCounts = 0x0145
73
+ SubIFDs = 0x014A
74
+ InkSet = 0x014C
75
+ InkNames = 0x014D
76
+ NumberOfInks = 0x014E
77
+ DotRange = 0x0150
78
+ TargetPrinter = 0x0151
79
+ ExtraSamples = 0x0152
80
+ SampleFormat = 0x0153
81
+ SMinSampleValue = 0x0154
82
+ SMaxSampleValue = 0x0155
83
+ TransferRange = 0x0156
84
+ ClipPath = 0x0157
85
+ XClipPathUnits = 0x0158
86
+ YClipPathUnits = 0x0159
87
+ Indexed = 0x015A
88
+ JPEGTables = 0x015B
89
+ OPIProxy = 0x015F
90
+ JPEGProc = 0x0200
91
+ JpegIFOffset = 0x0201
92
+ JpegIFByteCount = 0x0202
93
+ JpegRestartInterval = 0x0203
94
+ JpegLosslessPredictors = 0x0205
95
+ JpegPointTransforms = 0x0206
96
+ JpegQTables = 0x0207
97
+ JpegDCTables = 0x0208
98
+ JpegACTables = 0x0209
99
+ YCbCrCoefficients = 0x0211
100
+ YCbCrSubSampling = 0x0212
101
+ YCbCrPositioning = 0x0213
102
+ ReferenceBlackWhite = 0x0214
103
+ XMLPacket = 0x02BC
104
+ RelatedImageFileFormat = 0x1000
105
+ RelatedImageWidth = 0x1001
106
+ RelatedImageLength = 0x1002
107
+ Rating = 0x4746
108
+ RatingPercent = 0x4749
109
+ ImageID = 0x800D
110
+ CFARepeatPatternDim = 0x828D
111
+ BatteryLevel = 0x828F
112
+ Copyright = 0x8298
113
+ ExposureTime = 0x829A
114
+ FNumber = 0x829D
115
+ IPTCNAA = 0x83BB
116
+ ImageResources = 0x8649
117
+ ExifOffset = 0x8769
118
+ InterColorProfile = 0x8773
119
+ ExposureProgram = 0x8822
120
+ SpectralSensitivity = 0x8824
121
+ GPSInfo = 0x8825
122
+ ISOSpeedRatings = 0x8827
123
+ OECF = 0x8828
124
+ Interlace = 0x8829
125
+ TimeZoneOffset = 0x882A
126
+ SelfTimerMode = 0x882B
127
+ SensitivityType = 0x8830
128
+ StandardOutputSensitivity = 0x8831
129
+ RecommendedExposureIndex = 0x8832
130
+ ISOSpeed = 0x8833
131
+ ISOSpeedLatitudeyyy = 0x8834
132
+ ISOSpeedLatitudezzz = 0x8835
133
+ ExifVersion = 0x9000
134
+ DateTimeOriginal = 0x9003
135
+ DateTimeDigitized = 0x9004
136
+ OffsetTime = 0x9010
137
+ OffsetTimeOriginal = 0x9011
138
+ OffsetTimeDigitized = 0x9012
139
+ ComponentsConfiguration = 0x9101
140
+ CompressedBitsPerPixel = 0x9102
141
+ ShutterSpeedValue = 0x9201
142
+ ApertureValue = 0x9202
143
+ BrightnessValue = 0x9203
144
+ ExposureBiasValue = 0x9204
145
+ MaxApertureValue = 0x9205
146
+ SubjectDistance = 0x9206
147
+ MeteringMode = 0x9207
148
+ LightSource = 0x9208
149
+ Flash = 0x9209
150
+ FocalLength = 0x920A
151
+ Noise = 0x920D
152
+ ImageNumber = 0x9211
153
+ SecurityClassification = 0x9212
154
+ ImageHistory = 0x9213
155
+ TIFFEPStandardID = 0x9216
156
+ MakerNote = 0x927C
157
+ UserComment = 0x9286
158
+ SubsecTime = 0x9290
159
+ SubsecTimeOriginal = 0x9291
160
+ SubsecTimeDigitized = 0x9292
161
+ AmbientTemperature = 0x9400
162
+ Humidity = 0x9401
163
+ Pressure = 0x9402
164
+ WaterDepth = 0x9403
165
+ Acceleration = 0x9404
166
+ CameraElevationAngle = 0x9405
167
+ XPTitle = 0x9C9B
168
+ XPComment = 0x9C9C
169
+ XPAuthor = 0x9C9D
170
+ XPKeywords = 0x9C9E
171
+ XPSubject = 0x9C9F
172
+ FlashPixVersion = 0xA000
173
+ ColorSpace = 0xA001
174
+ ExifImageWidth = 0xA002
175
+ ExifImageHeight = 0xA003
176
+ RelatedSoundFile = 0xA004
177
+ ExifInteroperabilityOffset = 0xA005
178
+ FlashEnergy = 0xA20B
179
+ SpatialFrequencyResponse = 0xA20C
180
+ FocalPlaneXResolution = 0xA20E
181
+ FocalPlaneYResolution = 0xA20F
182
+ FocalPlaneResolutionUnit = 0xA210
183
+ SubjectLocation = 0xA214
184
+ ExposureIndex = 0xA215
185
+ SensingMethod = 0xA217
186
+ FileSource = 0xA300
187
+ SceneType = 0xA301
188
+ CFAPattern = 0xA302
189
+ CustomRendered = 0xA401
190
+ ExposureMode = 0xA402
191
+ WhiteBalance = 0xA403
192
+ DigitalZoomRatio = 0xA404
193
+ FocalLengthIn35mmFilm = 0xA405
194
+ SceneCaptureType = 0xA406
195
+ GainControl = 0xA407
196
+ Contrast = 0xA408
197
+ Saturation = 0xA409
198
+ Sharpness = 0xA40A
199
+ DeviceSettingDescription = 0xA40B
200
+ SubjectDistanceRange = 0xA40C
201
+ ImageUniqueID = 0xA420
202
+ CameraOwnerName = 0xA430
203
+ BodySerialNumber = 0xA431
204
+ LensSpecification = 0xA432
205
+ LensMake = 0xA433
206
+ LensModel = 0xA434
207
+ LensSerialNumber = 0xA435
208
+ CompositeImage = 0xA460
209
+ CompositeImageCount = 0xA461
210
+ CompositeImageExposureTimes = 0xA462
211
+ Gamma = 0xA500
212
+ PrintImageMatching = 0xC4A5
213
+ DNGVersion = 0xC612
214
+ DNGBackwardVersion = 0xC613
215
+ UniqueCameraModel = 0xC614
216
+ LocalizedCameraModel = 0xC615
217
+ CFAPlaneColor = 0xC616
218
+ CFALayout = 0xC617
219
+ LinearizationTable = 0xC618
220
+ BlackLevelRepeatDim = 0xC619
221
+ BlackLevel = 0xC61A
222
+ BlackLevelDeltaH = 0xC61B
223
+ BlackLevelDeltaV = 0xC61C
224
+ WhiteLevel = 0xC61D
225
+ DefaultScale = 0xC61E
226
+ DefaultCropOrigin = 0xC61F
227
+ DefaultCropSize = 0xC620
228
+ ColorMatrix1 = 0xC621
229
+ ColorMatrix2 = 0xC622
230
+ CameraCalibration1 = 0xC623
231
+ CameraCalibration2 = 0xC624
232
+ ReductionMatrix1 = 0xC625
233
+ ReductionMatrix2 = 0xC626
234
+ AnalogBalance = 0xC627
235
+ AsShotNeutral = 0xC628
236
+ AsShotWhiteXY = 0xC629
237
+ BaselineExposure = 0xC62A
238
+ BaselineNoise = 0xC62B
239
+ BaselineSharpness = 0xC62C
240
+ BayerGreenSplit = 0xC62D
241
+ LinearResponseLimit = 0xC62E
242
+ CameraSerialNumber = 0xC62F
243
+ LensInfo = 0xC630
244
+ ChromaBlurRadius = 0xC631
245
+ AntiAliasStrength = 0xC632
246
+ ShadowScale = 0xC633
247
+ DNGPrivateData = 0xC634
248
+ MakerNoteSafety = 0xC635
249
+ CalibrationIlluminant1 = 0xC65A
250
+ CalibrationIlluminant2 = 0xC65B
251
+ BestQualityScale = 0xC65C
252
+ RawDataUniqueID = 0xC65D
253
+ OriginalRawFileName = 0xC68B
254
+ OriginalRawFileData = 0xC68C
255
+ ActiveArea = 0xC68D
256
+ MaskedAreas = 0xC68E
257
+ AsShotICCProfile = 0xC68F
258
+ AsShotPreProfileMatrix = 0xC690
259
+ CurrentICCProfile = 0xC691
260
+ CurrentPreProfileMatrix = 0xC692
261
+ ColorimetricReference = 0xC6BF
262
+ CameraCalibrationSignature = 0xC6F3
263
+ ProfileCalibrationSignature = 0xC6F4
264
+ AsShotProfileName = 0xC6F6
265
+ NoiseReductionApplied = 0xC6F7
266
+ ProfileName = 0xC6F8
267
+ ProfileHueSatMapDims = 0xC6F9
268
+ ProfileHueSatMapData1 = 0xC6FA
269
+ ProfileHueSatMapData2 = 0xC6FB
270
+ ProfileToneCurve = 0xC6FC
271
+ ProfileEmbedPolicy = 0xC6FD
272
+ ProfileCopyright = 0xC6FE
273
+ ForwardMatrix1 = 0xC714
274
+ ForwardMatrix2 = 0xC715
275
+ PreviewApplicationName = 0xC716
276
+ PreviewApplicationVersion = 0xC717
277
+ PreviewSettingsName = 0xC718
278
+ PreviewSettingsDigest = 0xC719
279
+ PreviewColorSpace = 0xC71A
280
+ PreviewDateTime = 0xC71B
281
+ RawImageDigest = 0xC71C
282
+ OriginalRawFileDigest = 0xC71D
283
+ SubTileBlockSize = 0xC71E
284
+ RowInterleaveFactor = 0xC71F
285
+ ProfileLookTableDims = 0xC725
286
+ ProfileLookTableData = 0xC726
287
+ OpcodeList1 = 0xC740
288
+ OpcodeList2 = 0xC741
289
+ OpcodeList3 = 0xC74E
290
+ NoiseProfile = 0xC761
291
+
292
+
293
+ """Maps EXIF tags to tag names."""
294
+ TAGS = {
295
+ **{i.value: i.name for i in Base},
296
+ 0x920C: "SpatialFrequencyResponse",
297
+ 0x9214: "SubjectLocation",
298
+ 0x9215: "ExposureIndex",
299
+ 0x828E: "CFAPattern",
300
+ 0x920B: "FlashEnergy",
301
+ 0x9216: "TIFF/EPStandardID",
302
+ }
303
+
304
+
305
+ class GPS(IntEnum):
306
+ GPSVersionID = 0x00
307
+ GPSLatitudeRef = 0x01
308
+ GPSLatitude = 0x02
309
+ GPSLongitudeRef = 0x03
310
+ GPSLongitude = 0x04
311
+ GPSAltitudeRef = 0x05
312
+ GPSAltitude = 0x06
313
+ GPSTimeStamp = 0x07
314
+ GPSSatellites = 0x08
315
+ GPSStatus = 0x09
316
+ GPSMeasureMode = 0x0A
317
+ GPSDOP = 0x0B
318
+ GPSSpeedRef = 0x0C
319
+ GPSSpeed = 0x0D
320
+ GPSTrackRef = 0x0E
321
+ GPSTrack = 0x0F
322
+ GPSImgDirectionRef = 0x10
323
+ GPSImgDirection = 0x11
324
+ GPSMapDatum = 0x12
325
+ GPSDestLatitudeRef = 0x13
326
+ GPSDestLatitude = 0x14
327
+ GPSDestLongitudeRef = 0x15
328
+ GPSDestLongitude = 0x16
329
+ GPSDestBearingRef = 0x17
330
+ GPSDestBearing = 0x18
331
+ GPSDestDistanceRef = 0x19
332
+ GPSDestDistance = 0x1A
333
+ GPSProcessingMethod = 0x1B
334
+ GPSAreaInformation = 0x1C
335
+ GPSDateStamp = 0x1D
336
+ GPSDifferential = 0x1E
337
+ GPSHPositioningError = 0x1F
338
+
339
+
340
+ """Maps EXIF GPS tags to tag names."""
341
+ GPSTAGS = {i.value: i.name for i in GPS}
342
+
343
+
344
+ class Interop(IntEnum):
345
+ InteropIndex = 0x0001
346
+ InteropVersion = 0x0002
347
+ RelatedImageFileFormat = 0x1000
348
+ RelatedImageWidth = 0x1001
349
+ RelatedImageHeight = 0x1002
350
+
351
+
352
+ class IFD(IntEnum):
353
+ Exif = 0x8769
354
+ GPSInfo = 0x8825
355
+ MakerNote = 0x927C
356
+ Makernote = 0x927C # Deprecated
357
+ Interop = 0xA005
358
+ IFD1 = -1
359
+
360
+
361
+ class LightSource(IntEnum):
362
+ Unknown = 0x00
363
+ Daylight = 0x01
364
+ Fluorescent = 0x02
365
+ Tungsten = 0x03
366
+ Flash = 0x04
367
+ Fine = 0x09
368
+ Cloudy = 0x0A
369
+ Shade = 0x0B
370
+ DaylightFluorescent = 0x0C
371
+ DayWhiteFluorescent = 0x0D
372
+ CoolWhiteFluorescent = 0x0E
373
+ WhiteFluorescent = 0x0F
374
+ StandardLightA = 0x11
375
+ StandardLightB = 0x12
376
+ StandardLightC = 0x13
377
+ D55 = 0x14
378
+ D65 = 0x15
379
+ D75 = 0x16
380
+ D50 = 0x17
381
+ ISO = 0x18
382
+ Other = 0xFF
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/FitsImagePlugin.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library
3
+ # $Id$
4
+ #
5
+ # FITS file handling
6
+ #
7
+ # Copyright (c) 1998-2003 by Fredrik Lundh
8
+ #
9
+ # See the README file for information on usage and redistribution.
10
+ #
11
+ from __future__ import annotations
12
+
13
+ import gzip
14
+ import math
15
+
16
+ from . import Image, ImageFile
17
+
18
+
19
+ def _accept(prefix: bytes) -> bool:
20
+ return prefix.startswith(b"SIMPLE")
21
+
22
+
23
+ class FitsImageFile(ImageFile.ImageFile):
24
+ format = "FITS"
25
+ format_description = "FITS"
26
+
27
+ def _open(self) -> None:
28
+ assert self.fp is not None
29
+
30
+ headers: dict[bytes, bytes] = {}
31
+ header_in_progress = False
32
+ decoder_name = ""
33
+ while True:
34
+ header = self.fp.read(80)
35
+ if not header:
36
+ msg = "Truncated FITS file"
37
+ raise OSError(msg)
38
+ keyword = header[:8].strip()
39
+ if keyword in (b"SIMPLE", b"XTENSION"):
40
+ header_in_progress = True
41
+ elif headers and not header_in_progress:
42
+ # This is now a data unit
43
+ break
44
+ elif keyword == b"END":
45
+ # Seek to the end of the header unit
46
+ self.fp.seek(math.ceil(self.fp.tell() / 2880) * 2880)
47
+ if not decoder_name:
48
+ decoder_name, offset, args = self._parse_headers(headers)
49
+
50
+ header_in_progress = False
51
+ continue
52
+
53
+ if decoder_name:
54
+ # Keep going to read past the headers
55
+ continue
56
+
57
+ value = header[8:].split(b"/")[0].strip()
58
+ if value.startswith(b"="):
59
+ value = value[1:].strip()
60
+ if not headers and (not _accept(keyword) or value != b"T"):
61
+ msg = "Not a FITS file"
62
+ raise SyntaxError(msg)
63
+ headers[keyword] = value
64
+
65
+ if not decoder_name:
66
+ msg = "No image data"
67
+ raise ValueError(msg)
68
+
69
+ offset += self.fp.tell() - 80
70
+ self.tile = [ImageFile._Tile(decoder_name, (0, 0) + self.size, offset, args)]
71
+
72
+ def _get_size(
73
+ self, headers: dict[bytes, bytes], prefix: bytes
74
+ ) -> tuple[int, int] | None:
75
+ naxis = int(headers[prefix + b"NAXIS"])
76
+ if naxis == 0:
77
+ return None
78
+
79
+ if naxis == 1:
80
+ return 1, int(headers[prefix + b"NAXIS1"])
81
+ else:
82
+ return int(headers[prefix + b"NAXIS1"]), int(headers[prefix + b"NAXIS2"])
83
+
84
+ def _parse_headers(
85
+ self, headers: dict[bytes, bytes]
86
+ ) -> tuple[str, int, tuple[str | int, ...]]:
87
+ prefix = b""
88
+ decoder_name = "raw"
89
+ offset = 0
90
+ if (
91
+ headers.get(b"XTENSION") == b"'BINTABLE'"
92
+ and headers.get(b"ZIMAGE") == b"T"
93
+ and headers[b"ZCMPTYPE"] == b"'GZIP_1 '"
94
+ ):
95
+ no_prefix_size = self._get_size(headers, prefix) or (0, 0)
96
+ number_of_bits = int(headers[b"BITPIX"])
97
+ offset = no_prefix_size[0] * no_prefix_size[1] * (number_of_bits // 8)
98
+
99
+ prefix = b"Z"
100
+ decoder_name = "fits_gzip"
101
+
102
+ size = self._get_size(headers, prefix)
103
+ if not size:
104
+ return "", 0, ()
105
+
106
+ self._size = size
107
+
108
+ number_of_bits = int(headers[prefix + b"BITPIX"])
109
+ if number_of_bits == 8:
110
+ self._mode = "L"
111
+ elif number_of_bits == 16:
112
+ self._mode = "I;16"
113
+ elif number_of_bits == 32:
114
+ self._mode = "I"
115
+ elif number_of_bits in (-32, -64):
116
+ self._mode = "F"
117
+
118
+ args: tuple[str | int, ...]
119
+ if decoder_name == "raw":
120
+ args = (self.mode, 0, -1)
121
+ else:
122
+ args = (number_of_bits,)
123
+ return decoder_name, offset, args
124
+
125
+
126
+ class FitsGzipDecoder(ImageFile.PyDecoder):
127
+ _pulls_fd = True
128
+
129
+ def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:
130
+ assert self.fd is not None
131
+ value = gzip.decompress(self.fd.read())
132
+
133
+ rows = []
134
+ offset = 0
135
+ number_of_bits = min(self.args[0] // 8, 4)
136
+ for y in range(self.state.ysize):
137
+ row = bytearray()
138
+ for x in range(self.state.xsize):
139
+ row += value[offset + (4 - number_of_bits) : offset + 4]
140
+ offset += 4
141
+ rows.append(row)
142
+ self.set_as_raw(bytes([pixel for row in rows[::-1] for pixel in row]))
143
+ return -1, 0
144
+
145
+
146
+ # --------------------------------------------------------------------
147
+ # Registry
148
+
149
+ Image.register_open(FitsImageFile.format, FitsImageFile, _accept)
150
+ Image.register_decoder("fits_gzip", FitsGzipDecoder)
151
+
152
+ Image.register_extensions(FitsImageFile.format, [".fit", ".fits"])
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/FliImagePlugin.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # FLI/FLC file handling.
6
+ #
7
+ # History:
8
+ # 95-09-01 fl Created
9
+ # 97-01-03 fl Fixed parser, setup decoder tile
10
+ # 98-07-15 fl Renamed offset attribute to avoid name clash
11
+ #
12
+ # Copyright (c) Secret Labs AB 1997-98.
13
+ # Copyright (c) Fredrik Lundh 1995-97.
14
+ #
15
+ # See the README file for information on usage and redistribution.
16
+ #
17
+ from __future__ import annotations
18
+
19
+ import os
20
+
21
+ from . import Image, ImageFile, ImagePalette
22
+ from ._binary import i16le as i16
23
+ from ._binary import i32le as i32
24
+ from ._binary import o8
25
+ from ._util import DeferredError
26
+
27
+ #
28
+ # decoder
29
+
30
+
31
+ def _accept(prefix: bytes) -> bool:
32
+ return (
33
+ len(prefix) >= 6
34
+ and i16(prefix, 4) in [0xAF11, 0xAF12]
35
+ and i16(prefix, 14) in [0, 3] # flags
36
+ )
37
+
38
+
39
+ ##
40
+ # Image plugin for the FLI/FLC animation format. Use the <b>seek</b>
41
+ # method to load individual frames.
42
+
43
+
44
+ class FliImageFile(ImageFile.ImageFile):
45
+ format = "FLI"
46
+ format_description = "Autodesk FLI/FLC Animation"
47
+ _close_exclusive_fp_after_loading = False
48
+
49
+ def _open(self) -> None:
50
+ # HEAD
51
+ s = self.fp.read(128)
52
+ if not (_accept(s) and s[20:22] == b"\x00\x00"):
53
+ msg = "not an FLI/FLC file"
54
+ raise SyntaxError(msg)
55
+
56
+ # frames
57
+ self.n_frames = i16(s, 6)
58
+ self.is_animated = self.n_frames > 1
59
+
60
+ # image characteristics
61
+ self._mode = "P"
62
+ self._size = i16(s, 8), i16(s, 10)
63
+
64
+ # animation speed
65
+ duration = i32(s, 16)
66
+ magic = i16(s, 4)
67
+ if magic == 0xAF11:
68
+ duration = (duration * 1000) // 70
69
+ self.info["duration"] = duration
70
+
71
+ # look for palette
72
+ palette = [(a, a, a) for a in range(256)]
73
+
74
+ s = self.fp.read(16)
75
+
76
+ self.__offset = 128
77
+
78
+ if i16(s, 4) == 0xF100:
79
+ # prefix chunk; ignore it
80
+ self.__offset = self.__offset + i32(s)
81
+ self.fp.seek(self.__offset)
82
+ s = self.fp.read(16)
83
+
84
+ if i16(s, 4) == 0xF1FA:
85
+ # look for palette chunk
86
+ number_of_subchunks = i16(s, 6)
87
+ chunk_size: int | None = None
88
+ for _ in range(number_of_subchunks):
89
+ if chunk_size is not None:
90
+ self.fp.seek(chunk_size - 6, os.SEEK_CUR)
91
+ s = self.fp.read(6)
92
+ chunk_type = i16(s, 4)
93
+ if chunk_type in (4, 11):
94
+ self._palette(palette, 2 if chunk_type == 11 else 0)
95
+ break
96
+ chunk_size = i32(s)
97
+ if not chunk_size:
98
+ break
99
+
100
+ self.palette = ImagePalette.raw(
101
+ "RGB", b"".join(o8(r) + o8(g) + o8(b) for (r, g, b) in palette)
102
+ )
103
+
104
+ # set things up to decode first frame
105
+ self.__frame = -1
106
+ self._fp = self.fp
107
+ self.__rewind = self.fp.tell()
108
+ self.seek(0)
109
+
110
+ def _palette(self, palette: list[tuple[int, int, int]], shift: int) -> None:
111
+ # load palette
112
+
113
+ i = 0
114
+ for e in range(i16(self.fp.read(2))):
115
+ s = self.fp.read(2)
116
+ i = i + s[0]
117
+ n = s[1]
118
+ if n == 0:
119
+ n = 256
120
+ s = self.fp.read(n * 3)
121
+ for n in range(0, len(s), 3):
122
+ r = s[n] << shift
123
+ g = s[n + 1] << shift
124
+ b = s[n + 2] << shift
125
+ palette[i] = (r, g, b)
126
+ i += 1
127
+
128
+ def seek(self, frame: int) -> None:
129
+ if not self._seek_check(frame):
130
+ return
131
+ if frame < self.__frame:
132
+ self._seek(0)
133
+
134
+ for f in range(self.__frame + 1, frame + 1):
135
+ self._seek(f)
136
+
137
+ def _seek(self, frame: int) -> None:
138
+ if isinstance(self._fp, DeferredError):
139
+ raise self._fp.ex
140
+ if frame == 0:
141
+ self.__frame = -1
142
+ self._fp.seek(self.__rewind)
143
+ self.__offset = 128
144
+ else:
145
+ # ensure that the previous frame was loaded
146
+ self.load()
147
+
148
+ if frame != self.__frame + 1:
149
+ msg = f"cannot seek to frame {frame}"
150
+ raise ValueError(msg)
151
+ self.__frame = frame
152
+
153
+ # move to next frame
154
+ self.fp = self._fp
155
+ self.fp.seek(self.__offset)
156
+
157
+ s = self.fp.read(4)
158
+ if not s:
159
+ msg = "missing frame size"
160
+ raise EOFError(msg)
161
+
162
+ framesize = i32(s)
163
+
164
+ self.decodermaxblock = framesize
165
+ self.tile = [ImageFile._Tile("fli", (0, 0) + self.size, self.__offset)]
166
+
167
+ self.__offset += framesize
168
+
169
+ def tell(self) -> int:
170
+ return self.__frame
171
+
172
+
173
+ #
174
+ # registry
175
+
176
+ Image.register_open(FliImageFile.format, FliImageFile, _accept)
177
+
178
+ Image.register_extensions(FliImageFile.format, [".fli", ".flc"])
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/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])
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/FpxImagePlugin.py ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # THIS IS WORK IN PROGRESS
3
+ #
4
+ # The Python Imaging Library.
5
+ # $Id$
6
+ #
7
+ # FlashPix support for PIL
8
+ #
9
+ # History:
10
+ # 97-01-25 fl Created (reads uncompressed RGB images only)
11
+ #
12
+ # Copyright (c) Secret Labs AB 1997.
13
+ # Copyright (c) Fredrik Lundh 1997.
14
+ #
15
+ # See the README file for information on usage and redistribution.
16
+ #
17
+ from __future__ import annotations
18
+
19
+ import olefile
20
+
21
+ from . import Image, ImageFile
22
+ from ._binary import i32le as i32
23
+
24
+ # we map from colour field tuples to (mode, rawmode) descriptors
25
+ MODES = {
26
+ # opacity
27
+ (0x00007FFE,): ("A", "L"),
28
+ # monochrome
29
+ (0x00010000,): ("L", "L"),
30
+ (0x00018000, 0x00017FFE): ("RGBA", "LA"),
31
+ # photo YCC
32
+ (0x00020000, 0x00020001, 0x00020002): ("RGB", "YCC;P"),
33
+ (0x00028000, 0x00028001, 0x00028002, 0x00027FFE): ("RGBA", "YCCA;P"),
34
+ # standard RGB (NIFRGB)
35
+ (0x00030000, 0x00030001, 0x00030002): ("RGB", "RGB"),
36
+ (0x00038000, 0x00038001, 0x00038002, 0x00037FFE): ("RGBA", "RGBA"),
37
+ }
38
+
39
+
40
+ #
41
+ # --------------------------------------------------------------------
42
+
43
+
44
+ def _accept(prefix: bytes) -> bool:
45
+ return prefix.startswith(olefile.MAGIC)
46
+
47
+
48
+ ##
49
+ # Image plugin for the FlashPix images.
50
+
51
+
52
+ class FpxImageFile(ImageFile.ImageFile):
53
+ format = "FPX"
54
+ format_description = "FlashPix"
55
+
56
+ def _open(self) -> None:
57
+ #
58
+ # read the OLE directory and see if this is a likely
59
+ # to be a FlashPix file
60
+
61
+ try:
62
+ self.ole = olefile.OleFileIO(self.fp)
63
+ except OSError as e:
64
+ msg = "not an FPX file; invalid OLE file"
65
+ raise SyntaxError(msg) from e
66
+
67
+ root = self.ole.root
68
+ if not root or root.clsid != "56616700-C154-11CE-8553-00AA00A1F95B":
69
+ msg = "not an FPX file; bad root CLSID"
70
+ raise SyntaxError(msg)
71
+
72
+ self._open_index(1)
73
+
74
+ def _open_index(self, index: int = 1) -> None:
75
+ #
76
+ # get the Image Contents Property Set
77
+
78
+ prop = self.ole.getproperties(
79
+ [f"Data Object Store {index:06d}", "\005Image Contents"]
80
+ )
81
+
82
+ # size (highest resolution)
83
+
84
+ assert isinstance(prop[0x1000002], int)
85
+ assert isinstance(prop[0x1000003], int)
86
+ self._size = prop[0x1000002], prop[0x1000003]
87
+
88
+ size = max(self.size)
89
+ i = 1
90
+ while size > 64:
91
+ size = size // 2
92
+ i += 1
93
+ self.maxid = i - 1
94
+
95
+ # mode. instead of using a single field for this, flashpix
96
+ # requires you to specify the mode for each channel in each
97
+ # resolution subimage, and leaves it to the decoder to make
98
+ # sure that they all match. for now, we'll cheat and assume
99
+ # that this is always the case.
100
+
101
+ id = self.maxid << 16
102
+
103
+ s = prop[0x2000002 | id]
104
+
105
+ if not isinstance(s, bytes) or (bands := i32(s, 4)) > 4:
106
+ msg = "Invalid number of bands"
107
+ raise OSError(msg)
108
+
109
+ # note: for now, we ignore the "uncalibrated" flag
110
+ colors = tuple(i32(s, 8 + i * 4) & 0x7FFFFFFF for i in range(bands))
111
+
112
+ self._mode, self.rawmode = MODES[colors]
113
+
114
+ # load JPEG tables, if any
115
+ self.jpeg = {}
116
+ for i in range(256):
117
+ id = 0x3000001 | (i << 16)
118
+ if id in prop:
119
+ self.jpeg[i] = prop[id]
120
+
121
+ self._open_subimage(1, self.maxid)
122
+
123
+ def _open_subimage(self, index: int = 1, subimage: int = 0) -> None:
124
+ #
125
+ # setup tile descriptors for a given subimage
126
+
127
+ stream = [
128
+ f"Data Object Store {index:06d}",
129
+ f"Resolution {subimage:04d}",
130
+ "Subimage 0000 Header",
131
+ ]
132
+
133
+ fp = self.ole.openstream(stream)
134
+
135
+ # skip prefix
136
+ fp.read(28)
137
+
138
+ # header stream
139
+ s = fp.read(36)
140
+
141
+ size = i32(s, 4), i32(s, 8)
142
+ # tilecount = i32(s, 12)
143
+ tilesize = i32(s, 16), i32(s, 20)
144
+ # channels = i32(s, 24)
145
+ offset = i32(s, 28)
146
+ length = i32(s, 32)
147
+
148
+ if size != self.size:
149
+ msg = "subimage mismatch"
150
+ raise OSError(msg)
151
+
152
+ # get tile descriptors
153
+ fp.seek(28 + offset)
154
+ s = fp.read(i32(s, 12) * length)
155
+
156
+ x = y = 0
157
+ xsize, ysize = size
158
+ xtile, ytile = tilesize
159
+ self.tile = []
160
+
161
+ for i in range(0, len(s), length):
162
+ x1 = min(xsize, x + xtile)
163
+ y1 = min(ysize, y + ytile)
164
+
165
+ compression = i32(s, i + 8)
166
+
167
+ if compression == 0:
168
+ self.tile.append(
169
+ ImageFile._Tile(
170
+ "raw",
171
+ (x, y, x1, y1),
172
+ i32(s, i) + 28,
173
+ self.rawmode,
174
+ )
175
+ )
176
+
177
+ elif compression == 1:
178
+ # FIXME: the fill decoder is not implemented
179
+ self.tile.append(
180
+ ImageFile._Tile(
181
+ "fill",
182
+ (x, y, x1, y1),
183
+ i32(s, i) + 28,
184
+ (self.rawmode, s[12:16]),
185
+ )
186
+ )
187
+
188
+ elif compression == 2:
189
+ internal_color_conversion = s[14]
190
+ jpeg_tables = s[15]
191
+ rawmode = self.rawmode
192
+
193
+ if internal_color_conversion:
194
+ # The image is stored as usual (usually YCbCr).
195
+ if rawmode == "RGBA":
196
+ # For "RGBA", data is stored as YCbCrA based on
197
+ # negative RGB. The following trick works around
198
+ # this problem :
199
+ jpegmode, rawmode = "YCbCrK", "CMYK"
200
+ else:
201
+ jpegmode = None # let the decoder decide
202
+
203
+ else:
204
+ # The image is stored as defined by rawmode
205
+ jpegmode = rawmode
206
+
207
+ self.tile.append(
208
+ ImageFile._Tile(
209
+ "jpeg",
210
+ (x, y, x1, y1),
211
+ i32(s, i) + 28,
212
+ (rawmode, jpegmode),
213
+ )
214
+ )
215
+
216
+ # FIXME: jpeg tables are tile dependent; the prefix
217
+ # data must be placed in the tile descriptor itself!
218
+
219
+ if jpeg_tables:
220
+ self.tile_prefix = self.jpeg[jpeg_tables]
221
+
222
+ else:
223
+ msg = "unknown/invalid compression"
224
+ raise OSError(msg)
225
+
226
+ x = x + xtile
227
+ if x >= xsize:
228
+ x, y = 0, y + ytile
229
+ if y >= ysize:
230
+ break # isn't really required
231
+
232
+ self.stream = stream
233
+ self._fp = self.fp
234
+ self.fp = None
235
+
236
+ def load(self) -> Image.core.PixelAccess | None:
237
+ if not self.fp:
238
+ self.fp = self.ole.openstream(self.stream[:2] + ["Subimage 0000 Data"])
239
+
240
+ return ImageFile.ImageFile.load(self)
241
+
242
+ def close(self) -> None:
243
+ self.ole.close()
244
+ super().close()
245
+
246
+ def __exit__(self, *args: object) -> None:
247
+ self.ole.close()
248
+ super().__exit__()
249
+
250
+
251
+ #
252
+ # --------------------------------------------------------------------
253
+
254
+
255
+ Image.register_open(FpxImageFile.format, FpxImageFile, _accept)
256
+
257
+ Image.register_extension(FpxImageFile.format, ".fpx")
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/FtexImagePlugin.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A Pillow loader for .ftc and .ftu files (FTEX)
3
+ Jerome Leclanche <jerome@leclan.ch>
4
+
5
+ The contents of this file are hereby released in the public domain (CC0)
6
+ Full text of the CC0 license:
7
+ https://creativecommons.org/publicdomain/zero/1.0/
8
+
9
+ Independence War 2: Edge Of Chaos - Texture File Format - 16 October 2001
10
+
11
+ The textures used for 3D objects in Independence War 2: Edge Of Chaos are in a
12
+ packed custom format called FTEX. This file format uses file extensions FTC
13
+ and FTU.
14
+ * FTC files are compressed textures (using standard texture compression).
15
+ * FTU files are not compressed.
16
+ Texture File Format
17
+ The FTC and FTU texture files both use the same format. This
18
+ has the following structure:
19
+ {header}
20
+ {format_directory}
21
+ {data}
22
+ Where:
23
+ {header} = {
24
+ u32:magic,
25
+ u32:version,
26
+ u32:width,
27
+ u32:height,
28
+ u32:mipmap_count,
29
+ u32:format_count
30
+ }
31
+
32
+ * The "magic" number is "FTEX".
33
+ * "width" and "height" are the dimensions of the texture.
34
+ * "mipmap_count" is the number of mipmaps in the texture.
35
+ * "format_count" is the number of texture formats (different versions of the
36
+ same texture) in this file.
37
+
38
+ {format_directory} = format_count * { u32:format, u32:where }
39
+
40
+ The format value is 0 for DXT1 compressed textures and 1 for 24-bit RGB
41
+ uncompressed textures.
42
+ The texture data for a format starts at the position "where" in the file.
43
+
44
+ Each set of texture data in the file has the following structure:
45
+ {data} = format_count * { u32:mipmap_size, mipmap_size * { u8 } }
46
+ * "mipmap_size" is the number of bytes in that mip level. For compressed
47
+ textures this is the size of the texture data compressed with DXT1. For 24 bit
48
+ uncompressed textures, this is 3 * width * height. Following this are the image
49
+ bytes for that mipmap level.
50
+
51
+ Note: All data is stored in little-Endian (Intel) byte order.
52
+ """
53
+
54
+ from __future__ import annotations
55
+
56
+ import struct
57
+ from enum import IntEnum
58
+ from io import BytesIO
59
+
60
+ from . import Image, ImageFile
61
+
62
+ MAGIC = b"FTEX"
63
+
64
+
65
+ class Format(IntEnum):
66
+ DXT1 = 0
67
+ UNCOMPRESSED = 1
68
+
69
+
70
+ class FtexImageFile(ImageFile.ImageFile):
71
+ format = "FTEX"
72
+ format_description = "Texture File Format (IW2:EOC)"
73
+
74
+ def _open(self) -> None:
75
+ if not _accept(self.fp.read(4)):
76
+ msg = "not an FTEX file"
77
+ raise SyntaxError(msg)
78
+ struct.unpack("<i", self.fp.read(4)) # version
79
+ self._size = struct.unpack("<2i", self.fp.read(8))
80
+ mipmap_count, format_count = struct.unpack("<2i", self.fp.read(8))
81
+
82
+ # Only support single-format files.
83
+ # I don't know of any multi-format file.
84
+ assert format_count == 1
85
+
86
+ format, where = struct.unpack("<2i", self.fp.read(8))
87
+ self.fp.seek(where)
88
+ (mipmap_size,) = struct.unpack("<i", self.fp.read(4))
89
+
90
+ data = self.fp.read(mipmap_size)
91
+
92
+ if format == Format.DXT1:
93
+ self._mode = "RGBA"
94
+ self.tile = [ImageFile._Tile("bcn", (0, 0) + self.size, 0, (1,))]
95
+ elif format == Format.UNCOMPRESSED:
96
+ self._mode = "RGB"
97
+ self.tile = [ImageFile._Tile("raw", (0, 0) + self.size, 0, "RGB")]
98
+ else:
99
+ msg = f"Invalid texture compression format: {repr(format)}"
100
+ raise ValueError(msg)
101
+
102
+ self.fp.close()
103
+ self.fp = BytesIO(data)
104
+
105
+ def load_seek(self, pos: int) -> None:
106
+ pass
107
+
108
+
109
+ def _accept(prefix: bytes) -> bool:
110
+ return prefix.startswith(MAGIC)
111
+
112
+
113
+ Image.register_open(FtexImageFile.format, FtexImageFile, _accept)
114
+ Image.register_extensions(FtexImageFile.format, [".ftc", ".ftu"])
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/GbrImagePlugin.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library
3
+ #
4
+ # load a GIMP brush file
5
+ #
6
+ # History:
7
+ # 96-03-14 fl Created
8
+ # 16-01-08 es Version 2
9
+ #
10
+ # Copyright (c) Secret Labs AB 1997.
11
+ # Copyright (c) Fredrik Lundh 1996.
12
+ # Copyright (c) Eric Soroos 2016.
13
+ #
14
+ # See the README file for information on usage and redistribution.
15
+ #
16
+ #
17
+ # See https://github.com/GNOME/gimp/blob/mainline/devel-docs/gbr.txt for
18
+ # format documentation.
19
+ #
20
+ # This code Interprets version 1 and 2 .gbr files.
21
+ # Version 1 files are obsolete, and should not be used for new
22
+ # brushes.
23
+ # Version 2 files are saved by GIMP v2.8 (at least)
24
+ # Version 3 files have a format specifier of 18 for 16bit floats in
25
+ # the color depth field. This is currently unsupported by Pillow.
26
+ from __future__ import annotations
27
+
28
+ from . import Image, ImageFile
29
+ from ._binary import i32be as i32
30
+
31
+
32
+ def _accept(prefix: bytes) -> bool:
33
+ return len(prefix) >= 8 and i32(prefix, 0) >= 20 and i32(prefix, 4) in (1, 2)
34
+
35
+
36
+ ##
37
+ # Image plugin for the GIMP brush format.
38
+
39
+
40
+ class GbrImageFile(ImageFile.ImageFile):
41
+ format = "GBR"
42
+ format_description = "GIMP brush file"
43
+
44
+ def _open(self) -> None:
45
+ header_size = i32(self.fp.read(4))
46
+ if header_size < 20:
47
+ msg = "not a GIMP brush"
48
+ raise SyntaxError(msg)
49
+ version = i32(self.fp.read(4))
50
+ if version not in (1, 2):
51
+ msg = f"Unsupported GIMP brush version: {version}"
52
+ raise SyntaxError(msg)
53
+
54
+ width = i32(self.fp.read(4))
55
+ height = i32(self.fp.read(4))
56
+ color_depth = i32(self.fp.read(4))
57
+ if width <= 0 or height <= 0:
58
+ msg = "not a GIMP brush"
59
+ raise SyntaxError(msg)
60
+ if color_depth not in (1, 4):
61
+ msg = f"Unsupported GIMP brush color depth: {color_depth}"
62
+ raise SyntaxError(msg)
63
+
64
+ if version == 1:
65
+ comment_length = header_size - 20
66
+ else:
67
+ comment_length = header_size - 28
68
+ magic_number = self.fp.read(4)
69
+ if magic_number != b"GIMP":
70
+ msg = "not a GIMP brush, bad magic number"
71
+ raise SyntaxError(msg)
72
+ self.info["spacing"] = i32(self.fp.read(4))
73
+
74
+ comment = self.fp.read(comment_length)[:-1]
75
+
76
+ if color_depth == 1:
77
+ self._mode = "L"
78
+ else:
79
+ self._mode = "RGBA"
80
+
81
+ self._size = width, height
82
+
83
+ self.info["comment"] = comment
84
+
85
+ # Image might not be small
86
+ Image._decompression_bomb_check(self.size)
87
+
88
+ # Data is an uncompressed block of w * h * bytes/pixel
89
+ self._data_size = width * height * color_depth
90
+
91
+ def load(self) -> Image.core.PixelAccess | None:
92
+ if self._im is None:
93
+ self.im = Image.core.new(self.mode, self.size)
94
+ self.frombytes(self.fp.read(self._data_size))
95
+ return Image.Image.load(self)
96
+
97
+
98
+ #
99
+ # registry
100
+
101
+
102
+ Image.register_open(GbrImageFile.format, GbrImageFile, _accept)
103
+ Image.register_extension(GbrImageFile.format, ".gbr")
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/GdImageFile.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # GD file handling
6
+ #
7
+ # History:
8
+ # 1996-04-12 fl Created
9
+ #
10
+ # Copyright (c) 1997 by Secret Labs AB.
11
+ # Copyright (c) 1996 by Fredrik Lundh.
12
+ #
13
+ # See the README file for information on usage and redistribution.
14
+ #
15
+
16
+
17
+ """
18
+ .. note::
19
+ This format cannot be automatically recognized, so the
20
+ class is not registered for use with :py:func:`PIL.Image.open()`. To open a
21
+ gd file, use the :py:func:`PIL.GdImageFile.open()` function instead.
22
+
23
+ .. warning::
24
+ THE GD FORMAT IS NOT DESIGNED FOR DATA INTERCHANGE. This
25
+ implementation is provided for convenience and demonstrational
26
+ purposes only.
27
+ """
28
+ from __future__ import annotations
29
+
30
+ from typing import IO
31
+
32
+ from . import ImageFile, ImagePalette, UnidentifiedImageError
33
+ from ._binary import i16be as i16
34
+ from ._binary import i32be as i32
35
+ from ._typing import StrOrBytesPath
36
+
37
+
38
+ class GdImageFile(ImageFile.ImageFile):
39
+ """
40
+ Image plugin for the GD uncompressed format. Note that this format
41
+ is not supported by the standard :py:func:`PIL.Image.open()` function. To use
42
+ this plugin, you have to import the :py:mod:`PIL.GdImageFile` module and
43
+ use the :py:func:`PIL.GdImageFile.open()` function.
44
+ """
45
+
46
+ format = "GD"
47
+ format_description = "GD uncompressed images"
48
+
49
+ def _open(self) -> None:
50
+ # Header
51
+ assert self.fp is not None
52
+
53
+ s = self.fp.read(1037)
54
+
55
+ if i16(s) not in [65534, 65535]:
56
+ msg = "Not a valid GD 2.x .gd file"
57
+ raise SyntaxError(msg)
58
+
59
+ self._mode = "P"
60
+ self._size = i16(s, 2), i16(s, 4)
61
+
62
+ true_color = s[6]
63
+ true_color_offset = 2 if true_color else 0
64
+
65
+ # transparency index
66
+ tindex = i32(s, 7 + true_color_offset)
67
+ if tindex < 256:
68
+ self.info["transparency"] = tindex
69
+
70
+ self.palette = ImagePalette.raw(
71
+ "RGBX", s[7 + true_color_offset + 6 : 7 + true_color_offset + 6 + 256 * 4]
72
+ )
73
+
74
+ self.tile = [
75
+ ImageFile._Tile(
76
+ "raw",
77
+ (0, 0) + self.size,
78
+ 7 + true_color_offset + 6 + 256 * 4,
79
+ "L",
80
+ )
81
+ ]
82
+
83
+
84
+ def open(fp: StrOrBytesPath | IO[bytes], mode: str = "r") -> GdImageFile:
85
+ """
86
+ Load texture from a GD image file.
87
+
88
+ :param fp: GD file name, or an opened file handle.
89
+ :param mode: Optional mode. In this version, if the mode argument
90
+ is given, it must be "r".
91
+ :returns: An image instance.
92
+ :raises OSError: If the image could not be read.
93
+ """
94
+ if mode != "r":
95
+ msg = "bad mode"
96
+ raise ValueError(msg)
97
+
98
+ try:
99
+ return GdImageFile(fp)
100
+ except SyntaxError as e:
101
+ msg = "cannot identify this image file"
102
+ raise UnidentifiedImageError(msg) from e
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/GifImagePlugin.py ADDED
@@ -0,0 +1,1213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # GIF file handling
6
+ #
7
+ # History:
8
+ # 1995-09-01 fl Created
9
+ # 1996-12-14 fl Added interlace support
10
+ # 1996-12-30 fl Added animation support
11
+ # 1997-01-05 fl Added write support, fixed local colour map bug
12
+ # 1997-02-23 fl Make sure to load raster data in getdata()
13
+ # 1997-07-05 fl Support external decoder (0.4)
14
+ # 1998-07-09 fl Handle all modes when saving (0.5)
15
+ # 1998-07-15 fl Renamed offset attribute to avoid name clash
16
+ # 2001-04-16 fl Added rewind support (seek to frame 0) (0.6)
17
+ # 2001-04-17 fl Added palette optimization (0.7)
18
+ # 2002-06-06 fl Added transparency support for save (0.8)
19
+ # 2004-02-24 fl Disable interlacing for small images
20
+ #
21
+ # Copyright (c) 1997-2004 by Secret Labs AB
22
+ # Copyright (c) 1995-2004 by Fredrik Lundh
23
+ #
24
+ # See the README file for information on usage and redistribution.
25
+ #
26
+ from __future__ import annotations
27
+
28
+ import itertools
29
+ import math
30
+ import os
31
+ import subprocess
32
+ from enum import IntEnum
33
+ from functools import cached_property
34
+ from typing import IO, Any, Literal, NamedTuple, Union, cast
35
+
36
+ from . import (
37
+ Image,
38
+ ImageChops,
39
+ ImageFile,
40
+ ImageMath,
41
+ ImageOps,
42
+ ImagePalette,
43
+ ImageSequence,
44
+ )
45
+ from ._binary import i16le as i16
46
+ from ._binary import o8
47
+ from ._binary import o16le as o16
48
+ from ._util import DeferredError
49
+
50
+ TYPE_CHECKING = False
51
+ if TYPE_CHECKING:
52
+ from . import _imaging
53
+ from ._typing import Buffer
54
+
55
+
56
+ class LoadingStrategy(IntEnum):
57
+ """.. versionadded:: 9.1.0"""
58
+
59
+ RGB_AFTER_FIRST = 0
60
+ RGB_AFTER_DIFFERENT_PALETTE_ONLY = 1
61
+ RGB_ALWAYS = 2
62
+
63
+
64
+ #: .. versionadded:: 9.1.0
65
+ LOADING_STRATEGY = LoadingStrategy.RGB_AFTER_FIRST
66
+
67
+ # --------------------------------------------------------------------
68
+ # Identify/read GIF files
69
+
70
+
71
+ def _accept(prefix: bytes) -> bool:
72
+ return prefix.startswith((b"GIF87a", b"GIF89a"))
73
+
74
+
75
+ ##
76
+ # Image plugin for GIF images. This plugin supports both GIF87 and
77
+ # GIF89 images.
78
+
79
+
80
+ class GifImageFile(ImageFile.ImageFile):
81
+ format = "GIF"
82
+ format_description = "Compuserve GIF"
83
+ _close_exclusive_fp_after_loading = False
84
+
85
+ global_palette = None
86
+
87
+ def data(self) -> bytes | None:
88
+ s = self.fp.read(1)
89
+ if s and s[0]:
90
+ return self.fp.read(s[0])
91
+ return None
92
+
93
+ def _is_palette_needed(self, p: bytes) -> bool:
94
+ for i in range(0, len(p), 3):
95
+ if not (i // 3 == p[i] == p[i + 1] == p[i + 2]):
96
+ return True
97
+ return False
98
+
99
+ def _open(self) -> None:
100
+ # Screen
101
+ s = self.fp.read(13)
102
+ if not _accept(s):
103
+ msg = "not a GIF file"
104
+ raise SyntaxError(msg)
105
+
106
+ self.info["version"] = s[:6]
107
+ self._size = i16(s, 6), i16(s, 8)
108
+ flags = s[10]
109
+ bits = (flags & 7) + 1
110
+
111
+ if flags & 128:
112
+ # get global palette
113
+ self.info["background"] = s[11]
114
+ # check if palette contains colour indices
115
+ p = self.fp.read(3 << bits)
116
+ if self._is_palette_needed(p):
117
+ p = ImagePalette.raw("RGB", p)
118
+ self.global_palette = self.palette = p
119
+
120
+ self._fp = self.fp # FIXME: hack
121
+ self.__rewind = self.fp.tell()
122
+ self._n_frames: int | None = None
123
+ self._seek(0) # get ready to read first frame
124
+
125
+ @property
126
+ def n_frames(self) -> int:
127
+ if self._n_frames is None:
128
+ current = self.tell()
129
+ try:
130
+ while True:
131
+ self._seek(self.tell() + 1, False)
132
+ except EOFError:
133
+ self._n_frames = self.tell() + 1
134
+ self.seek(current)
135
+ return self._n_frames
136
+
137
+ @cached_property
138
+ def is_animated(self) -> bool:
139
+ if self._n_frames is not None:
140
+ return self._n_frames != 1
141
+
142
+ current = self.tell()
143
+ if current:
144
+ return True
145
+
146
+ try:
147
+ self._seek(1, False)
148
+ is_animated = True
149
+ except EOFError:
150
+ is_animated = False
151
+
152
+ self.seek(current)
153
+ return is_animated
154
+
155
+ def seek(self, frame: int) -> None:
156
+ if not self._seek_check(frame):
157
+ return
158
+ if frame < self.__frame:
159
+ self._im = None
160
+ self._seek(0)
161
+
162
+ last_frame = self.__frame
163
+ for f in range(self.__frame + 1, frame + 1):
164
+ try:
165
+ self._seek(f)
166
+ except EOFError as e:
167
+ self.seek(last_frame)
168
+ msg = "no more images in GIF file"
169
+ raise EOFError(msg) from e
170
+
171
+ def _seek(self, frame: int, update_image: bool = True) -> None:
172
+ if isinstance(self._fp, DeferredError):
173
+ raise self._fp.ex
174
+ if frame == 0:
175
+ # rewind
176
+ self.__offset = 0
177
+ self.dispose: _imaging.ImagingCore | None = None
178
+ self.__frame = -1
179
+ self._fp.seek(self.__rewind)
180
+ self.disposal_method = 0
181
+ if "comment" in self.info:
182
+ del self.info["comment"]
183
+ else:
184
+ # ensure that the previous frame was loaded
185
+ if self.tile and update_image:
186
+ self.load()
187
+
188
+ if frame != self.__frame + 1:
189
+ msg = f"cannot seek to frame {frame}"
190
+ raise ValueError(msg)
191
+
192
+ self.fp = self._fp
193
+ if self.__offset:
194
+ # backup to last frame
195
+ self.fp.seek(self.__offset)
196
+ while self.data():
197
+ pass
198
+ self.__offset = 0
199
+
200
+ s = self.fp.read(1)
201
+ if not s or s == b";":
202
+ msg = "no more images in GIF file"
203
+ raise EOFError(msg)
204
+
205
+ palette: ImagePalette.ImagePalette | Literal[False] | None = None
206
+
207
+ info: dict[str, Any] = {}
208
+ frame_transparency = None
209
+ interlace = None
210
+ frame_dispose_extent = None
211
+ while True:
212
+ if not s:
213
+ s = self.fp.read(1)
214
+ if not s or s == b";":
215
+ break
216
+
217
+ elif s == b"!":
218
+ #
219
+ # extensions
220
+ #
221
+ s = self.fp.read(1)
222
+ block = self.data()
223
+ if s[0] == 249 and block is not None:
224
+ #
225
+ # graphic control extension
226
+ #
227
+ flags = block[0]
228
+ if flags & 1:
229
+ frame_transparency = block[3]
230
+ info["duration"] = i16(block, 1) * 10
231
+
232
+ # disposal method - find the value of bits 4 - 6
233
+ dispose_bits = 0b00011100 & flags
234
+ dispose_bits = dispose_bits >> 2
235
+ if dispose_bits:
236
+ # only set the dispose if it is not
237
+ # unspecified. I'm not sure if this is
238
+ # correct, but it seems to prevent the last
239
+ # frame from looking odd for some animations
240
+ self.disposal_method = dispose_bits
241
+ elif s[0] == 254:
242
+ #
243
+ # comment extension
244
+ #
245
+ comment = b""
246
+
247
+ # Read this comment block
248
+ while block:
249
+ comment += block
250
+ block = self.data()
251
+
252
+ if "comment" in info:
253
+ # If multiple comment blocks in frame, separate with \n
254
+ info["comment"] += b"\n" + comment
255
+ else:
256
+ info["comment"] = comment
257
+ s = None
258
+ continue
259
+ elif s[0] == 255 and frame == 0 and block is not None:
260
+ #
261
+ # application extension
262
+ #
263
+ info["extension"] = block, self.fp.tell()
264
+ if block.startswith(b"NETSCAPE2.0"):
265
+ block = self.data()
266
+ if block and len(block) >= 3 and block[0] == 1:
267
+ self.info["loop"] = i16(block, 1)
268
+ while self.data():
269
+ pass
270
+
271
+ elif s == b",":
272
+ #
273
+ # local image
274
+ #
275
+ s = self.fp.read(9)
276
+
277
+ # extent
278
+ x0, y0 = i16(s, 0), i16(s, 2)
279
+ x1, y1 = x0 + i16(s, 4), y0 + i16(s, 6)
280
+ if (x1 > self.size[0] or y1 > self.size[1]) and update_image:
281
+ self._size = max(x1, self.size[0]), max(y1, self.size[1])
282
+ Image._decompression_bomb_check(self._size)
283
+ frame_dispose_extent = x0, y0, x1, y1
284
+ flags = s[8]
285
+
286
+ interlace = (flags & 64) != 0
287
+
288
+ if flags & 128:
289
+ bits = (flags & 7) + 1
290
+ p = self.fp.read(3 << bits)
291
+ if self._is_palette_needed(p):
292
+ palette = ImagePalette.raw("RGB", p)
293
+ else:
294
+ palette = False
295
+
296
+ # image data
297
+ bits = self.fp.read(1)[0]
298
+ self.__offset = self.fp.tell()
299
+ break
300
+ s = None
301
+
302
+ if interlace is None:
303
+ msg = "image not found in GIF frame"
304
+ raise EOFError(msg)
305
+
306
+ self.__frame = frame
307
+ if not update_image:
308
+ return
309
+
310
+ self.tile = []
311
+
312
+ if self.dispose:
313
+ self.im.paste(self.dispose, self.dispose_extent)
314
+
315
+ self._frame_palette = palette if palette is not None else self.global_palette
316
+ self._frame_transparency = frame_transparency
317
+ if frame == 0:
318
+ if self._frame_palette:
319
+ if LOADING_STRATEGY == LoadingStrategy.RGB_ALWAYS:
320
+ self._mode = "RGBA" if frame_transparency is not None else "RGB"
321
+ else:
322
+ self._mode = "P"
323
+ else:
324
+ self._mode = "L"
325
+
326
+ if palette:
327
+ self.palette = palette
328
+ elif self.global_palette:
329
+ from copy import copy
330
+
331
+ self.palette = copy(self.global_palette)
332
+ else:
333
+ self.palette = None
334
+ else:
335
+ if self.mode == "P":
336
+ if (
337
+ LOADING_STRATEGY != LoadingStrategy.RGB_AFTER_DIFFERENT_PALETTE_ONLY
338
+ or palette
339
+ ):
340
+ if "transparency" in self.info:
341
+ self.im.putpalettealpha(self.info["transparency"], 0)
342
+ self.im = self.im.convert("RGBA", Image.Dither.FLOYDSTEINBERG)
343
+ self._mode = "RGBA"
344
+ del self.info["transparency"]
345
+ else:
346
+ self._mode = "RGB"
347
+ self.im = self.im.convert("RGB", Image.Dither.FLOYDSTEINBERG)
348
+
349
+ def _rgb(color: int) -> tuple[int, int, int]:
350
+ if self._frame_palette:
351
+ if color * 3 + 3 > len(self._frame_palette.palette):
352
+ color = 0
353
+ return cast(
354
+ tuple[int, int, int],
355
+ tuple(self._frame_palette.palette[color * 3 : color * 3 + 3]),
356
+ )
357
+ else:
358
+ return (color, color, color)
359
+
360
+ self.dispose = None
361
+ self.dispose_extent: tuple[int, int, int, int] | None = frame_dispose_extent
362
+ if self.dispose_extent and self.disposal_method >= 2:
363
+ try:
364
+ if self.disposal_method == 2:
365
+ # replace with background colour
366
+
367
+ # only dispose the extent in this frame
368
+ x0, y0, x1, y1 = self.dispose_extent
369
+ dispose_size = (x1 - x0, y1 - y0)
370
+
371
+ Image._decompression_bomb_check(dispose_size)
372
+
373
+ # by convention, attempt to use transparency first
374
+ dispose_mode = "P"
375
+ color = self.info.get("transparency", frame_transparency)
376
+ if color is not None:
377
+ if self.mode in ("RGB", "RGBA"):
378
+ dispose_mode = "RGBA"
379
+ color = _rgb(color) + (0,)
380
+ else:
381
+ color = self.info.get("background", 0)
382
+ if self.mode in ("RGB", "RGBA"):
383
+ dispose_mode = "RGB"
384
+ color = _rgb(color)
385
+ self.dispose = Image.core.fill(dispose_mode, dispose_size, color)
386
+ else:
387
+ # replace with previous contents
388
+ if self._im is not None:
389
+ # only dispose the extent in this frame
390
+ self.dispose = self._crop(self.im, self.dispose_extent)
391
+ elif frame_transparency is not None:
392
+ x0, y0, x1, y1 = self.dispose_extent
393
+ dispose_size = (x1 - x0, y1 - y0)
394
+
395
+ Image._decompression_bomb_check(dispose_size)
396
+ dispose_mode = "P"
397
+ color = frame_transparency
398
+ if self.mode in ("RGB", "RGBA"):
399
+ dispose_mode = "RGBA"
400
+ color = _rgb(frame_transparency) + (0,)
401
+ self.dispose = Image.core.fill(
402
+ dispose_mode, dispose_size, color
403
+ )
404
+ except AttributeError:
405
+ pass
406
+
407
+ if interlace is not None:
408
+ transparency = -1
409
+ if frame_transparency is not None:
410
+ if frame == 0:
411
+ if LOADING_STRATEGY != LoadingStrategy.RGB_ALWAYS:
412
+ self.info["transparency"] = frame_transparency
413
+ elif self.mode not in ("RGB", "RGBA"):
414
+ transparency = frame_transparency
415
+ self.tile = [
416
+ ImageFile._Tile(
417
+ "gif",
418
+ (x0, y0, x1, y1),
419
+ self.__offset,
420
+ (bits, interlace, transparency),
421
+ )
422
+ ]
423
+
424
+ if info.get("comment"):
425
+ self.info["comment"] = info["comment"]
426
+ for k in ["duration", "extension"]:
427
+ if k in info:
428
+ self.info[k] = info[k]
429
+ elif k in self.info:
430
+ del self.info[k]
431
+
432
+ def load_prepare(self) -> None:
433
+ temp_mode = "P" if self._frame_palette else "L"
434
+ self._prev_im = None
435
+ if self.__frame == 0:
436
+ if self._frame_transparency is not None:
437
+ self.im = Image.core.fill(
438
+ temp_mode, self.size, self._frame_transparency
439
+ )
440
+ elif self.mode in ("RGB", "RGBA"):
441
+ self._prev_im = self.im
442
+ if self._frame_palette:
443
+ self.im = Image.core.fill("P", self.size, self._frame_transparency or 0)
444
+ self.im.putpalette("RGB", *self._frame_palette.getdata())
445
+ else:
446
+ self._im = None
447
+ if not self._prev_im and self._im is not None and self.size != self.im.size:
448
+ expanded_im = Image.core.fill(self.im.mode, self.size)
449
+ if self._frame_palette:
450
+ expanded_im.putpalette("RGB", *self._frame_palette.getdata())
451
+ expanded_im.paste(self.im, (0, 0) + self.im.size)
452
+
453
+ self.im = expanded_im
454
+ self._mode = temp_mode
455
+ self._frame_palette = None
456
+
457
+ super().load_prepare()
458
+
459
+ def load_end(self) -> None:
460
+ if self.__frame == 0:
461
+ if self.mode == "P" and LOADING_STRATEGY == LoadingStrategy.RGB_ALWAYS:
462
+ if self._frame_transparency is not None:
463
+ self.im.putpalettealpha(self._frame_transparency, 0)
464
+ self._mode = "RGBA"
465
+ else:
466
+ self._mode = "RGB"
467
+ self.im = self.im.convert(self.mode, Image.Dither.FLOYDSTEINBERG)
468
+ return
469
+ if not self._prev_im:
470
+ return
471
+ if self.size != self._prev_im.size:
472
+ if self._frame_transparency is not None:
473
+ expanded_im = Image.core.fill("RGBA", self.size)
474
+ else:
475
+ expanded_im = Image.core.fill("P", self.size)
476
+ expanded_im.putpalette("RGB", "RGB", self.im.getpalette())
477
+ expanded_im = expanded_im.convert("RGB")
478
+ expanded_im.paste(self._prev_im, (0, 0) + self._prev_im.size)
479
+
480
+ self._prev_im = expanded_im
481
+ assert self._prev_im is not None
482
+ if self._frame_transparency is not None:
483
+ if self.mode == "L":
484
+ frame_im = self.im.convert_transparent("LA", self._frame_transparency)
485
+ else:
486
+ self.im.putpalettealpha(self._frame_transparency, 0)
487
+ frame_im = self.im.convert("RGBA")
488
+ else:
489
+ frame_im = self.im.convert("RGB")
490
+
491
+ assert self.dispose_extent is not None
492
+ frame_im = self._crop(frame_im, self.dispose_extent)
493
+
494
+ self.im = self._prev_im
495
+ self._mode = self.im.mode
496
+ if frame_im.mode in ("LA", "RGBA"):
497
+ self.im.paste(frame_im, self.dispose_extent, frame_im)
498
+ else:
499
+ self.im.paste(frame_im, self.dispose_extent)
500
+
501
+ def tell(self) -> int:
502
+ return self.__frame
503
+
504
+
505
+ # --------------------------------------------------------------------
506
+ # Write GIF files
507
+
508
+
509
+ RAWMODE = {"1": "L", "L": "L", "P": "P"}
510
+
511
+
512
+ def _normalize_mode(im: Image.Image) -> Image.Image:
513
+ """
514
+ Takes an image (or frame), returns an image in a mode that is appropriate
515
+ for saving in a Gif.
516
+
517
+ It may return the original image, or it may return an image converted to
518
+ palette or 'L' mode.
519
+
520
+ :param im: Image object
521
+ :returns: Image object
522
+ """
523
+ if im.mode in RAWMODE:
524
+ im.load()
525
+ return im
526
+ if Image.getmodebase(im.mode) == "RGB":
527
+ im = im.convert("P", palette=Image.Palette.ADAPTIVE)
528
+ assert im.palette is not None
529
+ if im.palette.mode == "RGBA":
530
+ for rgba in im.palette.colors:
531
+ if rgba[3] == 0:
532
+ im.info["transparency"] = im.palette.colors[rgba]
533
+ break
534
+ return im
535
+ return im.convert("L")
536
+
537
+
538
+ _Palette = Union[bytes, bytearray, list[int], ImagePalette.ImagePalette]
539
+
540
+
541
+ def _normalize_palette(
542
+ im: Image.Image, palette: _Palette | None, info: dict[str, Any]
543
+ ) -> Image.Image:
544
+ """
545
+ Normalizes the palette for image.
546
+ - Sets the palette to the incoming palette, if provided.
547
+ - Ensures that there's a palette for L mode images
548
+ - Optimizes the palette if necessary/desired.
549
+
550
+ :param im: Image object
551
+ :param palette: bytes object containing the source palette, or ....
552
+ :param info: encoderinfo
553
+ :returns: Image object
554
+ """
555
+ source_palette = None
556
+ if palette:
557
+ # a bytes palette
558
+ if isinstance(palette, (bytes, bytearray, list)):
559
+ source_palette = bytearray(palette[:768])
560
+ if isinstance(palette, ImagePalette.ImagePalette):
561
+ source_palette = bytearray(palette.palette)
562
+
563
+ if im.mode == "P":
564
+ if not source_palette:
565
+ im_palette = im.getpalette(None)
566
+ assert im_palette is not None
567
+ source_palette = bytearray(im_palette)
568
+ else: # L-mode
569
+ if not source_palette:
570
+ source_palette = bytearray(i // 3 for i in range(768))
571
+ im.palette = ImagePalette.ImagePalette("RGB", palette=source_palette)
572
+ assert source_palette is not None
573
+
574
+ if palette:
575
+ used_palette_colors: list[int | None] = []
576
+ assert im.palette is not None
577
+ for i in range(0, len(source_palette), 3):
578
+ source_color = tuple(source_palette[i : i + 3])
579
+ index = im.palette.colors.get(source_color)
580
+ if index in used_palette_colors:
581
+ index = None
582
+ used_palette_colors.append(index)
583
+ for i, index in enumerate(used_palette_colors):
584
+ if index is None:
585
+ for j in range(len(used_palette_colors)):
586
+ if j not in used_palette_colors:
587
+ used_palette_colors[i] = j
588
+ break
589
+ dest_map: list[int] = []
590
+ for index in used_palette_colors:
591
+ assert index is not None
592
+ dest_map.append(index)
593
+ im = im.remap_palette(dest_map)
594
+ else:
595
+ optimized_palette_colors = _get_optimize(im, info)
596
+ if optimized_palette_colors is not None:
597
+ im = im.remap_palette(optimized_palette_colors, source_palette)
598
+ if "transparency" in info:
599
+ try:
600
+ info["transparency"] = optimized_palette_colors.index(
601
+ info["transparency"]
602
+ )
603
+ except ValueError:
604
+ del info["transparency"]
605
+ return im
606
+
607
+ assert im.palette is not None
608
+ im.palette.palette = source_palette
609
+ return im
610
+
611
+
612
+ def _write_single_frame(
613
+ im: Image.Image,
614
+ fp: IO[bytes],
615
+ palette: _Palette | None,
616
+ ) -> None:
617
+ im_out = _normalize_mode(im)
618
+ for k, v in im_out.info.items():
619
+ if isinstance(k, str):
620
+ im.encoderinfo.setdefault(k, v)
621
+ im_out = _normalize_palette(im_out, palette, im.encoderinfo)
622
+
623
+ for s in _get_global_header(im_out, im.encoderinfo):
624
+ fp.write(s)
625
+
626
+ # local image header
627
+ flags = 0
628
+ if get_interlace(im):
629
+ flags = flags | 64
630
+ _write_local_header(fp, im, (0, 0), flags)
631
+
632
+ im_out.encoderconfig = (8, get_interlace(im))
633
+ ImageFile._save(
634
+ im_out, fp, [ImageFile._Tile("gif", (0, 0) + im.size, 0, RAWMODE[im_out.mode])]
635
+ )
636
+
637
+ fp.write(b"\0") # end of image data
638
+
639
+
640
+ def _getbbox(
641
+ base_im: Image.Image, im_frame: Image.Image
642
+ ) -> tuple[Image.Image, tuple[int, int, int, int] | None]:
643
+ palette_bytes = [
644
+ bytes(im.palette.palette) if im.palette else b"" for im in (base_im, im_frame)
645
+ ]
646
+ if palette_bytes[0] != palette_bytes[1]:
647
+ im_frame = im_frame.convert("RGBA")
648
+ base_im = base_im.convert("RGBA")
649
+ delta = ImageChops.subtract_modulo(im_frame, base_im)
650
+ return delta, delta.getbbox(alpha_only=False)
651
+
652
+
653
+ class _Frame(NamedTuple):
654
+ im: Image.Image
655
+ bbox: tuple[int, int, int, int] | None
656
+ encoderinfo: dict[str, Any]
657
+
658
+
659
+ def _write_multiple_frames(
660
+ im: Image.Image, fp: IO[bytes], palette: _Palette | None
661
+ ) -> bool:
662
+ duration = im.encoderinfo.get("duration")
663
+ disposal = im.encoderinfo.get("disposal", im.info.get("disposal"))
664
+
665
+ im_frames: list[_Frame] = []
666
+ previous_im: Image.Image | None = None
667
+ frame_count = 0
668
+ background_im = None
669
+ for imSequence in itertools.chain([im], im.encoderinfo.get("append_images", [])):
670
+ for im_frame in ImageSequence.Iterator(imSequence):
671
+ # a copy is required here since seek can still mutate the image
672
+ im_frame = _normalize_mode(im_frame.copy())
673
+ if frame_count == 0:
674
+ for k, v in im_frame.info.items():
675
+ if k == "transparency":
676
+ continue
677
+ if isinstance(k, str):
678
+ im.encoderinfo.setdefault(k, v)
679
+
680
+ encoderinfo = im.encoderinfo.copy()
681
+ if "transparency" in im_frame.info:
682
+ encoderinfo.setdefault("transparency", im_frame.info["transparency"])
683
+ im_frame = _normalize_palette(im_frame, palette, encoderinfo)
684
+ if isinstance(duration, (list, tuple)):
685
+ encoderinfo["duration"] = duration[frame_count]
686
+ elif duration is None and "duration" in im_frame.info:
687
+ encoderinfo["duration"] = im_frame.info["duration"]
688
+ if isinstance(disposal, (list, tuple)):
689
+ encoderinfo["disposal"] = disposal[frame_count]
690
+ frame_count += 1
691
+
692
+ diff_frame = None
693
+ if im_frames and previous_im:
694
+ # delta frame
695
+ delta, bbox = _getbbox(previous_im, im_frame)
696
+ if not bbox:
697
+ # This frame is identical to the previous frame
698
+ if encoderinfo.get("duration"):
699
+ im_frames[-1].encoderinfo["duration"] += encoderinfo["duration"]
700
+ continue
701
+ if im_frames[-1].encoderinfo.get("disposal") == 2:
702
+ # To appear correctly in viewers using a convention,
703
+ # only consider transparency, and not background color
704
+ color = im.encoderinfo.get(
705
+ "transparency", im.info.get("transparency")
706
+ )
707
+ if color is not None:
708
+ if background_im is None:
709
+ background = _get_background(im_frame, color)
710
+ background_im = Image.new("P", im_frame.size, background)
711
+ first_palette = im_frames[0].im.palette
712
+ assert first_palette is not None
713
+ background_im.putpalette(first_palette, first_palette.mode)
714
+ bbox = _getbbox(background_im, im_frame)[1]
715
+ else:
716
+ bbox = (0, 0) + im_frame.size
717
+ elif encoderinfo.get("optimize") and im_frame.mode != "1":
718
+ if "transparency" not in encoderinfo:
719
+ assert im_frame.palette is not None
720
+ try:
721
+ encoderinfo["transparency"] = (
722
+ im_frame.palette._new_color_index(im_frame)
723
+ )
724
+ except ValueError:
725
+ pass
726
+ if "transparency" in encoderinfo:
727
+ # When the delta is zero, fill the image with transparency
728
+ diff_frame = im_frame.copy()
729
+ fill = Image.new("P", delta.size, encoderinfo["transparency"])
730
+ if delta.mode == "RGBA":
731
+ r, g, b, a = delta.split()
732
+ mask = ImageMath.lambda_eval(
733
+ lambda args: args["convert"](
734
+ args["max"](
735
+ args["max"](
736
+ args["max"](args["r"], args["g"]), args["b"]
737
+ ),
738
+ args["a"],
739
+ )
740
+ * 255,
741
+ "1",
742
+ ),
743
+ r=r,
744
+ g=g,
745
+ b=b,
746
+ a=a,
747
+ )
748
+ else:
749
+ if delta.mode == "P":
750
+ # Convert to L without considering palette
751
+ delta_l = Image.new("L", delta.size)
752
+ delta_l.putdata(delta.getdata())
753
+ delta = delta_l
754
+ mask = ImageMath.lambda_eval(
755
+ lambda args: args["convert"](args["im"] * 255, "1"),
756
+ im=delta,
757
+ )
758
+ diff_frame.paste(fill, mask=ImageOps.invert(mask))
759
+ else:
760
+ bbox = None
761
+ previous_im = im_frame
762
+ im_frames.append(_Frame(diff_frame or im_frame, bbox, encoderinfo))
763
+
764
+ if len(im_frames) == 1:
765
+ if "duration" in im.encoderinfo:
766
+ # Since multiple frames will not be written, use the combined duration
767
+ im.encoderinfo["duration"] = im_frames[0].encoderinfo["duration"]
768
+ return False
769
+
770
+ for frame_data in im_frames:
771
+ im_frame = frame_data.im
772
+ if not frame_data.bbox:
773
+ # global header
774
+ for s in _get_global_header(im_frame, frame_data.encoderinfo):
775
+ fp.write(s)
776
+ offset = (0, 0)
777
+ else:
778
+ # compress difference
779
+ if not palette:
780
+ frame_data.encoderinfo["include_color_table"] = True
781
+
782
+ if frame_data.bbox != (0, 0) + im_frame.size:
783
+ im_frame = im_frame.crop(frame_data.bbox)
784
+ offset = frame_data.bbox[:2]
785
+ _write_frame_data(fp, im_frame, offset, frame_data.encoderinfo)
786
+ return True
787
+
788
+
789
+ def _save_all(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
790
+ _save(im, fp, filename, save_all=True)
791
+
792
+
793
+ def _save(
794
+ im: Image.Image, fp: IO[bytes], filename: str | bytes, save_all: bool = False
795
+ ) -> None:
796
+ # header
797
+ if "palette" in im.encoderinfo or "palette" in im.info:
798
+ palette = im.encoderinfo.get("palette", im.info.get("palette"))
799
+ else:
800
+ palette = None
801
+ im.encoderinfo.setdefault("optimize", True)
802
+
803
+ if not save_all or not _write_multiple_frames(im, fp, palette):
804
+ _write_single_frame(im, fp, palette)
805
+
806
+ fp.write(b";") # end of file
807
+
808
+ if hasattr(fp, "flush"):
809
+ fp.flush()
810
+
811
+
812
+ def get_interlace(im: Image.Image) -> int:
813
+ interlace = im.encoderinfo.get("interlace", 1)
814
+
815
+ # workaround for @PIL153
816
+ if min(im.size) < 16:
817
+ interlace = 0
818
+
819
+ return interlace
820
+
821
+
822
+ def _write_local_header(
823
+ fp: IO[bytes], im: Image.Image, offset: tuple[int, int], flags: int
824
+ ) -> None:
825
+ try:
826
+ transparency = im.encoderinfo["transparency"]
827
+ except KeyError:
828
+ transparency = None
829
+
830
+ if "duration" in im.encoderinfo:
831
+ duration = int(im.encoderinfo["duration"] / 10)
832
+ else:
833
+ duration = 0
834
+
835
+ disposal = int(im.encoderinfo.get("disposal", 0))
836
+
837
+ if transparency is not None or duration != 0 or disposal:
838
+ packed_flag = 1 if transparency is not None else 0
839
+ packed_flag |= disposal << 2
840
+
841
+ fp.write(
842
+ b"!"
843
+ + o8(249) # extension intro
844
+ + o8(4) # length
845
+ + o8(packed_flag) # packed fields
846
+ + o16(duration) # duration
847
+ + o8(transparency or 0) # transparency index
848
+ + o8(0)
849
+ )
850
+
851
+ include_color_table = im.encoderinfo.get("include_color_table")
852
+ if include_color_table:
853
+ palette_bytes = _get_palette_bytes(im)
854
+ color_table_size = _get_color_table_size(palette_bytes)
855
+ if color_table_size:
856
+ flags = flags | 128 # local color table flag
857
+ flags = flags | color_table_size
858
+
859
+ fp.write(
860
+ b","
861
+ + o16(offset[0]) # offset
862
+ + o16(offset[1])
863
+ + o16(im.size[0]) # size
864
+ + o16(im.size[1])
865
+ + o8(flags) # flags
866
+ )
867
+ if include_color_table and color_table_size:
868
+ fp.write(_get_header_palette(palette_bytes))
869
+ fp.write(o8(8)) # bits
870
+
871
+
872
+ def _save_netpbm(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
873
+ # Unused by default.
874
+ # To use, uncomment the register_save call at the end of the file.
875
+ #
876
+ # If you need real GIF compression and/or RGB quantization, you
877
+ # can use the external NETPBM/PBMPLUS utilities. See comments
878
+ # below for information on how to enable this.
879
+ tempfile = im._dump()
880
+
881
+ try:
882
+ with open(filename, "wb") as f:
883
+ if im.mode != "RGB":
884
+ subprocess.check_call(
885
+ ["ppmtogif", tempfile], stdout=f, stderr=subprocess.DEVNULL
886
+ )
887
+ else:
888
+ # Pipe ppmquant output into ppmtogif
889
+ # "ppmquant 256 %s | ppmtogif > %s" % (tempfile, filename)
890
+ quant_cmd = ["ppmquant", "256", tempfile]
891
+ togif_cmd = ["ppmtogif"]
892
+ quant_proc = subprocess.Popen(
893
+ quant_cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL
894
+ )
895
+ togif_proc = subprocess.Popen(
896
+ togif_cmd,
897
+ stdin=quant_proc.stdout,
898
+ stdout=f,
899
+ stderr=subprocess.DEVNULL,
900
+ )
901
+
902
+ # Allow ppmquant to receive SIGPIPE if ppmtogif exits
903
+ assert quant_proc.stdout is not None
904
+ quant_proc.stdout.close()
905
+
906
+ retcode = quant_proc.wait()
907
+ if retcode:
908
+ raise subprocess.CalledProcessError(retcode, quant_cmd)
909
+
910
+ retcode = togif_proc.wait()
911
+ if retcode:
912
+ raise subprocess.CalledProcessError(retcode, togif_cmd)
913
+ finally:
914
+ try:
915
+ os.unlink(tempfile)
916
+ except OSError:
917
+ pass
918
+
919
+
920
+ # Force optimization so that we can test performance against
921
+ # cases where it took lots of memory and time previously.
922
+ _FORCE_OPTIMIZE = False
923
+
924
+
925
+ def _get_optimize(im: Image.Image, info: dict[str, Any]) -> list[int] | None:
926
+ """
927
+ Palette optimization is a potentially expensive operation.
928
+
929
+ This function determines if the palette should be optimized using
930
+ some heuristics, then returns the list of palette entries in use.
931
+
932
+ :param im: Image object
933
+ :param info: encoderinfo
934
+ :returns: list of indexes of palette entries in use, or None
935
+ """
936
+ if im.mode in ("P", "L") and info and info.get("optimize"):
937
+ # Potentially expensive operation.
938
+
939
+ # The palette saves 3 bytes per color not used, but palette
940
+ # lengths are restricted to 3*(2**N) bytes. Max saving would
941
+ # be 768 -> 6 bytes if we went all the way down to 2 colors.
942
+ # * If we're over 128 colors, we can't save any space.
943
+ # * If there aren't any holes, it's not worth collapsing.
944
+ # * If we have a 'large' image, the palette is in the noise.
945
+
946
+ # create the new palette if not every color is used
947
+ optimise = _FORCE_OPTIMIZE or im.mode == "L"
948
+ if optimise or im.width * im.height < 512 * 512:
949
+ # check which colors are used
950
+ used_palette_colors = []
951
+ for i, count in enumerate(im.histogram()):
952
+ if count:
953
+ used_palette_colors.append(i)
954
+
955
+ if optimise or max(used_palette_colors) >= len(used_palette_colors):
956
+ return used_palette_colors
957
+
958
+ assert im.palette is not None
959
+ num_palette_colors = len(im.palette.palette) // Image.getmodebands(
960
+ im.palette.mode
961
+ )
962
+ current_palette_size = 1 << (num_palette_colors - 1).bit_length()
963
+ if (
964
+ # check that the palette would become smaller when saved
965
+ len(used_palette_colors) <= current_palette_size // 2
966
+ # check that the palette is not already the smallest possible size
967
+ and current_palette_size > 2
968
+ ):
969
+ return used_palette_colors
970
+ return None
971
+
972
+
973
+ def _get_color_table_size(palette_bytes: bytes) -> int:
974
+ # calculate the palette size for the header
975
+ if not palette_bytes:
976
+ return 0
977
+ elif len(palette_bytes) < 9:
978
+ return 1
979
+ else:
980
+ return math.ceil(math.log(len(palette_bytes) // 3, 2)) - 1
981
+
982
+
983
+ def _get_header_palette(palette_bytes: bytes) -> bytes:
984
+ """
985
+ Returns the palette, null padded to the next power of 2 (*3) bytes
986
+ suitable for direct inclusion in the GIF header
987
+
988
+ :param palette_bytes: Unpadded palette bytes, in RGBRGB form
989
+ :returns: Null padded palette
990
+ """
991
+ color_table_size = _get_color_table_size(palette_bytes)
992
+
993
+ # add the missing amount of bytes
994
+ # the palette has to be 2<<n in size
995
+ actual_target_size_diff = (2 << color_table_size) - len(palette_bytes) // 3
996
+ if actual_target_size_diff > 0:
997
+ palette_bytes += o8(0) * 3 * actual_target_size_diff
998
+ return palette_bytes
999
+
1000
+
1001
+ def _get_palette_bytes(im: Image.Image) -> bytes:
1002
+ """
1003
+ Gets the palette for inclusion in the gif header
1004
+
1005
+ :param im: Image object
1006
+ :returns: Bytes, len<=768 suitable for inclusion in gif header
1007
+ """
1008
+ if not im.palette:
1009
+ return b""
1010
+
1011
+ palette = bytes(im.palette.palette)
1012
+ if im.palette.mode == "RGBA":
1013
+ palette = b"".join(palette[i * 4 : i * 4 + 3] for i in range(len(palette) // 3))
1014
+ return palette
1015
+
1016
+
1017
+ def _get_background(
1018
+ im: Image.Image,
1019
+ info_background: int | tuple[int, int, int] | tuple[int, int, int, int] | None,
1020
+ ) -> int:
1021
+ background = 0
1022
+ if info_background:
1023
+ if isinstance(info_background, tuple):
1024
+ # WebPImagePlugin stores an RGBA value in info["background"]
1025
+ # So it must be converted to the same format as GifImagePlugin's
1026
+ # info["background"] - a global color table index
1027
+ assert im.palette is not None
1028
+ try:
1029
+ background = im.palette.getcolor(info_background, im)
1030
+ except ValueError as e:
1031
+ if str(e) not in (
1032
+ # If all 256 colors are in use,
1033
+ # then there is no need for the background color
1034
+ "cannot allocate more than 256 colors",
1035
+ # Ignore non-opaque WebP background
1036
+ "cannot add non-opaque RGBA color to RGB palette",
1037
+ ):
1038
+ raise
1039
+ else:
1040
+ background = info_background
1041
+ return background
1042
+
1043
+
1044
+ def _get_global_header(im: Image.Image, info: dict[str, Any]) -> list[bytes]:
1045
+ """Return a list of strings representing a GIF header"""
1046
+
1047
+ # Header Block
1048
+ # https://www.matthewflickinger.com/lab/whatsinagif/bits_and_bytes.asp
1049
+
1050
+ version = b"87a"
1051
+ if im.info.get("version") == b"89a" or (
1052
+ info
1053
+ and (
1054
+ "transparency" in info
1055
+ or info.get("loop") is not None
1056
+ or info.get("duration")
1057
+ or info.get("comment")
1058
+ )
1059
+ ):
1060
+ version = b"89a"
1061
+
1062
+ background = _get_background(im, info.get("background"))
1063
+
1064
+ palette_bytes = _get_palette_bytes(im)
1065
+ color_table_size = _get_color_table_size(palette_bytes)
1066
+
1067
+ header = [
1068
+ b"GIF" # signature
1069
+ + version # version
1070
+ + o16(im.size[0]) # canvas width
1071
+ + o16(im.size[1]), # canvas height
1072
+ # Logical Screen Descriptor
1073
+ # size of global color table + global color table flag
1074
+ o8(color_table_size + 128), # packed fields
1075
+ # background + reserved/aspect
1076
+ o8(background) + o8(0),
1077
+ # Global Color Table
1078
+ _get_header_palette(palette_bytes),
1079
+ ]
1080
+ if info.get("loop") is not None:
1081
+ header.append(
1082
+ b"!"
1083
+ + o8(255) # extension intro
1084
+ + o8(11)
1085
+ + b"NETSCAPE2.0"
1086
+ + o8(3)
1087
+ + o8(1)
1088
+ + o16(info["loop"]) # number of loops
1089
+ + o8(0)
1090
+ )
1091
+ if info.get("comment"):
1092
+ comment_block = b"!" + o8(254) # extension intro
1093
+
1094
+ comment = info["comment"]
1095
+ if isinstance(comment, str):
1096
+ comment = comment.encode()
1097
+ for i in range(0, len(comment), 255):
1098
+ subblock = comment[i : i + 255]
1099
+ comment_block += o8(len(subblock)) + subblock
1100
+
1101
+ comment_block += o8(0)
1102
+ header.append(comment_block)
1103
+ return header
1104
+
1105
+
1106
+ def _write_frame_data(
1107
+ fp: IO[bytes],
1108
+ im_frame: Image.Image,
1109
+ offset: tuple[int, int],
1110
+ params: dict[str, Any],
1111
+ ) -> None:
1112
+ try:
1113
+ im_frame.encoderinfo = params
1114
+
1115
+ # local image header
1116
+ _write_local_header(fp, im_frame, offset, 0)
1117
+
1118
+ ImageFile._save(
1119
+ im_frame,
1120
+ fp,
1121
+ [ImageFile._Tile("gif", (0, 0) + im_frame.size, 0, RAWMODE[im_frame.mode])],
1122
+ )
1123
+
1124
+ fp.write(b"\0") # end of image data
1125
+ finally:
1126
+ del im_frame.encoderinfo
1127
+
1128
+
1129
+ # --------------------------------------------------------------------
1130
+ # Legacy GIF utilities
1131
+
1132
+
1133
+ def getheader(
1134
+ im: Image.Image, palette: _Palette | None = None, info: dict[str, Any] | None = None
1135
+ ) -> tuple[list[bytes], list[int] | None]:
1136
+ """
1137
+ Legacy Method to get Gif data from image.
1138
+
1139
+ Warning:: May modify image data.
1140
+
1141
+ :param im: Image object
1142
+ :param palette: bytes object containing the source palette, or ....
1143
+ :param info: encoderinfo
1144
+ :returns: tuple of(list of header items, optimized palette)
1145
+
1146
+ """
1147
+ if info is None:
1148
+ info = {}
1149
+
1150
+ used_palette_colors = _get_optimize(im, info)
1151
+
1152
+ if "background" not in info and "background" in im.info:
1153
+ info["background"] = im.info["background"]
1154
+
1155
+ im_mod = _normalize_palette(im, palette, info)
1156
+ im.palette = im_mod.palette
1157
+ im.im = im_mod.im
1158
+ header = _get_global_header(im, info)
1159
+
1160
+ return header, used_palette_colors
1161
+
1162
+
1163
+ def getdata(
1164
+ im: Image.Image, offset: tuple[int, int] = (0, 0), **params: Any
1165
+ ) -> list[bytes]:
1166
+ """
1167
+ Legacy Method
1168
+
1169
+ Return a list of strings representing this image.
1170
+ The first string is a local image header, the rest contains
1171
+ encoded image data.
1172
+
1173
+ To specify duration, add the time in milliseconds,
1174
+ e.g. ``getdata(im_frame, duration=1000)``
1175
+
1176
+ :param im: Image object
1177
+ :param offset: Tuple of (x, y) pixels. Defaults to (0, 0)
1178
+ :param \\**params: e.g. duration or other encoder info parameters
1179
+ :returns: List of bytes containing GIF encoded frame data
1180
+
1181
+ """
1182
+ from io import BytesIO
1183
+
1184
+ class Collector(BytesIO):
1185
+ data = []
1186
+
1187
+ def write(self, data: Buffer) -> int:
1188
+ self.data.append(data)
1189
+ return len(data)
1190
+
1191
+ im.load() # make sure raster data is available
1192
+
1193
+ fp = Collector()
1194
+
1195
+ _write_frame_data(fp, im, offset, params)
1196
+
1197
+ return fp.data
1198
+
1199
+
1200
+ # --------------------------------------------------------------------
1201
+ # Registry
1202
+
1203
+ Image.register_open(GifImageFile.format, GifImageFile, _accept)
1204
+ Image.register_save(GifImageFile.format, _save)
1205
+ Image.register_save_all(GifImageFile.format, _save_all)
1206
+ Image.register_extension(GifImageFile.format, ".gif")
1207
+ Image.register_mime(GifImageFile.format, "image/gif")
1208
+
1209
+ #
1210
+ # Uncomment the following line if you wish to use NETPBM/PBMPLUS
1211
+ # instead of the built-in "uncompressed" GIF encoder
1212
+
1213
+ # Image.register_save(GifImageFile.format, _save_netpbm)
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/GimpGradientFile.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Python Imaging Library
3
+ # $Id$
4
+ #
5
+ # stuff to read (and render) GIMP gradient files
6
+ #
7
+ # History:
8
+ # 97-08-23 fl Created
9
+ #
10
+ # Copyright (c) Secret Labs AB 1997.
11
+ # Copyright (c) Fredrik Lundh 1997.
12
+ #
13
+ # See the README file for information on usage and redistribution.
14
+ #
15
+
16
+ """
17
+ Stuff to translate curve segments to palette values (derived from
18
+ the corresponding code in GIMP, written by Federico Mena Quintero.
19
+ See the GIMP distribution for more information.)
20
+ """
21
+ from __future__ import annotations
22
+
23
+ from math import log, pi, sin, sqrt
24
+ from typing import IO, Callable
25
+
26
+ from ._binary import o8
27
+
28
+ EPSILON = 1e-10
29
+ """""" # Enable auto-doc for data member
30
+
31
+
32
+ def linear(middle: float, pos: float) -> float:
33
+ if pos <= middle:
34
+ if middle < EPSILON:
35
+ return 0.0
36
+ else:
37
+ return 0.5 * pos / middle
38
+ else:
39
+ pos = pos - middle
40
+ middle = 1.0 - middle
41
+ if middle < EPSILON:
42
+ return 1.0
43
+ else:
44
+ return 0.5 + 0.5 * pos / middle
45
+
46
+
47
+ def curved(middle: float, pos: float) -> float:
48
+ return pos ** (log(0.5) / log(max(middle, EPSILON)))
49
+
50
+
51
+ def sine(middle: float, pos: float) -> float:
52
+ return (sin((-pi / 2.0) + pi * linear(middle, pos)) + 1.0) / 2.0
53
+
54
+
55
+ def sphere_increasing(middle: float, pos: float) -> float:
56
+ return sqrt(1.0 - (linear(middle, pos) - 1.0) ** 2)
57
+
58
+
59
+ def sphere_decreasing(middle: float, pos: float) -> float:
60
+ return 1.0 - sqrt(1.0 - linear(middle, pos) ** 2)
61
+
62
+
63
+ SEGMENTS = [linear, curved, sine, sphere_increasing, sphere_decreasing]
64
+ """""" # Enable auto-doc for data member
65
+
66
+
67
+ class GradientFile:
68
+ gradient: (
69
+ list[
70
+ tuple[
71
+ float,
72
+ float,
73
+ float,
74
+ list[float],
75
+ list[float],
76
+ Callable[[float, float], float],
77
+ ]
78
+ ]
79
+ | None
80
+ ) = None
81
+
82
+ def getpalette(self, entries: int = 256) -> tuple[bytes, str]:
83
+ assert self.gradient is not None
84
+ palette = []
85
+
86
+ ix = 0
87
+ x0, x1, xm, rgb0, rgb1, segment = self.gradient[ix]
88
+
89
+ for i in range(entries):
90
+ x = i / (entries - 1)
91
+
92
+ while x1 < x:
93
+ ix += 1
94
+ x0, x1, xm, rgb0, rgb1, segment = self.gradient[ix]
95
+
96
+ w = x1 - x0
97
+
98
+ if w < EPSILON:
99
+ scale = segment(0.5, 0.5)
100
+ else:
101
+ scale = segment((xm - x0) / w, (x - x0) / w)
102
+
103
+ # expand to RGBA
104
+ r = o8(int(255 * ((rgb1[0] - rgb0[0]) * scale + rgb0[0]) + 0.5))
105
+ g = o8(int(255 * ((rgb1[1] - rgb0[1]) * scale + rgb0[1]) + 0.5))
106
+ b = o8(int(255 * ((rgb1[2] - rgb0[2]) * scale + rgb0[2]) + 0.5))
107
+ a = o8(int(255 * ((rgb1[3] - rgb0[3]) * scale + rgb0[3]) + 0.5))
108
+
109
+ # add to palette
110
+ palette.append(r + g + b + a)
111
+
112
+ return b"".join(palette), "RGBA"
113
+
114
+
115
+ class GimpGradientFile(GradientFile):
116
+ """File handler for GIMP's gradient format."""
117
+
118
+ def __init__(self, fp: IO[bytes]) -> None:
119
+ if not fp.readline().startswith(b"GIMP Gradient"):
120
+ msg = "not a GIMP gradient file"
121
+ raise SyntaxError(msg)
122
+
123
+ line = fp.readline()
124
+
125
+ # GIMP 1.2 gradient files don't contain a name, but GIMP 1.3 files do
126
+ if line.startswith(b"Name: "):
127
+ line = fp.readline().strip()
128
+
129
+ count = int(line)
130
+
131
+ self.gradient = []
132
+
133
+ for i in range(count):
134
+ s = fp.readline().split()
135
+ w = [float(x) for x in s[:11]]
136
+
137
+ x0, x1 = w[0], w[2]
138
+ xm = w[1]
139
+ rgb0 = w[3:7]
140
+ rgb1 = w[7:11]
141
+
142
+ segment = SEGMENTS[int(s[11])]
143
+ cspace = int(s[12])
144
+
145
+ if cspace != 0:
146
+ msg = "cannot handle HSV colour space"
147
+ raise OSError(msg)
148
+
149
+ self.gradient.append((x0, x1, xm, rgb0, rgb1, segment))
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/GimpPaletteFile.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Python Imaging Library
3
+ # $Id$
4
+ #
5
+ # stuff to read GIMP palette files
6
+ #
7
+ # History:
8
+ # 1997-08-23 fl Created
9
+ # 2004-09-07 fl Support GIMP 2.0 palette files.
10
+ #
11
+ # Copyright (c) Secret Labs AB 1997-2004. All rights reserved.
12
+ # Copyright (c) Fredrik Lundh 1997-2004.
13
+ #
14
+ # See the README file for information on usage and redistribution.
15
+ #
16
+ from __future__ import annotations
17
+
18
+ import re
19
+ from io import BytesIO
20
+ from typing import IO
21
+
22
+
23
+ class GimpPaletteFile:
24
+ """File handler for GIMP's palette format."""
25
+
26
+ rawmode = "RGB"
27
+
28
+ def _read(self, fp: IO[bytes], limit: bool = True) -> None:
29
+ if not fp.readline().startswith(b"GIMP Palette"):
30
+ msg = "not a GIMP palette file"
31
+ raise SyntaxError(msg)
32
+
33
+ palette: list[int] = []
34
+ i = 0
35
+ while True:
36
+ if limit and i == 256 + 3:
37
+ break
38
+
39
+ i += 1
40
+ s = fp.readline()
41
+ if not s:
42
+ break
43
+
44
+ # skip fields and comment lines
45
+ if re.match(rb"\w+:|#", s):
46
+ continue
47
+ if limit and len(s) > 100:
48
+ msg = "bad palette file"
49
+ raise SyntaxError(msg)
50
+
51
+ v = s.split(maxsplit=3)
52
+ if len(v) < 3:
53
+ msg = "bad palette entry"
54
+ raise ValueError(msg)
55
+
56
+ palette += (int(v[i]) for i in range(3))
57
+ if limit and len(palette) == 768:
58
+ break
59
+
60
+ self.palette = bytes(palette)
61
+
62
+ def __init__(self, fp: IO[bytes]) -> None:
63
+ self._read(fp)
64
+
65
+ @classmethod
66
+ def frombytes(cls, data: bytes) -> GimpPaletteFile:
67
+ self = cls.__new__(cls)
68
+ self._read(BytesIO(data), False)
69
+ return self
70
+
71
+ def getpalette(self) -> tuple[bytes, str]:
72
+ return self.palette, self.rawmode
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/GribStubImagePlugin.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library
3
+ # $Id$
4
+ #
5
+ # GRIB stub adapter
6
+ #
7
+ # Copyright (c) 1996-2003 by Fredrik Lundh
8
+ #
9
+ # See the README file for information on usage and redistribution.
10
+ #
11
+ from __future__ import annotations
12
+
13
+ import os
14
+ from typing import IO
15
+
16
+ from . import Image, ImageFile
17
+
18
+ _handler = None
19
+
20
+
21
+ def register_handler(handler: ImageFile.StubHandler | None) -> None:
22
+ """
23
+ Install application-specific GRIB image handler.
24
+
25
+ :param handler: Handler object.
26
+ """
27
+ global _handler
28
+ _handler = handler
29
+
30
+
31
+ # --------------------------------------------------------------------
32
+ # Image adapter
33
+
34
+
35
+ def _accept(prefix: bytes) -> bool:
36
+ return prefix.startswith(b"GRIB") and prefix[7] == 1
37
+
38
+
39
+ class GribStubImageFile(ImageFile.StubImageFile):
40
+ format = "GRIB"
41
+ format_description = "GRIB"
42
+
43
+ def _open(self) -> None:
44
+ if not _accept(self.fp.read(8)):
45
+ msg = "Not a GRIB file"
46
+ raise SyntaxError(msg)
47
+
48
+ self.fp.seek(-8, os.SEEK_CUR)
49
+
50
+ # make something up
51
+ self._mode = "F"
52
+ self._size = 1, 1
53
+
54
+ loader = self._load()
55
+ if loader:
56
+ loader.open(self)
57
+
58
+ def _load(self) -> ImageFile.StubHandler | None:
59
+ return _handler
60
+
61
+
62
+ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
63
+ if _handler is None or not hasattr(_handler, "save"):
64
+ msg = "GRIB save handler not installed"
65
+ raise OSError(msg)
66
+ _handler.save(im, fp, filename)
67
+
68
+
69
+ # --------------------------------------------------------------------
70
+ # Registry
71
+
72
+ Image.register_open(GribStubImageFile.format, GribStubImageFile, _accept)
73
+ Image.register_save(GribStubImageFile.format, _save)
74
+
75
+ Image.register_extension(GribStubImageFile.format, ".grib")
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/Hdf5StubImagePlugin.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library
3
+ # $Id$
4
+ #
5
+ # HDF5 stub adapter
6
+ #
7
+ # Copyright (c) 2000-2003 by Fredrik Lundh
8
+ #
9
+ # See the README file for information on usage and redistribution.
10
+ #
11
+ from __future__ import annotations
12
+
13
+ import os
14
+ from typing import IO
15
+
16
+ from . import Image, ImageFile
17
+
18
+ _handler = None
19
+
20
+
21
+ def register_handler(handler: ImageFile.StubHandler | None) -> None:
22
+ """
23
+ Install application-specific HDF5 image handler.
24
+
25
+ :param handler: Handler object.
26
+ """
27
+ global _handler
28
+ _handler = handler
29
+
30
+
31
+ # --------------------------------------------------------------------
32
+ # Image adapter
33
+
34
+
35
+ def _accept(prefix: bytes) -> bool:
36
+ return prefix.startswith(b"\x89HDF\r\n\x1a\n")
37
+
38
+
39
+ class HDF5StubImageFile(ImageFile.StubImageFile):
40
+ format = "HDF5"
41
+ format_description = "HDF5"
42
+
43
+ def _open(self) -> None:
44
+ if not _accept(self.fp.read(8)):
45
+ msg = "Not an HDF file"
46
+ raise SyntaxError(msg)
47
+
48
+ self.fp.seek(-8, os.SEEK_CUR)
49
+
50
+ # make something up
51
+ self._mode = "F"
52
+ self._size = 1, 1
53
+
54
+ loader = self._load()
55
+ if loader:
56
+ loader.open(self)
57
+
58
+ def _load(self) -> ImageFile.StubHandler | None:
59
+ return _handler
60
+
61
+
62
+ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
63
+ if _handler is None or not hasattr(_handler, "save"):
64
+ msg = "HDF5 save handler not installed"
65
+ raise OSError(msg)
66
+ _handler.save(im, fp, filename)
67
+
68
+
69
+ # --------------------------------------------------------------------
70
+ # Registry
71
+
72
+ Image.register_open(HDF5StubImageFile.format, HDF5StubImageFile, _accept)
73
+ Image.register_save(HDF5StubImageFile.format, _save)
74
+
75
+ Image.register_extensions(HDF5StubImageFile.format, [".h5", ".hdf"])
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/IcnsImagePlugin.py ADDED
@@ -0,0 +1,411 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # macOS icns file decoder, based on icns.py by Bob Ippolito.
6
+ #
7
+ # history:
8
+ # 2004-10-09 fl Turned into a PIL plugin; removed 2.3 dependencies.
9
+ # 2020-04-04 Allow saving on all operating systems.
10
+ #
11
+ # Copyright (c) 2004 by Bob Ippolito.
12
+ # Copyright (c) 2004 by Secret Labs.
13
+ # Copyright (c) 2004 by Fredrik Lundh.
14
+ # Copyright (c) 2014 by Alastair Houghton.
15
+ # Copyright (c) 2020 by Pan Jing.
16
+ #
17
+ # See the README file for information on usage and redistribution.
18
+ #
19
+ from __future__ import annotations
20
+
21
+ import io
22
+ import os
23
+ import struct
24
+ import sys
25
+ from typing import IO
26
+
27
+ from . import Image, ImageFile, PngImagePlugin, features
28
+ from ._deprecate import deprecate
29
+
30
+ enable_jpeg2k = features.check_codec("jpg_2000")
31
+ if enable_jpeg2k:
32
+ from . import Jpeg2KImagePlugin
33
+
34
+ MAGIC = b"icns"
35
+ HEADERSIZE = 8
36
+
37
+
38
+ def nextheader(fobj: IO[bytes]) -> tuple[bytes, int]:
39
+ return struct.unpack(">4sI", fobj.read(HEADERSIZE))
40
+
41
+
42
+ def read_32t(
43
+ fobj: IO[bytes], start_length: tuple[int, int], size: tuple[int, int, int]
44
+ ) -> dict[str, Image.Image]:
45
+ # The 128x128 icon seems to have an extra header for some reason.
46
+ (start, length) = start_length
47
+ fobj.seek(start)
48
+ sig = fobj.read(4)
49
+ if sig != b"\x00\x00\x00\x00":
50
+ msg = "Unknown signature, expecting 0x00000000"
51
+ raise SyntaxError(msg)
52
+ return read_32(fobj, (start + 4, length - 4), size)
53
+
54
+
55
+ def read_32(
56
+ fobj: IO[bytes], start_length: tuple[int, int], size: tuple[int, int, int]
57
+ ) -> dict[str, Image.Image]:
58
+ """
59
+ Read a 32bit RGB icon resource. Seems to be either uncompressed or
60
+ an RLE packbits-like scheme.
61
+ """
62
+ (start, length) = start_length
63
+ fobj.seek(start)
64
+ pixel_size = (size[0] * size[2], size[1] * size[2])
65
+ sizesq = pixel_size[0] * pixel_size[1]
66
+ if length == sizesq * 3:
67
+ # uncompressed ("RGBRGBGB")
68
+ indata = fobj.read(length)
69
+ im = Image.frombuffer("RGB", pixel_size, indata, "raw", "RGB", 0, 1)
70
+ else:
71
+ # decode image
72
+ im = Image.new("RGB", pixel_size, None)
73
+ for band_ix in range(3):
74
+ data = []
75
+ bytesleft = sizesq
76
+ while bytesleft > 0:
77
+ byte = fobj.read(1)
78
+ if not byte:
79
+ break
80
+ byte_int = byte[0]
81
+ if byte_int & 0x80:
82
+ blocksize = byte_int - 125
83
+ byte = fobj.read(1)
84
+ for i in range(blocksize):
85
+ data.append(byte)
86
+ else:
87
+ blocksize = byte_int + 1
88
+ data.append(fobj.read(blocksize))
89
+ bytesleft -= blocksize
90
+ if bytesleft <= 0:
91
+ break
92
+ if bytesleft != 0:
93
+ msg = f"Error reading channel [{repr(bytesleft)} left]"
94
+ raise SyntaxError(msg)
95
+ band = Image.frombuffer("L", pixel_size, b"".join(data), "raw", "L", 0, 1)
96
+ im.im.putband(band.im, band_ix)
97
+ return {"RGB": im}
98
+
99
+
100
+ def read_mk(
101
+ fobj: IO[bytes], start_length: tuple[int, int], size: tuple[int, int, int]
102
+ ) -> dict[str, Image.Image]:
103
+ # Alpha masks seem to be uncompressed
104
+ start = start_length[0]
105
+ fobj.seek(start)
106
+ pixel_size = (size[0] * size[2], size[1] * size[2])
107
+ sizesq = pixel_size[0] * pixel_size[1]
108
+ band = Image.frombuffer("L", pixel_size, fobj.read(sizesq), "raw", "L", 0, 1)
109
+ return {"A": band}
110
+
111
+
112
+ def read_png_or_jpeg2000(
113
+ fobj: IO[bytes], start_length: tuple[int, int], size: tuple[int, int, int]
114
+ ) -> dict[str, Image.Image]:
115
+ (start, length) = start_length
116
+ fobj.seek(start)
117
+ sig = fobj.read(12)
118
+
119
+ im: Image.Image
120
+ if sig.startswith(b"\x89PNG\x0d\x0a\x1a\x0a"):
121
+ fobj.seek(start)
122
+ im = PngImagePlugin.PngImageFile(fobj)
123
+ Image._decompression_bomb_check(im.size)
124
+ return {"RGBA": im}
125
+ elif (
126
+ sig.startswith((b"\xff\x4f\xff\x51", b"\x0d\x0a\x87\x0a"))
127
+ or sig == b"\x00\x00\x00\x0cjP \x0d\x0a\x87\x0a"
128
+ ):
129
+ if not enable_jpeg2k:
130
+ msg = (
131
+ "Unsupported icon subimage format (rebuild PIL "
132
+ "with JPEG 2000 support to fix this)"
133
+ )
134
+ raise ValueError(msg)
135
+ # j2k, jpc or j2c
136
+ fobj.seek(start)
137
+ jp2kstream = fobj.read(length)
138
+ f = io.BytesIO(jp2kstream)
139
+ im = Jpeg2KImagePlugin.Jpeg2KImageFile(f)
140
+ Image._decompression_bomb_check(im.size)
141
+ if im.mode != "RGBA":
142
+ im = im.convert("RGBA")
143
+ return {"RGBA": im}
144
+ else:
145
+ msg = "Unsupported icon subimage format"
146
+ raise ValueError(msg)
147
+
148
+
149
+ class IcnsFile:
150
+ SIZES = {
151
+ (512, 512, 2): [(b"ic10", read_png_or_jpeg2000)],
152
+ (512, 512, 1): [(b"ic09", read_png_or_jpeg2000)],
153
+ (256, 256, 2): [(b"ic14", read_png_or_jpeg2000)],
154
+ (256, 256, 1): [(b"ic08", read_png_or_jpeg2000)],
155
+ (128, 128, 2): [(b"ic13", read_png_or_jpeg2000)],
156
+ (128, 128, 1): [
157
+ (b"ic07", read_png_or_jpeg2000),
158
+ (b"it32", read_32t),
159
+ (b"t8mk", read_mk),
160
+ ],
161
+ (64, 64, 1): [(b"icp6", read_png_or_jpeg2000)],
162
+ (32, 32, 2): [(b"ic12", read_png_or_jpeg2000)],
163
+ (48, 48, 1): [(b"ih32", read_32), (b"h8mk", read_mk)],
164
+ (32, 32, 1): [
165
+ (b"icp5", read_png_or_jpeg2000),
166
+ (b"il32", read_32),
167
+ (b"l8mk", read_mk),
168
+ ],
169
+ (16, 16, 2): [(b"ic11", read_png_or_jpeg2000)],
170
+ (16, 16, 1): [
171
+ (b"icp4", read_png_or_jpeg2000),
172
+ (b"is32", read_32),
173
+ (b"s8mk", read_mk),
174
+ ],
175
+ }
176
+
177
+ def __init__(self, fobj: IO[bytes]) -> None:
178
+ """
179
+ fobj is a file-like object as an icns resource
180
+ """
181
+ # signature : (start, length)
182
+ self.dct = {}
183
+ self.fobj = fobj
184
+ sig, filesize = nextheader(fobj)
185
+ if not _accept(sig):
186
+ msg = "not an icns file"
187
+ raise SyntaxError(msg)
188
+ i = HEADERSIZE
189
+ while i < filesize:
190
+ sig, blocksize = nextheader(fobj)
191
+ if blocksize <= 0:
192
+ msg = "invalid block header"
193
+ raise SyntaxError(msg)
194
+ i += HEADERSIZE
195
+ blocksize -= HEADERSIZE
196
+ self.dct[sig] = (i, blocksize)
197
+ fobj.seek(blocksize, io.SEEK_CUR)
198
+ i += blocksize
199
+
200
+ def itersizes(self) -> list[tuple[int, int, int]]:
201
+ sizes = []
202
+ for size, fmts in self.SIZES.items():
203
+ for fmt, reader in fmts:
204
+ if fmt in self.dct:
205
+ sizes.append(size)
206
+ break
207
+ return sizes
208
+
209
+ def bestsize(self) -> tuple[int, int, int]:
210
+ sizes = self.itersizes()
211
+ if not sizes:
212
+ msg = "No 32bit icon resources found"
213
+ raise SyntaxError(msg)
214
+ return max(sizes)
215
+
216
+ def dataforsize(self, size: tuple[int, int, int]) -> dict[str, Image.Image]:
217
+ """
218
+ Get an icon resource as {channel: array}. Note that
219
+ the arrays are bottom-up like windows bitmaps and will likely
220
+ need to be flipped or transposed in some way.
221
+ """
222
+ dct = {}
223
+ for code, reader in self.SIZES[size]:
224
+ desc = self.dct.get(code)
225
+ if desc is not None:
226
+ dct.update(reader(self.fobj, desc, size))
227
+ return dct
228
+
229
+ def getimage(
230
+ self, size: tuple[int, int] | tuple[int, int, int] | None = None
231
+ ) -> Image.Image:
232
+ if size is None:
233
+ size = self.bestsize()
234
+ elif len(size) == 2:
235
+ size = (size[0], size[1], 1)
236
+ channels = self.dataforsize(size)
237
+
238
+ im = channels.get("RGBA")
239
+ if im:
240
+ return im
241
+
242
+ im = channels["RGB"].copy()
243
+ try:
244
+ im.putalpha(channels["A"])
245
+ except KeyError:
246
+ pass
247
+ return im
248
+
249
+
250
+ ##
251
+ # Image plugin for Mac OS icons.
252
+
253
+
254
+ class IcnsImageFile(ImageFile.ImageFile):
255
+ """
256
+ PIL image support for Mac OS .icns files.
257
+ Chooses the best resolution, but will possibly load
258
+ a different size image if you mutate the size attribute
259
+ before calling 'load'.
260
+
261
+ The info dictionary has a key 'sizes' that is a list
262
+ of sizes that the icns file has.
263
+ """
264
+
265
+ format = "ICNS"
266
+ format_description = "Mac OS icns resource"
267
+
268
+ def _open(self) -> None:
269
+ self.icns = IcnsFile(self.fp)
270
+ self._mode = "RGBA"
271
+ self.info["sizes"] = self.icns.itersizes()
272
+ self.best_size = self.icns.bestsize()
273
+ self.size = (
274
+ self.best_size[0] * self.best_size[2],
275
+ self.best_size[1] * self.best_size[2],
276
+ )
277
+
278
+ @property # type: ignore[override]
279
+ def size(self) -> tuple[int, int] | tuple[int, int, int]:
280
+ return self._size
281
+
282
+ @size.setter
283
+ def size(self, value: tuple[int, int] | tuple[int, int, int]) -> None:
284
+ if len(value) == 3:
285
+ deprecate("Setting size to (width, height, scale)", 12, "load(scale)")
286
+ if value in self.info["sizes"]:
287
+ self._size = value # type: ignore[assignment]
288
+ return
289
+ else:
290
+ # Check that a matching size exists,
291
+ # or that there is a scale that would create a size that matches
292
+ for size in self.info["sizes"]:
293
+ simple_size = size[0] * size[2], size[1] * size[2]
294
+ scale = simple_size[0] // value[0]
295
+ if simple_size[1] / value[1] == scale:
296
+ self._size = value
297
+ return
298
+ msg = "This is not one of the allowed sizes of this image"
299
+ raise ValueError(msg)
300
+
301
+ def load(self, scale: int | None = None) -> Image.core.PixelAccess | None:
302
+ if scale is not None or len(self.size) == 3:
303
+ if scale is None and len(self.size) == 3:
304
+ scale = self.size[2]
305
+ assert scale is not None
306
+ width, height = self.size[:2]
307
+ self.size = width * scale, height * scale
308
+ self.best_size = width, height, scale
309
+
310
+ px = Image.Image.load(self)
311
+ if self._im is not None and self.im.size == self.size:
312
+ # Already loaded
313
+ return px
314
+ self.load_prepare()
315
+ # This is likely NOT the best way to do it, but whatever.
316
+ im = self.icns.getimage(self.best_size)
317
+
318
+ # If this is a PNG or JPEG 2000, it won't be loaded yet
319
+ px = im.load()
320
+
321
+ self.im = im.im
322
+ self._mode = im.mode
323
+ self.size = im.size
324
+
325
+ return px
326
+
327
+
328
+ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
329
+ """
330
+ Saves the image as a series of PNG files,
331
+ that are then combined into a .icns file.
332
+ """
333
+ if hasattr(fp, "flush"):
334
+ fp.flush()
335
+
336
+ sizes = {
337
+ b"ic07": 128,
338
+ b"ic08": 256,
339
+ b"ic09": 512,
340
+ b"ic10": 1024,
341
+ b"ic11": 32,
342
+ b"ic12": 64,
343
+ b"ic13": 256,
344
+ b"ic14": 512,
345
+ }
346
+ provided_images = {im.width: im for im in im.encoderinfo.get("append_images", [])}
347
+ size_streams = {}
348
+ for size in set(sizes.values()):
349
+ image = (
350
+ provided_images[size]
351
+ if size in provided_images
352
+ else im.resize((size, size))
353
+ )
354
+
355
+ temp = io.BytesIO()
356
+ image.save(temp, "png")
357
+ size_streams[size] = temp.getvalue()
358
+
359
+ entries = []
360
+ for type, size in sizes.items():
361
+ stream = size_streams[size]
362
+ entries.append((type, HEADERSIZE + len(stream), stream))
363
+
364
+ # Header
365
+ fp.write(MAGIC)
366
+ file_length = HEADERSIZE # Header
367
+ file_length += HEADERSIZE + 8 * len(entries) # TOC
368
+ file_length += sum(entry[1] for entry in entries)
369
+ fp.write(struct.pack(">i", file_length))
370
+
371
+ # TOC
372
+ fp.write(b"TOC ")
373
+ fp.write(struct.pack(">i", HEADERSIZE + len(entries) * HEADERSIZE))
374
+ for entry in entries:
375
+ fp.write(entry[0])
376
+ fp.write(struct.pack(">i", entry[1]))
377
+
378
+ # Data
379
+ for entry in entries:
380
+ fp.write(entry[0])
381
+ fp.write(struct.pack(">i", entry[1]))
382
+ fp.write(entry[2])
383
+
384
+ if hasattr(fp, "flush"):
385
+ fp.flush()
386
+
387
+
388
+ def _accept(prefix: bytes) -> bool:
389
+ return prefix.startswith(MAGIC)
390
+
391
+
392
+ Image.register_open(IcnsImageFile.format, IcnsImageFile, _accept)
393
+ Image.register_extension(IcnsImageFile.format, ".icns")
394
+
395
+ Image.register_save(IcnsImageFile.format, _save)
396
+ Image.register_mime(IcnsImageFile.format, "image/icns")
397
+
398
+ if __name__ == "__main__":
399
+ if len(sys.argv) < 2:
400
+ print("Syntax: python3 IcnsImagePlugin.py [file]")
401
+ sys.exit()
402
+
403
+ with open(sys.argv[1], "rb") as fp:
404
+ imf = IcnsImageFile(fp)
405
+ for size in imf.info["sizes"]:
406
+ width, height, scale = imf.size = size
407
+ imf.save(f"out-{width}-{height}-{scale}.png")
408
+ with Image.open(sys.argv[1]) as im:
409
+ im.save("out.png")
410
+ if sys.platform == "windows":
411
+ os.startfile("out.png")
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/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.startswith(_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 Image.Image.load(self)
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")
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/ImImagePlugin.py ADDED
@@ -0,0 +1,389 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # IFUNC IM file handling for PIL
6
+ #
7
+ # history:
8
+ # 1995-09-01 fl Created.
9
+ # 1997-01-03 fl Save palette images
10
+ # 1997-01-08 fl Added sequence support
11
+ # 1997-01-23 fl Added P and RGB save support
12
+ # 1997-05-31 fl Read floating point images
13
+ # 1997-06-22 fl Save floating point images
14
+ # 1997-08-27 fl Read and save 1-bit images
15
+ # 1998-06-25 fl Added support for RGB+LUT images
16
+ # 1998-07-02 fl Added support for YCC images
17
+ # 1998-07-15 fl Renamed offset attribute to avoid name clash
18
+ # 1998-12-29 fl Added I;16 support
19
+ # 2001-02-17 fl Use 're' instead of 'regex' (Python 2.1) (0.7)
20
+ # 2003-09-26 fl Added LA/PA support
21
+ #
22
+ # Copyright (c) 1997-2003 by Secret Labs AB.
23
+ # Copyright (c) 1995-2001 by Fredrik Lundh.
24
+ #
25
+ # See the README file for information on usage and redistribution.
26
+ #
27
+ from __future__ import annotations
28
+
29
+ import os
30
+ import re
31
+ from typing import IO, Any
32
+
33
+ from . import Image, ImageFile, ImagePalette
34
+ from ._util import DeferredError
35
+
36
+ # --------------------------------------------------------------------
37
+ # Standard tags
38
+
39
+ COMMENT = "Comment"
40
+ DATE = "Date"
41
+ EQUIPMENT = "Digitalization equipment"
42
+ FRAMES = "File size (no of images)"
43
+ LUT = "Lut"
44
+ NAME = "Name"
45
+ SCALE = "Scale (x,y)"
46
+ SIZE = "Image size (x*y)"
47
+ MODE = "Image type"
48
+
49
+ TAGS = {
50
+ COMMENT: 0,
51
+ DATE: 0,
52
+ EQUIPMENT: 0,
53
+ FRAMES: 0,
54
+ LUT: 0,
55
+ NAME: 0,
56
+ SCALE: 0,
57
+ SIZE: 0,
58
+ MODE: 0,
59
+ }
60
+
61
+ OPEN = {
62
+ # ifunc93/p3cfunc formats
63
+ "0 1 image": ("1", "1"),
64
+ "L 1 image": ("1", "1"),
65
+ "Greyscale image": ("L", "L"),
66
+ "Grayscale image": ("L", "L"),
67
+ "RGB image": ("RGB", "RGB;L"),
68
+ "RLB image": ("RGB", "RLB"),
69
+ "RYB image": ("RGB", "RLB"),
70
+ "B1 image": ("1", "1"),
71
+ "B2 image": ("P", "P;2"),
72
+ "B4 image": ("P", "P;4"),
73
+ "X 24 image": ("RGB", "RGB"),
74
+ "L 32 S image": ("I", "I;32"),
75
+ "L 32 F image": ("F", "F;32"),
76
+ # old p3cfunc formats
77
+ "RGB3 image": ("RGB", "RGB;T"),
78
+ "RYB3 image": ("RGB", "RYB;T"),
79
+ # extensions
80
+ "LA image": ("LA", "LA;L"),
81
+ "PA image": ("LA", "PA;L"),
82
+ "RGBA image": ("RGBA", "RGBA;L"),
83
+ "RGBX image": ("RGB", "RGBX;L"),
84
+ "CMYK image": ("CMYK", "CMYK;L"),
85
+ "YCC image": ("YCbCr", "YCbCr;L"),
86
+ }
87
+
88
+ # ifunc95 extensions
89
+ for i in ["8", "8S", "16", "16S", "32", "32F"]:
90
+ OPEN[f"L {i} image"] = ("F", f"F;{i}")
91
+ OPEN[f"L*{i} image"] = ("F", f"F;{i}")
92
+ for i in ["16", "16L", "16B"]:
93
+ OPEN[f"L {i} image"] = (f"I;{i}", f"I;{i}")
94
+ OPEN[f"L*{i} image"] = (f"I;{i}", f"I;{i}")
95
+ for i in ["32S"]:
96
+ OPEN[f"L {i} image"] = ("I", f"I;{i}")
97
+ OPEN[f"L*{i} image"] = ("I", f"I;{i}")
98
+ for j in range(2, 33):
99
+ OPEN[f"L*{j} image"] = ("F", f"F;{j}")
100
+
101
+
102
+ # --------------------------------------------------------------------
103
+ # Read IM directory
104
+
105
+ split = re.compile(rb"^([A-Za-z][^:]*):[ \t]*(.*)[ \t]*$")
106
+
107
+
108
+ def number(s: Any) -> float:
109
+ try:
110
+ return int(s)
111
+ except ValueError:
112
+ return float(s)
113
+
114
+
115
+ ##
116
+ # Image plugin for the IFUNC IM file format.
117
+
118
+
119
+ class ImImageFile(ImageFile.ImageFile):
120
+ format = "IM"
121
+ format_description = "IFUNC Image Memory"
122
+ _close_exclusive_fp_after_loading = False
123
+
124
+ def _open(self) -> None:
125
+ # Quick rejection: if there's not an LF among the first
126
+ # 100 bytes, this is (probably) not a text header.
127
+
128
+ if b"\n" not in self.fp.read(100):
129
+ msg = "not an IM file"
130
+ raise SyntaxError(msg)
131
+ self.fp.seek(0)
132
+
133
+ n = 0
134
+
135
+ # Default values
136
+ self.info[MODE] = "L"
137
+ self.info[SIZE] = (512, 512)
138
+ self.info[FRAMES] = 1
139
+
140
+ self.rawmode = "L"
141
+
142
+ while True:
143
+ s = self.fp.read(1)
144
+
145
+ # Some versions of IFUNC uses \n\r instead of \r\n...
146
+ if s == b"\r":
147
+ continue
148
+
149
+ if not s or s == b"\0" or s == b"\x1a":
150
+ break
151
+
152
+ # FIXME: this may read whole file if not a text file
153
+ s = s + self.fp.readline()
154
+
155
+ if len(s) > 100:
156
+ msg = "not an IM file"
157
+ raise SyntaxError(msg)
158
+
159
+ if s.endswith(b"\r\n"):
160
+ s = s[:-2]
161
+ elif s.endswith(b"\n"):
162
+ s = s[:-1]
163
+
164
+ try:
165
+ m = split.match(s)
166
+ except re.error as e:
167
+ msg = "not an IM file"
168
+ raise SyntaxError(msg) from e
169
+
170
+ if m:
171
+ k, v = m.group(1, 2)
172
+
173
+ # Don't know if this is the correct encoding,
174
+ # but a decent guess (I guess)
175
+ k = k.decode("latin-1", "replace")
176
+ v = v.decode("latin-1", "replace")
177
+
178
+ # Convert value as appropriate
179
+ if k in [FRAMES, SCALE, SIZE]:
180
+ v = v.replace("*", ",")
181
+ v = tuple(map(number, v.split(",")))
182
+ if len(v) == 1:
183
+ v = v[0]
184
+ elif k == MODE and v in OPEN:
185
+ v, self.rawmode = OPEN[v]
186
+
187
+ # Add to dictionary. Note that COMMENT tags are
188
+ # combined into a list of strings.
189
+ if k == COMMENT:
190
+ if k in self.info:
191
+ self.info[k].append(v)
192
+ else:
193
+ self.info[k] = [v]
194
+ else:
195
+ self.info[k] = v
196
+
197
+ if k in TAGS:
198
+ n += 1
199
+
200
+ else:
201
+ msg = f"Syntax error in IM header: {s.decode('ascii', 'replace')}"
202
+ raise SyntaxError(msg)
203
+
204
+ if not n:
205
+ msg = "Not an IM file"
206
+ raise SyntaxError(msg)
207
+
208
+ # Basic attributes
209
+ self._size = self.info[SIZE]
210
+ self._mode = self.info[MODE]
211
+
212
+ # Skip forward to start of image data
213
+ while s and not s.startswith(b"\x1a"):
214
+ s = self.fp.read(1)
215
+ if not s:
216
+ msg = "File truncated"
217
+ raise SyntaxError(msg)
218
+
219
+ if LUT in self.info:
220
+ # convert lookup table to palette or lut attribute
221
+ palette = self.fp.read(768)
222
+ greyscale = 1 # greyscale palette
223
+ linear = 1 # linear greyscale palette
224
+ for i in range(256):
225
+ if palette[i] == palette[i + 256] == palette[i + 512]:
226
+ if palette[i] != i:
227
+ linear = 0
228
+ else:
229
+ greyscale = 0
230
+ if self.mode in ["L", "LA", "P", "PA"]:
231
+ if greyscale:
232
+ if not linear:
233
+ self.lut = list(palette[:256])
234
+ else:
235
+ if self.mode in ["L", "P"]:
236
+ self._mode = self.rawmode = "P"
237
+ elif self.mode in ["LA", "PA"]:
238
+ self._mode = "PA"
239
+ self.rawmode = "PA;L"
240
+ self.palette = ImagePalette.raw("RGB;L", palette)
241
+ elif self.mode == "RGB":
242
+ if not greyscale or not linear:
243
+ self.lut = list(palette)
244
+
245
+ self.frame = 0
246
+
247
+ self.__offset = offs = self.fp.tell()
248
+
249
+ self._fp = self.fp # FIXME: hack
250
+
251
+ if self.rawmode.startswith("F;"):
252
+ # ifunc95 formats
253
+ try:
254
+ # use bit decoder (if necessary)
255
+ bits = int(self.rawmode[2:])
256
+ if bits not in [8, 16, 32]:
257
+ self.tile = [
258
+ ImageFile._Tile(
259
+ "bit", (0, 0) + self.size, offs, (bits, 8, 3, 0, -1)
260
+ )
261
+ ]
262
+ return
263
+ except ValueError:
264
+ pass
265
+
266
+ if self.rawmode in ["RGB;T", "RYB;T"]:
267
+ # Old LabEye/3PC files. Would be very surprised if anyone
268
+ # ever stumbled upon such a file ;-)
269
+ size = self.size[0] * self.size[1]
270
+ self.tile = [
271
+ ImageFile._Tile("raw", (0, 0) + self.size, offs, ("G", 0, -1)),
272
+ ImageFile._Tile("raw", (0, 0) + self.size, offs + size, ("R", 0, -1)),
273
+ ImageFile._Tile(
274
+ "raw", (0, 0) + self.size, offs + 2 * size, ("B", 0, -1)
275
+ ),
276
+ ]
277
+ else:
278
+ # LabEye/IFUNC files
279
+ self.tile = [
280
+ ImageFile._Tile("raw", (0, 0) + self.size, offs, (self.rawmode, 0, -1))
281
+ ]
282
+
283
+ @property
284
+ def n_frames(self) -> int:
285
+ return self.info[FRAMES]
286
+
287
+ @property
288
+ def is_animated(self) -> bool:
289
+ return self.info[FRAMES] > 1
290
+
291
+ def seek(self, frame: int) -> None:
292
+ if not self._seek_check(frame):
293
+ return
294
+ if isinstance(self._fp, DeferredError):
295
+ raise self._fp.ex
296
+
297
+ self.frame = frame
298
+
299
+ if self.mode == "1":
300
+ bits = 1
301
+ else:
302
+ bits = 8 * len(self.mode)
303
+
304
+ size = ((self.size[0] * bits + 7) // 8) * self.size[1]
305
+ offs = self.__offset + frame * size
306
+
307
+ self.fp = self._fp
308
+
309
+ self.tile = [
310
+ ImageFile._Tile("raw", (0, 0) + self.size, offs, (self.rawmode, 0, -1))
311
+ ]
312
+
313
+ def tell(self) -> int:
314
+ return self.frame
315
+
316
+
317
+ #
318
+ # --------------------------------------------------------------------
319
+ # Save IM files
320
+
321
+
322
+ SAVE = {
323
+ # mode: (im type, raw mode)
324
+ "1": ("0 1", "1"),
325
+ "L": ("Greyscale", "L"),
326
+ "LA": ("LA", "LA;L"),
327
+ "P": ("Greyscale", "P"),
328
+ "PA": ("LA", "PA;L"),
329
+ "I": ("L 32S", "I;32S"),
330
+ "I;16": ("L 16", "I;16"),
331
+ "I;16L": ("L 16L", "I;16L"),
332
+ "I;16B": ("L 16B", "I;16B"),
333
+ "F": ("L 32F", "F;32F"),
334
+ "RGB": ("RGB", "RGB;L"),
335
+ "RGBA": ("RGBA", "RGBA;L"),
336
+ "RGBX": ("RGBX", "RGBX;L"),
337
+ "CMYK": ("CMYK", "CMYK;L"),
338
+ "YCbCr": ("YCC", "YCbCr;L"),
339
+ }
340
+
341
+
342
+ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
343
+ try:
344
+ image_type, rawmode = SAVE[im.mode]
345
+ except KeyError as e:
346
+ msg = f"Cannot save {im.mode} images as IM"
347
+ raise ValueError(msg) from e
348
+
349
+ frames = im.encoderinfo.get("frames", 1)
350
+
351
+ fp.write(f"Image type: {image_type} image\r\n".encode("ascii"))
352
+ if filename:
353
+ # Each line must be 100 characters or less,
354
+ # or: SyntaxError("not an IM file")
355
+ # 8 characters are used for "Name: " and "\r\n"
356
+ # Keep just the filename, ditch the potentially overlong path
357
+ if isinstance(filename, bytes):
358
+ filename = filename.decode("ascii")
359
+ name, ext = os.path.splitext(os.path.basename(filename))
360
+ name = "".join([name[: 92 - len(ext)], ext])
361
+
362
+ fp.write(f"Name: {name}\r\n".encode("ascii"))
363
+ fp.write(f"Image size (x*y): {im.size[0]}*{im.size[1]}\r\n".encode("ascii"))
364
+ fp.write(f"File size (no of images): {frames}\r\n".encode("ascii"))
365
+ if im.mode in ["P", "PA"]:
366
+ fp.write(b"Lut: 1\r\n")
367
+ fp.write(b"\000" * (511 - fp.tell()) + b"\032")
368
+ if im.mode in ["P", "PA"]:
369
+ im_palette = im.im.getpalette("RGB", "RGB;L")
370
+ colors = len(im_palette) // 3
371
+ palette = b""
372
+ for i in range(3):
373
+ palette += im_palette[colors * i : colors * (i + 1)]
374
+ palette += b"\x00" * (256 - colors)
375
+ fp.write(palette) # 768 bytes
376
+ ImageFile._save(
377
+ im, fp, [ImageFile._Tile("raw", (0, 0) + im.size, 0, (rawmode, 0, -1))]
378
+ )
379
+
380
+
381
+ #
382
+ # --------------------------------------------------------------------
383
+ # Registry
384
+
385
+
386
+ Image.register_open(ImImageFile.format, ImImageFile)
387
+ Image.register_save(ImImageFile.format, _save)
388
+
389
+ Image.register_extension(ImImageFile.format, ".im")
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/Image.py ADDED
The diff for this file is too large to render. See raw diff
 
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/ImageChops.py ADDED
@@ -0,0 +1,311 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # standard channel operations
6
+ #
7
+ # History:
8
+ # 1996-03-24 fl Created
9
+ # 1996-08-13 fl Added logical operations (for "1" images)
10
+ # 2000-10-12 fl Added offset method (from Image.py)
11
+ #
12
+ # Copyright (c) 1997-2000 by Secret Labs AB
13
+ # Copyright (c) 1996-2000 by Fredrik Lundh
14
+ #
15
+ # See the README file for information on usage and redistribution.
16
+ #
17
+
18
+ from __future__ import annotations
19
+
20
+ from . import Image
21
+
22
+
23
+ def constant(image: Image.Image, value: int) -> Image.Image:
24
+ """Fill a channel with a given gray level.
25
+
26
+ :rtype: :py:class:`~PIL.Image.Image`
27
+ """
28
+
29
+ return Image.new("L", image.size, value)
30
+
31
+
32
+ def duplicate(image: Image.Image) -> Image.Image:
33
+ """Copy a channel. Alias for :py:meth:`PIL.Image.Image.copy`.
34
+
35
+ :rtype: :py:class:`~PIL.Image.Image`
36
+ """
37
+
38
+ return image.copy()
39
+
40
+
41
+ def invert(image: Image.Image) -> Image.Image:
42
+ """
43
+ Invert an image (channel). ::
44
+
45
+ out = MAX - image
46
+
47
+ :rtype: :py:class:`~PIL.Image.Image`
48
+ """
49
+
50
+ image.load()
51
+ return image._new(image.im.chop_invert())
52
+
53
+
54
+ def lighter(image1: Image.Image, image2: Image.Image) -> Image.Image:
55
+ """
56
+ Compares the two images, pixel by pixel, and returns a new image containing
57
+ the lighter values. ::
58
+
59
+ out = max(image1, image2)
60
+
61
+ :rtype: :py:class:`~PIL.Image.Image`
62
+ """
63
+
64
+ image1.load()
65
+ image2.load()
66
+ return image1._new(image1.im.chop_lighter(image2.im))
67
+
68
+
69
+ def darker(image1: Image.Image, image2: Image.Image) -> Image.Image:
70
+ """
71
+ Compares the two images, pixel by pixel, and returns a new image containing
72
+ the darker values. ::
73
+
74
+ out = min(image1, image2)
75
+
76
+ :rtype: :py:class:`~PIL.Image.Image`
77
+ """
78
+
79
+ image1.load()
80
+ image2.load()
81
+ return image1._new(image1.im.chop_darker(image2.im))
82
+
83
+
84
+ def difference(image1: Image.Image, image2: Image.Image) -> Image.Image:
85
+ """
86
+ Returns the absolute value of the pixel-by-pixel difference between the two
87
+ images. ::
88
+
89
+ out = abs(image1 - image2)
90
+
91
+ :rtype: :py:class:`~PIL.Image.Image`
92
+ """
93
+
94
+ image1.load()
95
+ image2.load()
96
+ return image1._new(image1.im.chop_difference(image2.im))
97
+
98
+
99
+ def multiply(image1: Image.Image, image2: Image.Image) -> Image.Image:
100
+ """
101
+ Superimposes two images on top of each other.
102
+
103
+ If you multiply an image with a solid black image, the result is black. If
104
+ you multiply with a solid white image, the image is unaffected. ::
105
+
106
+ out = image1 * image2 / MAX
107
+
108
+ :rtype: :py:class:`~PIL.Image.Image`
109
+ """
110
+
111
+ image1.load()
112
+ image2.load()
113
+ return image1._new(image1.im.chop_multiply(image2.im))
114
+
115
+
116
+ def screen(image1: Image.Image, image2: Image.Image) -> Image.Image:
117
+ """
118
+ Superimposes two inverted images on top of each other. ::
119
+
120
+ out = MAX - ((MAX - image1) * (MAX - image2) / MAX)
121
+
122
+ :rtype: :py:class:`~PIL.Image.Image`
123
+ """
124
+
125
+ image1.load()
126
+ image2.load()
127
+ return image1._new(image1.im.chop_screen(image2.im))
128
+
129
+
130
+ def soft_light(image1: Image.Image, image2: Image.Image) -> Image.Image:
131
+ """
132
+ Superimposes two images on top of each other using the Soft Light algorithm
133
+
134
+ :rtype: :py:class:`~PIL.Image.Image`
135
+ """
136
+
137
+ image1.load()
138
+ image2.load()
139
+ return image1._new(image1.im.chop_soft_light(image2.im))
140
+
141
+
142
+ def hard_light(image1: Image.Image, image2: Image.Image) -> Image.Image:
143
+ """
144
+ Superimposes two images on top of each other using the Hard Light algorithm
145
+
146
+ :rtype: :py:class:`~PIL.Image.Image`
147
+ """
148
+
149
+ image1.load()
150
+ image2.load()
151
+ return image1._new(image1.im.chop_hard_light(image2.im))
152
+
153
+
154
+ def overlay(image1: Image.Image, image2: Image.Image) -> Image.Image:
155
+ """
156
+ Superimposes two images on top of each other using the Overlay algorithm
157
+
158
+ :rtype: :py:class:`~PIL.Image.Image`
159
+ """
160
+
161
+ image1.load()
162
+ image2.load()
163
+ return image1._new(image1.im.chop_overlay(image2.im))
164
+
165
+
166
+ def add(
167
+ image1: Image.Image, image2: Image.Image, scale: float = 1.0, offset: float = 0
168
+ ) -> Image.Image:
169
+ """
170
+ Adds two images, dividing the result by scale and adding the
171
+ offset. If omitted, scale defaults to 1.0, and offset to 0.0. ::
172
+
173
+ out = ((image1 + image2) / scale + offset)
174
+
175
+ :rtype: :py:class:`~PIL.Image.Image`
176
+ """
177
+
178
+ image1.load()
179
+ image2.load()
180
+ return image1._new(image1.im.chop_add(image2.im, scale, offset))
181
+
182
+
183
+ def subtract(
184
+ image1: Image.Image, image2: Image.Image, scale: float = 1.0, offset: float = 0
185
+ ) -> Image.Image:
186
+ """
187
+ Subtracts two images, dividing the result by scale and adding the offset.
188
+ If omitted, scale defaults to 1.0, and offset to 0.0. ::
189
+
190
+ out = ((image1 - image2) / scale + offset)
191
+
192
+ :rtype: :py:class:`~PIL.Image.Image`
193
+ """
194
+
195
+ image1.load()
196
+ image2.load()
197
+ return image1._new(image1.im.chop_subtract(image2.im, scale, offset))
198
+
199
+
200
+ def add_modulo(image1: Image.Image, image2: Image.Image) -> Image.Image:
201
+ """Add two images, without clipping the result. ::
202
+
203
+ out = ((image1 + image2) % MAX)
204
+
205
+ :rtype: :py:class:`~PIL.Image.Image`
206
+ """
207
+
208
+ image1.load()
209
+ image2.load()
210
+ return image1._new(image1.im.chop_add_modulo(image2.im))
211
+
212
+
213
+ def subtract_modulo(image1: Image.Image, image2: Image.Image) -> Image.Image:
214
+ """Subtract two images, without clipping the result. ::
215
+
216
+ out = ((image1 - image2) % MAX)
217
+
218
+ :rtype: :py:class:`~PIL.Image.Image`
219
+ """
220
+
221
+ image1.load()
222
+ image2.load()
223
+ return image1._new(image1.im.chop_subtract_modulo(image2.im))
224
+
225
+
226
+ def logical_and(image1: Image.Image, image2: Image.Image) -> Image.Image:
227
+ """Logical AND between two images.
228
+
229
+ Both of the images must have mode "1". If you would like to perform a
230
+ logical AND on an image with a mode other than "1", try
231
+ :py:meth:`~PIL.ImageChops.multiply` instead, using a black-and-white mask
232
+ as the second image. ::
233
+
234
+ out = ((image1 and image2) % MAX)
235
+
236
+ :rtype: :py:class:`~PIL.Image.Image`
237
+ """
238
+
239
+ image1.load()
240
+ image2.load()
241
+ return image1._new(image1.im.chop_and(image2.im))
242
+
243
+
244
+ def logical_or(image1: Image.Image, image2: Image.Image) -> Image.Image:
245
+ """Logical OR between two images.
246
+
247
+ Both of the images must have mode "1". ::
248
+
249
+ out = ((image1 or image2) % MAX)
250
+
251
+ :rtype: :py:class:`~PIL.Image.Image`
252
+ """
253
+
254
+ image1.load()
255
+ image2.load()
256
+ return image1._new(image1.im.chop_or(image2.im))
257
+
258
+
259
+ def logical_xor(image1: Image.Image, image2: Image.Image) -> Image.Image:
260
+ """Logical XOR between two images.
261
+
262
+ Both of the images must have mode "1". ::
263
+
264
+ out = ((bool(image1) != bool(image2)) % MAX)
265
+
266
+ :rtype: :py:class:`~PIL.Image.Image`
267
+ """
268
+
269
+ image1.load()
270
+ image2.load()
271
+ return image1._new(image1.im.chop_xor(image2.im))
272
+
273
+
274
+ def blend(image1: Image.Image, image2: Image.Image, alpha: float) -> Image.Image:
275
+ """Blend images using constant transparency weight. Alias for
276
+ :py:func:`PIL.Image.blend`.
277
+
278
+ :rtype: :py:class:`~PIL.Image.Image`
279
+ """
280
+
281
+ return Image.blend(image1, image2, alpha)
282
+
283
+
284
+ def composite(
285
+ image1: Image.Image, image2: Image.Image, mask: Image.Image
286
+ ) -> Image.Image:
287
+ """Create composite using transparency mask. Alias for
288
+ :py:func:`PIL.Image.composite`.
289
+
290
+ :rtype: :py:class:`~PIL.Image.Image`
291
+ """
292
+
293
+ return Image.composite(image1, image2, mask)
294
+
295
+
296
+ def offset(image: Image.Image, xoffset: int, yoffset: int | None = None) -> Image.Image:
297
+ """Returns a copy of the image where data has been offset by the given
298
+ distances. Data wraps around the edges. If ``yoffset`` is omitted, it
299
+ is assumed to be equal to ``xoffset``.
300
+
301
+ :param image: Input image.
302
+ :param xoffset: The horizontal distance.
303
+ :param yoffset: The vertical distance. If omitted, both
304
+ distances are set to the same value.
305
+ :rtype: :py:class:`~PIL.Image.Image`
306
+ """
307
+
308
+ if yoffset is None:
309
+ yoffset = xoffset
310
+ image.load()
311
+ return image._new(image.im.offset(xoffset, yoffset))
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/ImageCms.py ADDED
@@ -0,0 +1,1123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ self.filename = None
252
+ self.product_name = None # profile.product_name
253
+ self.product_info = None # profile.product_info
254
+
255
+ if isinstance(profile, str):
256
+ if sys.platform == "win32":
257
+ profile_bytes_path = profile.encode()
258
+ try:
259
+ profile_bytes_path.decode("ascii")
260
+ except UnicodeDecodeError:
261
+ with open(profile, "rb") as f:
262
+ self.profile = core.profile_frombytes(f.read())
263
+ return
264
+ self.filename = profile
265
+ self.profile = core.profile_open(profile)
266
+ elif hasattr(profile, "read"):
267
+ self.profile = core.profile_frombytes(profile.read())
268
+ elif isinstance(profile, core.CmsProfile):
269
+ self.profile = profile
270
+ else:
271
+ msg = "Invalid type for Profile" # type: ignore[unreachable]
272
+ raise TypeError(msg)
273
+
274
+ def tobytes(self) -> bytes:
275
+ """
276
+ Returns the profile in a format suitable for embedding in
277
+ saved images.
278
+
279
+ :returns: a bytes object containing the ICC profile.
280
+ """
281
+
282
+ return core.profile_tobytes(self.profile)
283
+
284
+
285
+ class ImageCmsTransform(Image.ImagePointHandler):
286
+ """
287
+ Transform. This can be used with the procedural API, or with the standard
288
+ :py:func:`~PIL.Image.Image.point` method.
289
+
290
+ Will return the output profile in the ``output.info['icc_profile']``.
291
+ """
292
+
293
+ def __init__(
294
+ self,
295
+ input: ImageCmsProfile,
296
+ output: ImageCmsProfile,
297
+ input_mode: str,
298
+ output_mode: str,
299
+ intent: Intent = Intent.PERCEPTUAL,
300
+ proof: ImageCmsProfile | None = None,
301
+ proof_intent: Intent = Intent.ABSOLUTE_COLORIMETRIC,
302
+ flags: Flags = Flags.NONE,
303
+ ):
304
+ supported_modes = (
305
+ "RGB",
306
+ "RGBA",
307
+ "RGBX",
308
+ "CMYK",
309
+ "I;16",
310
+ "I;16L",
311
+ "I;16B",
312
+ "YCbCr",
313
+ "LAB",
314
+ "L",
315
+ "1",
316
+ )
317
+ for mode in (input_mode, output_mode):
318
+ if mode not in supported_modes:
319
+ deprecate(
320
+ mode,
321
+ 12,
322
+ {
323
+ "L;16": "I;16 or I;16L",
324
+ "L:16B": "I;16B",
325
+ "YCCA": "YCbCr",
326
+ "YCC": "YCbCr",
327
+ }.get(mode),
328
+ )
329
+ if proof is None:
330
+ self.transform = core.buildTransform(
331
+ input.profile, output.profile, input_mode, output_mode, intent, flags
332
+ )
333
+ else:
334
+ self.transform = core.buildProofTransform(
335
+ input.profile,
336
+ output.profile,
337
+ proof.profile,
338
+ input_mode,
339
+ output_mode,
340
+ intent,
341
+ proof_intent,
342
+ flags,
343
+ )
344
+ # Note: inputMode and outputMode are for pyCMS compatibility only
345
+ self.input_mode = self.inputMode = input_mode
346
+ self.output_mode = self.outputMode = output_mode
347
+
348
+ self.output_profile = output
349
+
350
+ def point(self, im: Image.Image) -> Image.Image:
351
+ return self.apply(im)
352
+
353
+ def apply(self, im: Image.Image, imOut: Image.Image | None = None) -> Image.Image:
354
+ if imOut is None:
355
+ imOut = Image.new(self.output_mode, im.size, None)
356
+ self.transform.apply(im.getim(), imOut.getim())
357
+ imOut.info["icc_profile"] = self.output_profile.tobytes()
358
+ return imOut
359
+
360
+ def apply_in_place(self, im: Image.Image) -> Image.Image:
361
+ if im.mode != self.output_mode:
362
+ msg = "mode mismatch"
363
+ raise ValueError(msg) # wrong output mode
364
+ self.transform.apply(im.getim(), im.getim())
365
+ im.info["icc_profile"] = self.output_profile.tobytes()
366
+ return im
367
+
368
+
369
+ def get_display_profile(handle: SupportsInt | None = None) -> ImageCmsProfile | None:
370
+ """
371
+ (experimental) Fetches the profile for the current display device.
372
+
373
+ :returns: ``None`` if the profile is not known.
374
+ """
375
+
376
+ if sys.platform != "win32":
377
+ return None
378
+
379
+ from . import ImageWin # type: ignore[unused-ignore, unreachable]
380
+
381
+ if isinstance(handle, ImageWin.HDC):
382
+ profile = core.get_display_profile_win32(int(handle), 1)
383
+ else:
384
+ profile = core.get_display_profile_win32(int(handle or 0))
385
+ if profile is None:
386
+ return None
387
+ return ImageCmsProfile(profile)
388
+
389
+
390
+ # --------------------------------------------------------------------.
391
+ # pyCMS compatible layer
392
+ # --------------------------------------------------------------------.
393
+
394
+
395
+ class PyCMSError(Exception):
396
+ """(pyCMS) Exception class.
397
+ This is used for all errors in the pyCMS API."""
398
+
399
+ pass
400
+
401
+
402
+ def profileToProfile(
403
+ im: Image.Image,
404
+ inputProfile: _CmsProfileCompatible,
405
+ outputProfile: _CmsProfileCompatible,
406
+ renderingIntent: Intent = Intent.PERCEPTUAL,
407
+ outputMode: str | None = None,
408
+ inPlace: bool = False,
409
+ flags: Flags = Flags.NONE,
410
+ ) -> Image.Image | None:
411
+ """
412
+ (pyCMS) Applies an ICC transformation to a given image, mapping from
413
+ ``inputProfile`` to ``outputProfile``.
414
+
415
+ If the input or output profiles specified are not valid filenames, a
416
+ :exc:`PyCMSError` will be raised. If ``inPlace`` is ``True`` and
417
+ ``outputMode != im.mode``, a :exc:`PyCMSError` will be raised.
418
+ If an error occurs during application of the profiles,
419
+ a :exc:`PyCMSError` will be raised.
420
+ If ``outputMode`` is not a mode supported by the ``outputProfile`` (or by pyCMS),
421
+ a :exc:`PyCMSError` will be raised.
422
+
423
+ This function applies an ICC transformation to im from ``inputProfile``'s
424
+ color space to ``outputProfile``'s color space using the specified rendering
425
+ intent to decide how to handle out-of-gamut colors.
426
+
427
+ ``outputMode`` can be used to specify that a color mode conversion is to
428
+ be done using these profiles, but the specified profiles must be able
429
+ to handle that mode. I.e., if converting im from RGB to CMYK using
430
+ profiles, the input profile must handle RGB data, and the output
431
+ profile must handle CMYK data.
432
+
433
+ :param im: An open :py:class:`~PIL.Image.Image` object (i.e. Image.new(...)
434
+ or Image.open(...), etc.)
435
+ :param inputProfile: String, as a valid filename path to the ICC input
436
+ profile you wish to use for this image, or a profile object
437
+ :param outputProfile: String, as a valid filename path to the ICC output
438
+ profile you wish to use for this image, or a profile object
439
+ :param renderingIntent: Integer (0-3) specifying the rendering intent you
440
+ wish to use for the transform
441
+
442
+ ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
443
+ ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
444
+ ImageCms.Intent.SATURATION = 2
445
+ ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
446
+
447
+ see the pyCMS documentation for details on rendering intents and what
448
+ they do.
449
+ :param outputMode: A valid PIL mode for the output image (i.e. "RGB",
450
+ "CMYK", etc.). Note: if rendering the image "inPlace", outputMode
451
+ MUST be the same mode as the input, or omitted completely. If
452
+ omitted, the outputMode will be the same as the mode of the input
453
+ image (im.mode)
454
+ :param inPlace: Boolean. If ``True``, the original image is modified in-place,
455
+ and ``None`` is returned. If ``False`` (default), a new
456
+ :py:class:`~PIL.Image.Image` object is returned with the transform applied.
457
+ :param flags: Integer (0-...) specifying additional flags
458
+ :returns: Either None or a new :py:class:`~PIL.Image.Image` object, depending on
459
+ the value of ``inPlace``
460
+ :exception PyCMSError:
461
+ """
462
+
463
+ if outputMode is None:
464
+ outputMode = im.mode
465
+
466
+ if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3):
467
+ msg = "renderingIntent must be an integer between 0 and 3"
468
+ raise PyCMSError(msg)
469
+
470
+ if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
471
+ msg = f"flags must be an integer between 0 and {_MAX_FLAG}"
472
+ raise PyCMSError(msg)
473
+
474
+ try:
475
+ if not isinstance(inputProfile, ImageCmsProfile):
476
+ inputProfile = ImageCmsProfile(inputProfile)
477
+ if not isinstance(outputProfile, ImageCmsProfile):
478
+ outputProfile = ImageCmsProfile(outputProfile)
479
+ transform = ImageCmsTransform(
480
+ inputProfile,
481
+ outputProfile,
482
+ im.mode,
483
+ outputMode,
484
+ renderingIntent,
485
+ flags=flags,
486
+ )
487
+ if inPlace:
488
+ transform.apply_in_place(im)
489
+ imOut = None
490
+ else:
491
+ imOut = transform.apply(im)
492
+ except (OSError, TypeError, ValueError) as v:
493
+ raise PyCMSError(v) from v
494
+
495
+ return imOut
496
+
497
+
498
+ def getOpenProfile(
499
+ profileFilename: str | SupportsRead[bytes] | core.CmsProfile,
500
+ ) -> ImageCmsProfile:
501
+ """
502
+ (pyCMS) Opens an ICC profile file.
503
+
504
+ The PyCMSProfile object can be passed back into pyCMS for use in creating
505
+ transforms and such (as in ImageCms.buildTransformFromOpenProfiles()).
506
+
507
+ If ``profileFilename`` is not a valid filename for an ICC profile,
508
+ a :exc:`PyCMSError` will be raised.
509
+
510
+ :param profileFilename: String, as a valid filename path to the ICC profile
511
+ you wish to open, or a file-like object.
512
+ :returns: A CmsProfile class object.
513
+ :exception PyCMSError:
514
+ """
515
+
516
+ try:
517
+ return ImageCmsProfile(profileFilename)
518
+ except (OSError, TypeError, ValueError) as v:
519
+ raise PyCMSError(v) from v
520
+
521
+
522
+ def buildTransform(
523
+ inputProfile: _CmsProfileCompatible,
524
+ outputProfile: _CmsProfileCompatible,
525
+ inMode: str,
526
+ outMode: str,
527
+ renderingIntent: Intent = Intent.PERCEPTUAL,
528
+ flags: Flags = Flags.NONE,
529
+ ) -> ImageCmsTransform:
530
+ """
531
+ (pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the
532
+ ``outputProfile``. Use applyTransform to apply the transform to a given
533
+ image.
534
+
535
+ If the input or output profiles specified are not valid filenames, a
536
+ :exc:`PyCMSError` will be raised. If an error occurs during creation
537
+ of the transform, a :exc:`PyCMSError` will be raised.
538
+
539
+ If ``inMode`` or ``outMode`` are not a mode supported by the ``outputProfile``
540
+ (or by pyCMS), a :exc:`PyCMSError` will be raised.
541
+
542
+ This function builds and returns an ICC transform from the ``inputProfile``
543
+ to the ``outputProfile`` using the ``renderingIntent`` to determine what to do
544
+ with out-of-gamut colors. It will ONLY work for converting images that
545
+ are in ``inMode`` to images that are in ``outMode`` color format (PIL mode,
546
+ i.e. "RGB", "RGBA", "CMYK", etc.).
547
+
548
+ Building the transform is a fair part of the overhead in
549
+ ImageCms.profileToProfile(), so if you're planning on converting multiple
550
+ images using the same input/output settings, this can save you time.
551
+ Once you have a transform object, it can be used with
552
+ ImageCms.applyProfile() to convert images without the need to re-compute
553
+ the lookup table for the transform.
554
+
555
+ The reason pyCMS returns a class object rather than a handle directly
556
+ to the transform is that it needs to keep track of the PIL input/output
557
+ modes that the transform is meant for. These attributes are stored in
558
+ the ``inMode`` and ``outMode`` attributes of the object (which can be
559
+ manually overridden if you really want to, but I don't know of any
560
+ time that would be of use, or would even work).
561
+
562
+ :param inputProfile: String, as a valid filename path to the ICC input
563
+ profile you wish to use for this transform, or a profile object
564
+ :param outputProfile: String, as a valid filename path to the ICC output
565
+ profile you wish to use for this transform, or a profile object
566
+ :param inMode: String, as a valid PIL mode that the appropriate profile
567
+ also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
568
+ :param outMode: String, as a valid PIL mode that the appropriate profile
569
+ also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
570
+ :param renderingIntent: Integer (0-3) specifying the rendering intent you
571
+ wish to use for the transform
572
+
573
+ ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
574
+ ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
575
+ ImageCms.Intent.SATURATION = 2
576
+ ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
577
+
578
+ see the pyCMS documentation for details on rendering intents and what
579
+ they do.
580
+ :param flags: Integer (0-...) specifying additional flags
581
+ :returns: A CmsTransform class object.
582
+ :exception PyCMSError:
583
+ """
584
+
585
+ if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3):
586
+ msg = "renderingIntent must be an integer between 0 and 3"
587
+ raise PyCMSError(msg)
588
+
589
+ if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
590
+ msg = f"flags must be an integer between 0 and {_MAX_FLAG}"
591
+ raise PyCMSError(msg)
592
+
593
+ try:
594
+ if not isinstance(inputProfile, ImageCmsProfile):
595
+ inputProfile = ImageCmsProfile(inputProfile)
596
+ if not isinstance(outputProfile, ImageCmsProfile):
597
+ outputProfile = ImageCmsProfile(outputProfile)
598
+ return ImageCmsTransform(
599
+ inputProfile, outputProfile, inMode, outMode, renderingIntent, flags=flags
600
+ )
601
+ except (OSError, TypeError, ValueError) as v:
602
+ raise PyCMSError(v) from v
603
+
604
+
605
+ def buildProofTransform(
606
+ inputProfile: _CmsProfileCompatible,
607
+ outputProfile: _CmsProfileCompatible,
608
+ proofProfile: _CmsProfileCompatible,
609
+ inMode: str,
610
+ outMode: str,
611
+ renderingIntent: Intent = Intent.PERCEPTUAL,
612
+ proofRenderingIntent: Intent = Intent.ABSOLUTE_COLORIMETRIC,
613
+ flags: Flags = Flags.SOFTPROOFING,
614
+ ) -> ImageCmsTransform:
615
+ """
616
+ (pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the
617
+ ``outputProfile``, but tries to simulate the result that would be
618
+ obtained on the ``proofProfile`` device.
619
+
620
+ If the input, output, or proof profiles specified are not valid
621
+ filenames, a :exc:`PyCMSError` will be raised.
622
+
623
+ If an error occurs during creation of the transform,
624
+ a :exc:`PyCMSError` will be raised.
625
+
626
+ If ``inMode`` or ``outMode`` are not a mode supported by the ``outputProfile``
627
+ (or by pyCMS), a :exc:`PyCMSError` will be raised.
628
+
629
+ This function builds and returns an ICC transform from the ``inputProfile``
630
+ to the ``outputProfile``, but tries to simulate the result that would be
631
+ obtained on the ``proofProfile`` device using ``renderingIntent`` and
632
+ ``proofRenderingIntent`` to determine what to do with out-of-gamut
633
+ colors. This is known as "soft-proofing". It will ONLY work for
634
+ converting images that are in ``inMode`` to images that are in outMode
635
+ color format (PIL mode, i.e. "RGB", "RGBA", "CMYK", etc.).
636
+
637
+ Usage of the resulting transform object is exactly the same as with
638
+ ImageCms.buildTransform().
639
+
640
+ Proof profiling is generally used when using an output device to get a
641
+ good idea of what the final printed/displayed image would look like on
642
+ the ``proofProfile`` device when it's quicker and easier to use the
643
+ output device for judging color. Generally, this means that the
644
+ output device is a monitor, or a dye-sub printer (etc.), and the simulated
645
+ device is something more expensive, complicated, or time consuming
646
+ (making it difficult to make a real print for color judgement purposes).
647
+
648
+ Soft-proofing basically functions by adjusting the colors on the
649
+ output device to match the colors of the device being simulated. However,
650
+ when the simulated device has a much wider gamut than the output
651
+ device, you may obtain marginal results.
652
+
653
+ :param inputProfile: String, as a valid filename path to the ICC input
654
+ profile you wish to use for this transform, or a profile object
655
+ :param outputProfile: String, as a valid filename path to the ICC output
656
+ (monitor, usually) profile you wish to use for this transform, or a
657
+ profile object
658
+ :param proofProfile: String, as a valid filename path to the ICC proof
659
+ profile you wish to use for this transform, or a profile object
660
+ :param inMode: String, as a valid PIL mode that the appropriate profile
661
+ also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
662
+ :param outMode: String, as a valid PIL mode that the appropriate profile
663
+ also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
664
+ :param renderingIntent: Integer (0-3) specifying the rendering intent you
665
+ wish to use for the input->proof (simulated) transform
666
+
667
+ ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
668
+ ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
669
+ ImageCms.Intent.SATURATION = 2
670
+ ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
671
+
672
+ see the pyCMS documentation for details on rendering intents and what
673
+ they do.
674
+ :param proofRenderingIntent: Integer (0-3) specifying the rendering intent
675
+ you wish to use for proof->output transform
676
+
677
+ ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
678
+ ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
679
+ ImageCms.Intent.SATURATION = 2
680
+ ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
681
+
682
+ see the pyCMS documentation for details on rendering intents and what
683
+ they do.
684
+ :param flags: Integer (0-...) specifying additional flags
685
+ :returns: A CmsTransform class object.
686
+ :exception PyCMSError:
687
+ """
688
+
689
+ if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3):
690
+ msg = "renderingIntent must be an integer between 0 and 3"
691
+ raise PyCMSError(msg)
692
+
693
+ if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
694
+ msg = f"flags must be an integer between 0 and {_MAX_FLAG}"
695
+ raise PyCMSError(msg)
696
+
697
+ try:
698
+ if not isinstance(inputProfile, ImageCmsProfile):
699
+ inputProfile = ImageCmsProfile(inputProfile)
700
+ if not isinstance(outputProfile, ImageCmsProfile):
701
+ outputProfile = ImageCmsProfile(outputProfile)
702
+ if not isinstance(proofProfile, ImageCmsProfile):
703
+ proofProfile = ImageCmsProfile(proofProfile)
704
+ return ImageCmsTransform(
705
+ inputProfile,
706
+ outputProfile,
707
+ inMode,
708
+ outMode,
709
+ renderingIntent,
710
+ proofProfile,
711
+ proofRenderingIntent,
712
+ flags,
713
+ )
714
+ except (OSError, TypeError, ValueError) as v:
715
+ raise PyCMSError(v) from v
716
+
717
+
718
+ buildTransformFromOpenProfiles = buildTransform
719
+ buildProofTransformFromOpenProfiles = buildProofTransform
720
+
721
+
722
+ def applyTransform(
723
+ im: Image.Image, transform: ImageCmsTransform, inPlace: bool = False
724
+ ) -> Image.Image | None:
725
+ """
726
+ (pyCMS) Applies a transform to a given image.
727
+
728
+ If ``im.mode != transform.input_mode``, a :exc:`PyCMSError` is raised.
729
+
730
+ If ``inPlace`` is ``True`` and ``transform.input_mode != transform.output_mode``, a
731
+ :exc:`PyCMSError` is raised.
732
+
733
+ If ``im.mode``, ``transform.input_mode`` or ``transform.output_mode`` is not
734
+ supported by pyCMSdll or the profiles you used for the transform, a
735
+ :exc:`PyCMSError` is raised.
736
+
737
+ If an error occurs while the transform is being applied,
738
+ a :exc:`PyCMSError` is raised.
739
+
740
+ This function applies a pre-calculated transform (from
741
+ ImageCms.buildTransform() or ImageCms.buildTransformFromOpenProfiles())
742
+ to an image. The transform can be used for multiple images, saving
743
+ considerable calculation time if doing the same conversion multiple times.
744
+
745
+ If you want to modify im in-place instead of receiving a new image as
746
+ the return value, set ``inPlace`` to ``True``. This can only be done if
747
+ ``transform.input_mode`` and ``transform.output_mode`` are the same, because we
748
+ can't change the mode in-place (the buffer sizes for some modes are
749
+ different). The default behavior is to return a new :py:class:`~PIL.Image.Image`
750
+ object of the same dimensions in mode ``transform.output_mode``.
751
+
752
+ :param im: An :py:class:`~PIL.Image.Image` object, and ``im.mode`` must be the same
753
+ as the ``input_mode`` supported by the transform.
754
+ :param transform: A valid CmsTransform class object
755
+ :param inPlace: Bool. If ``True``, ``im`` is modified in place and ``None`` is
756
+ returned, if ``False``, a new :py:class:`~PIL.Image.Image` object with the
757
+ transform applied is returned (and ``im`` is not changed). The default is
758
+ ``False``.
759
+ :returns: Either ``None``, or a new :py:class:`~PIL.Image.Image` object,
760
+ depending on the value of ``inPlace``. The profile will be returned in
761
+ the image's ``info['icc_profile']``.
762
+ :exception PyCMSError:
763
+ """
764
+
765
+ try:
766
+ if inPlace:
767
+ transform.apply_in_place(im)
768
+ imOut = None
769
+ else:
770
+ imOut = transform.apply(im)
771
+ except (TypeError, ValueError) as v:
772
+ raise PyCMSError(v) from v
773
+
774
+ return imOut
775
+
776
+
777
+ def createProfile(
778
+ colorSpace: Literal["LAB", "XYZ", "sRGB"], colorTemp: SupportsFloat = 0
779
+ ) -> core.CmsProfile:
780
+ """
781
+ (pyCMS) Creates a profile.
782
+
783
+ If colorSpace not in ``["LAB", "XYZ", "sRGB"]``,
784
+ a :exc:`PyCMSError` is raised.
785
+
786
+ If using LAB and ``colorTemp`` is not a positive integer,
787
+ a :exc:`PyCMSError` is raised.
788
+
789
+ If an error occurs while creating the profile,
790
+ a :exc:`PyCMSError` is raised.
791
+
792
+ Use this function to create common profiles on-the-fly instead of
793
+ having to supply a profile on disk and knowing the path to it. It
794
+ returns a normal CmsProfile object that can be passed to
795
+ ImageCms.buildTransformFromOpenProfiles() to create a transform to apply
796
+ to images.
797
+
798
+ :param colorSpace: String, the color space of the profile you wish to
799
+ create.
800
+ Currently only "LAB", "XYZ", and "sRGB" are supported.
801
+ :param colorTemp: Positive number for the white point for the profile, in
802
+ degrees Kelvin (i.e. 5000, 6500, 9600, etc.). The default is for D50
803
+ illuminant if omitted (5000k). colorTemp is ONLY applied to LAB
804
+ profiles, and is ignored for XYZ and sRGB.
805
+ :returns: A CmsProfile class object
806
+ :exception PyCMSError:
807
+ """
808
+
809
+ if colorSpace not in ["LAB", "XYZ", "sRGB"]:
810
+ msg = (
811
+ f"Color space not supported for on-the-fly profile creation ({colorSpace})"
812
+ )
813
+ raise PyCMSError(msg)
814
+
815
+ if colorSpace == "LAB":
816
+ try:
817
+ colorTemp = float(colorTemp)
818
+ except (TypeError, ValueError) as e:
819
+ msg = f'Color temperature must be numeric, "{colorTemp}" not valid'
820
+ raise PyCMSError(msg) from e
821
+
822
+ try:
823
+ return core.createProfile(colorSpace, colorTemp)
824
+ except (TypeError, ValueError) as v:
825
+ raise PyCMSError(v) from v
826
+
827
+
828
+ def getProfileName(profile: _CmsProfileCompatible) -> str:
829
+ """
830
+
831
+ (pyCMS) Gets the internal product name for the given profile.
832
+
833
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile,
834
+ a :exc:`PyCMSError` is raised If an error occurs while trying
835
+ to obtain the name tag, a :exc:`PyCMSError` is raised.
836
+
837
+ Use this function to obtain the INTERNAL name of the profile (stored
838
+ in an ICC tag in the profile itself), usually the one used when the
839
+ profile was originally created. Sometimes this tag also contains
840
+ additional information supplied by the creator.
841
+
842
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
843
+ filename of an ICC profile.
844
+ :returns: A string containing the internal name of the profile as stored
845
+ in an ICC tag.
846
+ :exception PyCMSError:
847
+ """
848
+
849
+ try:
850
+ # add an extra newline to preserve pyCMS compatibility
851
+ if not isinstance(profile, ImageCmsProfile):
852
+ profile = ImageCmsProfile(profile)
853
+ # do it in python, not c.
854
+ # // name was "%s - %s" (model, manufacturer) || Description ,
855
+ # // but if the Model and Manufacturer were the same or the model
856
+ # // was long, Just the model, in 1.x
857
+ model = profile.profile.model
858
+ manufacturer = profile.profile.manufacturer
859
+
860
+ if not (model or manufacturer):
861
+ return (profile.profile.profile_description or "") + "\n"
862
+ if not manufacturer or (model and len(model) > 30):
863
+ return f"{model}\n"
864
+ return f"{model} - {manufacturer}\n"
865
+
866
+ except (AttributeError, OSError, TypeError, ValueError) as v:
867
+ raise PyCMSError(v) from v
868
+
869
+
870
+ def getProfileInfo(profile: _CmsProfileCompatible) -> str:
871
+ """
872
+ (pyCMS) Gets the internal product information for the given profile.
873
+
874
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile,
875
+ a :exc:`PyCMSError` is raised.
876
+
877
+ If an error occurs while trying to obtain the info tag,
878
+ a :exc:`PyCMSError` is raised.
879
+
880
+ Use this function to obtain the information stored in the profile's
881
+ info tag. This often contains details about the profile, and how it
882
+ was created, as supplied by the creator.
883
+
884
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
885
+ filename of an ICC profile.
886
+ :returns: A string containing the internal profile information stored in
887
+ an ICC tag.
888
+ :exception PyCMSError:
889
+ """
890
+
891
+ try:
892
+ if not isinstance(profile, ImageCmsProfile):
893
+ profile = ImageCmsProfile(profile)
894
+ # add an extra newline to preserve pyCMS compatibility
895
+ # Python, not C. the white point bits weren't working well,
896
+ # so skipping.
897
+ # info was description \r\n\r\n copyright \r\n\r\n K007 tag \r\n\r\n whitepoint
898
+ description = profile.profile.profile_description
899
+ cpright = profile.profile.copyright
900
+ elements = [element for element in (description, cpright) if element]
901
+ return "\r\n\r\n".join(elements) + "\r\n\r\n"
902
+
903
+ except (AttributeError, OSError, TypeError, ValueError) as v:
904
+ raise PyCMSError(v) from v
905
+
906
+
907
+ def getProfileCopyright(profile: _CmsProfileCompatible) -> str:
908
+ """
909
+ (pyCMS) Gets the copyright for the given profile.
910
+
911
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
912
+ :exc:`PyCMSError` is raised.
913
+
914
+ If an error occurs while trying to obtain the copyright tag,
915
+ a :exc:`PyCMSError` is raised.
916
+
917
+ Use this function to obtain the information stored in the profile's
918
+ copyright tag.
919
+
920
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
921
+ filename of an ICC profile.
922
+ :returns: A string containing the internal profile information stored in
923
+ an ICC tag.
924
+ :exception PyCMSError:
925
+ """
926
+ try:
927
+ # add an extra newline to preserve pyCMS compatibility
928
+ if not isinstance(profile, ImageCmsProfile):
929
+ profile = ImageCmsProfile(profile)
930
+ return (profile.profile.copyright or "") + "\n"
931
+ except (AttributeError, OSError, TypeError, ValueError) as v:
932
+ raise PyCMSError(v) from v
933
+
934
+
935
+ def getProfileManufacturer(profile: _CmsProfileCompatible) -> str:
936
+ """
937
+ (pyCMS) Gets the manufacturer for the given profile.
938
+
939
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
940
+ :exc:`PyCMSError` is raised.
941
+
942
+ If an error occurs while trying to obtain the manufacturer tag, a
943
+ :exc:`PyCMSError` is raised.
944
+
945
+ Use this function to obtain the information stored in the profile's
946
+ manufacturer tag.
947
+
948
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
949
+ filename of an ICC profile.
950
+ :returns: A string containing the internal profile information stored in
951
+ an ICC tag.
952
+ :exception PyCMSError:
953
+ """
954
+ try:
955
+ # add an extra newline to preserve pyCMS compatibility
956
+ if not isinstance(profile, ImageCmsProfile):
957
+ profile = ImageCmsProfile(profile)
958
+ return (profile.profile.manufacturer or "") + "\n"
959
+ except (AttributeError, OSError, TypeError, ValueError) as v:
960
+ raise PyCMSError(v) from v
961
+
962
+
963
+ def getProfileModel(profile: _CmsProfileCompatible) -> str:
964
+ """
965
+ (pyCMS) Gets the model for the given profile.
966
+
967
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
968
+ :exc:`PyCMSError` is raised.
969
+
970
+ If an error occurs while trying to obtain the model tag,
971
+ a :exc:`PyCMSError` is raised.
972
+
973
+ Use this function to obtain the information stored in the profile's
974
+ model tag.
975
+
976
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
977
+ filename of an ICC profile.
978
+ :returns: A string containing the internal profile information stored in
979
+ an ICC tag.
980
+ :exception PyCMSError:
981
+ """
982
+
983
+ try:
984
+ # add an extra newline to preserve pyCMS compatibility
985
+ if not isinstance(profile, ImageCmsProfile):
986
+ profile = ImageCmsProfile(profile)
987
+ return (profile.profile.model or "") + "\n"
988
+ except (AttributeError, OSError, TypeError, ValueError) as v:
989
+ raise PyCMSError(v) from v
990
+
991
+
992
+ def getProfileDescription(profile: _CmsProfileCompatible) -> str:
993
+ """
994
+ (pyCMS) Gets the description for the given profile.
995
+
996
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
997
+ :exc:`PyCMSError` is raised.
998
+
999
+ If an error occurs while trying to obtain the description tag,
1000
+ a :exc:`PyCMSError` is raised.
1001
+
1002
+ Use this function to obtain the information stored in the profile's
1003
+ description tag.
1004
+
1005
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
1006
+ filename of an ICC profile.
1007
+ :returns: A string containing the internal profile information stored in an
1008
+ ICC tag.
1009
+ :exception PyCMSError:
1010
+ """
1011
+
1012
+ try:
1013
+ # add an extra newline to preserve pyCMS compatibility
1014
+ if not isinstance(profile, ImageCmsProfile):
1015
+ profile = ImageCmsProfile(profile)
1016
+ return (profile.profile.profile_description or "") + "\n"
1017
+ except (AttributeError, OSError, TypeError, ValueError) as v:
1018
+ raise PyCMSError(v) from v
1019
+
1020
+
1021
+ def getDefaultIntent(profile: _CmsProfileCompatible) -> int:
1022
+ """
1023
+ (pyCMS) Gets the default intent name for the given profile.
1024
+
1025
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
1026
+ :exc:`PyCMSError` is raised.
1027
+
1028
+ If an error occurs while trying to obtain the default intent, a
1029
+ :exc:`PyCMSError` is raised.
1030
+
1031
+ Use this function to determine the default (and usually best optimized)
1032
+ rendering intent for this profile. Most profiles support multiple
1033
+ rendering intents, but are intended mostly for one type of conversion.
1034
+ If you wish to use a different intent than returned, use
1035
+ ImageCms.isIntentSupported() to verify it will work first.
1036
+
1037
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
1038
+ filename of an ICC profile.
1039
+ :returns: Integer 0-3 specifying the default rendering intent for this
1040
+ profile.
1041
+
1042
+ ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
1043
+ ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
1044
+ ImageCms.Intent.SATURATION = 2
1045
+ ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
1046
+
1047
+ see the pyCMS documentation for details on rendering intents and what
1048
+ they do.
1049
+ :exception PyCMSError:
1050
+ """
1051
+
1052
+ try:
1053
+ if not isinstance(profile, ImageCmsProfile):
1054
+ profile = ImageCmsProfile(profile)
1055
+ return profile.profile.rendering_intent
1056
+ except (AttributeError, OSError, TypeError, ValueError) as v:
1057
+ raise PyCMSError(v) from v
1058
+
1059
+
1060
+ def isIntentSupported(
1061
+ profile: _CmsProfileCompatible, intent: Intent, direction: Direction
1062
+ ) -> Literal[-1, 1]:
1063
+ """
1064
+ (pyCMS) Checks if a given intent is supported.
1065
+
1066
+ Use this function to verify that you can use your desired
1067
+ ``intent`` with ``profile``, and that ``profile`` can be used for the
1068
+ input/output/proof profile as you desire.
1069
+
1070
+ Some profiles are created specifically for one "direction", can cannot
1071
+ be used for others. Some profiles can only be used for certain
1072
+ rendering intents, so it's best to either verify this before trying
1073
+ to create a transform with them (using this function), or catch the
1074
+ potential :exc:`PyCMSError` that will occur if they don't
1075
+ support the modes you select.
1076
+
1077
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
1078
+ filename of an ICC profile.
1079
+ :param intent: Integer (0-3) specifying the rendering intent you wish to
1080
+ use with this profile
1081
+
1082
+ ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
1083
+ ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
1084
+ ImageCms.Intent.SATURATION = 2
1085
+ ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
1086
+
1087
+ see the pyCMS documentation for details on rendering intents and what
1088
+ they do.
1089
+ :param direction: Integer specifying if the profile is to be used for
1090
+ input, output, or proof
1091
+
1092
+ INPUT = 0 (or use ImageCms.Direction.INPUT)
1093
+ OUTPUT = 1 (or use ImageCms.Direction.OUTPUT)
1094
+ PROOF = 2 (or use ImageCms.Direction.PROOF)
1095
+
1096
+ :returns: 1 if the intent/direction are supported, -1 if they are not.
1097
+ :exception PyCMSError:
1098
+ """
1099
+
1100
+ try:
1101
+ if not isinstance(profile, ImageCmsProfile):
1102
+ profile = ImageCmsProfile(profile)
1103
+ # FIXME: I get different results for the same data w. different
1104
+ # compilers. Bug in LittleCMS or in the binding?
1105
+ if profile.profile.is_intent_supported(intent, direction):
1106
+ return 1
1107
+ else:
1108
+ return -1
1109
+ except (AttributeError, OSError, TypeError, ValueError) as v:
1110
+ raise PyCMSError(v) from v
1111
+
1112
+
1113
+ def versions() -> tuple[str, str | None, str, str]:
1114
+ """
1115
+ (pyCMS) Fetches versions.
1116
+ """
1117
+
1118
+ deprecate(
1119
+ "PIL.ImageCms.versions()",
1120
+ 12,
1121
+ '(PIL.features.version("littlecms2"), sys.version, PIL.__version__)',
1122
+ )
1123
+ return _VERSION, core.littlecms_version, sys.version.split()[0], __version__
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/ImageColor.py ADDED
@@ -0,0 +1,320 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library
3
+ # $Id$
4
+ #
5
+ # map CSS3-style colour description strings to RGB
6
+ #
7
+ # History:
8
+ # 2002-10-24 fl Added support for CSS-style color strings
9
+ # 2002-12-15 fl Added RGBA support
10
+ # 2004-03-27 fl Fixed remaining int() problems for Python 1.5.2
11
+ # 2004-07-19 fl Fixed gray/grey spelling issues
12
+ # 2009-03-05 fl Fixed rounding error in grayscale calculation
13
+ #
14
+ # Copyright (c) 2002-2004 by Secret Labs AB
15
+ # Copyright (c) 2002-2004 by Fredrik Lundh
16
+ #
17
+ # See the README file for information on usage and redistribution.
18
+ #
19
+ from __future__ import annotations
20
+
21
+ import re
22
+ from functools import lru_cache
23
+
24
+ from . import Image
25
+
26
+
27
+ @lru_cache
28
+ def getrgb(color: str) -> tuple[int, int, int] | tuple[int, int, int, int]:
29
+ """
30
+ Convert a color string to an RGB or RGBA tuple. If the string cannot be
31
+ parsed, this function raises a :py:exc:`ValueError` exception.
32
+
33
+ .. versionadded:: 1.1.4
34
+
35
+ :param color: A color string
36
+ :return: ``(red, green, blue[, alpha])``
37
+ """
38
+ if len(color) > 100:
39
+ msg = "color specifier is too long"
40
+ raise ValueError(msg)
41
+ color = color.lower()
42
+
43
+ rgb = colormap.get(color, None)
44
+ if rgb:
45
+ if isinstance(rgb, tuple):
46
+ return rgb
47
+ rgb_tuple = getrgb(rgb)
48
+ assert len(rgb_tuple) == 3
49
+ colormap[color] = rgb_tuple
50
+ return rgb_tuple
51
+
52
+ # check for known string formats
53
+ if re.match("#[a-f0-9]{3}$", color):
54
+ return int(color[1] * 2, 16), int(color[2] * 2, 16), int(color[3] * 2, 16)
55
+
56
+ if re.match("#[a-f0-9]{4}$", color):
57
+ return (
58
+ int(color[1] * 2, 16),
59
+ int(color[2] * 2, 16),
60
+ int(color[3] * 2, 16),
61
+ int(color[4] * 2, 16),
62
+ )
63
+
64
+ if re.match("#[a-f0-9]{6}$", color):
65
+ return int(color[1:3], 16), int(color[3:5], 16), int(color[5:7], 16)
66
+
67
+ if re.match("#[a-f0-9]{8}$", color):
68
+ return (
69
+ int(color[1:3], 16),
70
+ int(color[3:5], 16),
71
+ int(color[5:7], 16),
72
+ int(color[7:9], 16),
73
+ )
74
+
75
+ m = re.match(r"rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$", color)
76
+ if m:
77
+ return int(m.group(1)), int(m.group(2)), int(m.group(3))
78
+
79
+ m = re.match(r"rgb\(\s*(\d+)%\s*,\s*(\d+)%\s*,\s*(\d+)%\s*\)$", color)
80
+ if m:
81
+ return (
82
+ int((int(m.group(1)) * 255) / 100.0 + 0.5),
83
+ int((int(m.group(2)) * 255) / 100.0 + 0.5),
84
+ int((int(m.group(3)) * 255) / 100.0 + 0.5),
85
+ )
86
+
87
+ m = re.match(
88
+ r"hsl\(\s*(\d+\.?\d*)\s*,\s*(\d+\.?\d*)%\s*,\s*(\d+\.?\d*)%\s*\)$", color
89
+ )
90
+ if m:
91
+ from colorsys import hls_to_rgb
92
+
93
+ rgb_floats = hls_to_rgb(
94
+ float(m.group(1)) / 360.0,
95
+ float(m.group(3)) / 100.0,
96
+ float(m.group(2)) / 100.0,
97
+ )
98
+ return (
99
+ int(rgb_floats[0] * 255 + 0.5),
100
+ int(rgb_floats[1] * 255 + 0.5),
101
+ int(rgb_floats[2] * 255 + 0.5),
102
+ )
103
+
104
+ m = re.match(
105
+ r"hs[bv]\(\s*(\d+\.?\d*)\s*,\s*(\d+\.?\d*)%\s*,\s*(\d+\.?\d*)%\s*\)$", color
106
+ )
107
+ if m:
108
+ from colorsys import hsv_to_rgb
109
+
110
+ rgb_floats = hsv_to_rgb(
111
+ float(m.group(1)) / 360.0,
112
+ float(m.group(2)) / 100.0,
113
+ float(m.group(3)) / 100.0,
114
+ )
115
+ return (
116
+ int(rgb_floats[0] * 255 + 0.5),
117
+ int(rgb_floats[1] * 255 + 0.5),
118
+ int(rgb_floats[2] * 255 + 0.5),
119
+ )
120
+
121
+ m = re.match(r"rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$", color)
122
+ if m:
123
+ return int(m.group(1)), int(m.group(2)), int(m.group(3)), int(m.group(4))
124
+ msg = f"unknown color specifier: {repr(color)}"
125
+ raise ValueError(msg)
126
+
127
+
128
+ @lru_cache
129
+ def getcolor(color: str, mode: str) -> int | tuple[int, ...]:
130
+ """
131
+ Same as :py:func:`~PIL.ImageColor.getrgb` for most modes. However, if
132
+ ``mode`` is HSV, converts the RGB value to a HSV value, or if ``mode`` is
133
+ not color or a palette image, converts the RGB value to a grayscale value.
134
+ If the string cannot be parsed, this function raises a :py:exc:`ValueError`
135
+ exception.
136
+
137
+ .. versionadded:: 1.1.4
138
+
139
+ :param color: A color string
140
+ :param mode: Convert result to this mode
141
+ :return: ``graylevel, (graylevel, alpha) or (red, green, blue[, alpha])``
142
+ """
143
+ # same as getrgb, but converts the result to the given mode
144
+ rgb, alpha = getrgb(color), 255
145
+ if len(rgb) == 4:
146
+ alpha = rgb[3]
147
+ rgb = rgb[:3]
148
+
149
+ if mode == "HSV":
150
+ from colorsys import rgb_to_hsv
151
+
152
+ r, g, b = rgb
153
+ h, s, v = rgb_to_hsv(r / 255, g / 255, b / 255)
154
+ return int(h * 255), int(s * 255), int(v * 255)
155
+ elif Image.getmodebase(mode) == "L":
156
+ r, g, b = rgb
157
+ # ITU-R Recommendation 601-2 for nonlinear RGB
158
+ # scaled to 24 bits to match the convert's implementation.
159
+ graylevel = (r * 19595 + g * 38470 + b * 7471 + 0x8000) >> 16
160
+ if mode[-1] == "A":
161
+ return graylevel, alpha
162
+ return graylevel
163
+ elif mode[-1] == "A":
164
+ return rgb + (alpha,)
165
+ return rgb
166
+
167
+
168
+ colormap: dict[str, str | tuple[int, int, int]] = {
169
+ # X11 colour table from https://drafts.csswg.org/css-color-4/, with
170
+ # gray/grey spelling issues fixed. This is a superset of HTML 4.0
171
+ # colour names used in CSS 1.
172
+ "aliceblue": "#f0f8ff",
173
+ "antiquewhite": "#faebd7",
174
+ "aqua": "#00ffff",
175
+ "aquamarine": "#7fffd4",
176
+ "azure": "#f0ffff",
177
+ "beige": "#f5f5dc",
178
+ "bisque": "#ffe4c4",
179
+ "black": "#000000",
180
+ "blanchedalmond": "#ffebcd",
181
+ "blue": "#0000ff",
182
+ "blueviolet": "#8a2be2",
183
+ "brown": "#a52a2a",
184
+ "burlywood": "#deb887",
185
+ "cadetblue": "#5f9ea0",
186
+ "chartreuse": "#7fff00",
187
+ "chocolate": "#d2691e",
188
+ "coral": "#ff7f50",
189
+ "cornflowerblue": "#6495ed",
190
+ "cornsilk": "#fff8dc",
191
+ "crimson": "#dc143c",
192
+ "cyan": "#00ffff",
193
+ "darkblue": "#00008b",
194
+ "darkcyan": "#008b8b",
195
+ "darkgoldenrod": "#b8860b",
196
+ "darkgray": "#a9a9a9",
197
+ "darkgrey": "#a9a9a9",
198
+ "darkgreen": "#006400",
199
+ "darkkhaki": "#bdb76b",
200
+ "darkmagenta": "#8b008b",
201
+ "darkolivegreen": "#556b2f",
202
+ "darkorange": "#ff8c00",
203
+ "darkorchid": "#9932cc",
204
+ "darkred": "#8b0000",
205
+ "darksalmon": "#e9967a",
206
+ "darkseagreen": "#8fbc8f",
207
+ "darkslateblue": "#483d8b",
208
+ "darkslategray": "#2f4f4f",
209
+ "darkslategrey": "#2f4f4f",
210
+ "darkturquoise": "#00ced1",
211
+ "darkviolet": "#9400d3",
212
+ "deeppink": "#ff1493",
213
+ "deepskyblue": "#00bfff",
214
+ "dimgray": "#696969",
215
+ "dimgrey": "#696969",
216
+ "dodgerblue": "#1e90ff",
217
+ "firebrick": "#b22222",
218
+ "floralwhite": "#fffaf0",
219
+ "forestgreen": "#228b22",
220
+ "fuchsia": "#ff00ff",
221
+ "gainsboro": "#dcdcdc",
222
+ "ghostwhite": "#f8f8ff",
223
+ "gold": "#ffd700",
224
+ "goldenrod": "#daa520",
225
+ "gray": "#808080",
226
+ "grey": "#808080",
227
+ "green": "#008000",
228
+ "greenyellow": "#adff2f",
229
+ "honeydew": "#f0fff0",
230
+ "hotpink": "#ff69b4",
231
+ "indianred": "#cd5c5c",
232
+ "indigo": "#4b0082",
233
+ "ivory": "#fffff0",
234
+ "khaki": "#f0e68c",
235
+ "lavender": "#e6e6fa",
236
+ "lavenderblush": "#fff0f5",
237
+ "lawngreen": "#7cfc00",
238
+ "lemonchiffon": "#fffacd",
239
+ "lightblue": "#add8e6",
240
+ "lightcoral": "#f08080",
241
+ "lightcyan": "#e0ffff",
242
+ "lightgoldenrodyellow": "#fafad2",
243
+ "lightgreen": "#90ee90",
244
+ "lightgray": "#d3d3d3",
245
+ "lightgrey": "#d3d3d3",
246
+ "lightpink": "#ffb6c1",
247
+ "lightsalmon": "#ffa07a",
248
+ "lightseagreen": "#20b2aa",
249
+ "lightskyblue": "#87cefa",
250
+ "lightslategray": "#778899",
251
+ "lightslategrey": "#778899",
252
+ "lightsteelblue": "#b0c4de",
253
+ "lightyellow": "#ffffe0",
254
+ "lime": "#00ff00",
255
+ "limegreen": "#32cd32",
256
+ "linen": "#faf0e6",
257
+ "magenta": "#ff00ff",
258
+ "maroon": "#800000",
259
+ "mediumaquamarine": "#66cdaa",
260
+ "mediumblue": "#0000cd",
261
+ "mediumorchid": "#ba55d3",
262
+ "mediumpurple": "#9370db",
263
+ "mediumseagreen": "#3cb371",
264
+ "mediumslateblue": "#7b68ee",
265
+ "mediumspringgreen": "#00fa9a",
266
+ "mediumturquoise": "#48d1cc",
267
+ "mediumvioletred": "#c71585",
268
+ "midnightblue": "#191970",
269
+ "mintcream": "#f5fffa",
270
+ "mistyrose": "#ffe4e1",
271
+ "moccasin": "#ffe4b5",
272
+ "navajowhite": "#ffdead",
273
+ "navy": "#000080",
274
+ "oldlace": "#fdf5e6",
275
+ "olive": "#808000",
276
+ "olivedrab": "#6b8e23",
277
+ "orange": "#ffa500",
278
+ "orangered": "#ff4500",
279
+ "orchid": "#da70d6",
280
+ "palegoldenrod": "#eee8aa",
281
+ "palegreen": "#98fb98",
282
+ "paleturquoise": "#afeeee",
283
+ "palevioletred": "#db7093",
284
+ "papayawhip": "#ffefd5",
285
+ "peachpuff": "#ffdab9",
286
+ "peru": "#cd853f",
287
+ "pink": "#ffc0cb",
288
+ "plum": "#dda0dd",
289
+ "powderblue": "#b0e0e6",
290
+ "purple": "#800080",
291
+ "rebeccapurple": "#663399",
292
+ "red": "#ff0000",
293
+ "rosybrown": "#bc8f8f",
294
+ "royalblue": "#4169e1",
295
+ "saddlebrown": "#8b4513",
296
+ "salmon": "#fa8072",
297
+ "sandybrown": "#f4a460",
298
+ "seagreen": "#2e8b57",
299
+ "seashell": "#fff5ee",
300
+ "sienna": "#a0522d",
301
+ "silver": "#c0c0c0",
302
+ "skyblue": "#87ceeb",
303
+ "slateblue": "#6a5acd",
304
+ "slategray": "#708090",
305
+ "slategrey": "#708090",
306
+ "snow": "#fffafa",
307
+ "springgreen": "#00ff7f",
308
+ "steelblue": "#4682b4",
309
+ "tan": "#d2b48c",
310
+ "teal": "#008080",
311
+ "thistle": "#d8bfd8",
312
+ "tomato": "#ff6347",
313
+ "turquoise": "#40e0d0",
314
+ "violet": "#ee82ee",
315
+ "wheat": "#f5deb3",
316
+ "white": "#ffffff",
317
+ "whitesmoke": "#f5f5f5",
318
+ "yellow": "#ffff00",
319
+ "yellowgreen": "#9acd32",
320
+ }
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/ImageDraw.py ADDED
@@ -0,0 +1,1232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library
3
+ # $Id$
4
+ #
5
+ # drawing interface operations
6
+ #
7
+ # History:
8
+ # 1996-04-13 fl Created (experimental)
9
+ # 1996-08-07 fl Filled polygons, ellipses.
10
+ # 1996-08-13 fl Added text support
11
+ # 1998-06-28 fl Handle I and F images
12
+ # 1998-12-29 fl Added arc; use arc primitive to draw ellipses
13
+ # 1999-01-10 fl Added shape stuff (experimental)
14
+ # 1999-02-06 fl Added bitmap support
15
+ # 1999-02-11 fl Changed all primitives to take options
16
+ # 1999-02-20 fl Fixed backwards compatibility
17
+ # 2000-10-12 fl Copy on write, when necessary
18
+ # 2001-02-18 fl Use default ink for bitmap/text also in fill mode
19
+ # 2002-10-24 fl Added support for CSS-style color strings
20
+ # 2002-12-10 fl Added experimental support for RGBA-on-RGB drawing
21
+ # 2002-12-11 fl Refactored low-level drawing API (work in progress)
22
+ # 2004-08-26 fl Made Draw() a factory function, added getdraw() support
23
+ # 2004-09-04 fl Added width support to line primitive
24
+ # 2004-09-10 fl Added font mode handling
25
+ # 2006-06-19 fl Added font bearing support (getmask2)
26
+ #
27
+ # Copyright (c) 1997-2006 by Secret Labs AB
28
+ # Copyright (c) 1996-2006 by Fredrik Lundh
29
+ #
30
+ # See the README file for information on usage and redistribution.
31
+ #
32
+ from __future__ import annotations
33
+
34
+ import math
35
+ import struct
36
+ from collections.abc import Sequence
37
+ from types import ModuleType
38
+ from typing import Any, AnyStr, Callable, Union, cast
39
+
40
+ from . import Image, ImageColor
41
+ from ._deprecate import deprecate
42
+ from ._typing import Coords
43
+
44
+ # experimental access to the outline API
45
+ Outline: Callable[[], Image.core._Outline] = Image.core.outline
46
+
47
+ TYPE_CHECKING = False
48
+ if TYPE_CHECKING:
49
+ from . import ImageDraw2, ImageFont
50
+
51
+ _Ink = Union[float, tuple[int, ...], str]
52
+
53
+ """
54
+ A simple 2D drawing interface for PIL images.
55
+ <p>
56
+ Application code should use the <b>Draw</b> factory, instead of
57
+ directly.
58
+ """
59
+
60
+
61
+ class ImageDraw:
62
+ font: (
63
+ ImageFont.ImageFont | ImageFont.FreeTypeFont | ImageFont.TransposedFont | None
64
+ ) = None
65
+
66
+ def __init__(self, im: Image.Image, mode: str | None = None) -> None:
67
+ """
68
+ Create a drawing instance.
69
+
70
+ :param im: The image to draw in.
71
+ :param mode: Optional mode to use for color values. For RGB
72
+ images, this argument can be RGB or RGBA (to blend the
73
+ drawing into the image). For all other modes, this argument
74
+ must be the same as the image mode. If omitted, the mode
75
+ defaults to the mode of the image.
76
+ """
77
+ im.load()
78
+ if im.readonly:
79
+ im._copy() # make it writeable
80
+ blend = 0
81
+ if mode is None:
82
+ mode = im.mode
83
+ if mode != im.mode:
84
+ if mode == "RGBA" and im.mode == "RGB":
85
+ blend = 1
86
+ else:
87
+ msg = "mode mismatch"
88
+ raise ValueError(msg)
89
+ if mode == "P":
90
+ self.palette = im.palette
91
+ else:
92
+ self.palette = None
93
+ self._image = im
94
+ self.im = im.im
95
+ self.draw = Image.core.draw(self.im, blend)
96
+ self.mode = mode
97
+ if mode in ("I", "F"):
98
+ self.ink = self.draw.draw_ink(1)
99
+ else:
100
+ self.ink = self.draw.draw_ink(-1)
101
+ if mode in ("1", "P", "I", "F"):
102
+ # FIXME: fix Fill2 to properly support matte for I+F images
103
+ self.fontmode = "1"
104
+ else:
105
+ self.fontmode = "L" # aliasing is okay for other modes
106
+ self.fill = False
107
+
108
+ def getfont(
109
+ self,
110
+ ) -> ImageFont.ImageFont | ImageFont.FreeTypeFont | ImageFont.TransposedFont:
111
+ """
112
+ Get the current default font.
113
+
114
+ To set the default font for this ImageDraw instance::
115
+
116
+ from PIL import ImageDraw, ImageFont
117
+ draw.font = ImageFont.truetype("Tests/fonts/FreeMono.ttf")
118
+
119
+ To set the default font for all future ImageDraw instances::
120
+
121
+ from PIL import ImageDraw, ImageFont
122
+ ImageDraw.ImageDraw.font = ImageFont.truetype("Tests/fonts/FreeMono.ttf")
123
+
124
+ If the current default font is ``None``,
125
+ it is initialized with ``ImageFont.load_default()``.
126
+
127
+ :returns: An image font."""
128
+ if not self.font:
129
+ # FIXME: should add a font repository
130
+ from . import ImageFont
131
+
132
+ self.font = ImageFont.load_default()
133
+ return self.font
134
+
135
+ def _getfont(
136
+ self, font_size: float | None
137
+ ) -> ImageFont.ImageFont | ImageFont.FreeTypeFont | ImageFont.TransposedFont:
138
+ if font_size is not None:
139
+ from . import ImageFont
140
+
141
+ return ImageFont.load_default(font_size)
142
+ else:
143
+ return self.getfont()
144
+
145
+ def _getink(
146
+ self, ink: _Ink | None, fill: _Ink | None = None
147
+ ) -> tuple[int | None, int | None]:
148
+ result_ink = None
149
+ result_fill = None
150
+ if ink is None and fill is None:
151
+ if self.fill:
152
+ result_fill = self.ink
153
+ else:
154
+ result_ink = self.ink
155
+ else:
156
+ if ink is not None:
157
+ if isinstance(ink, str):
158
+ ink = ImageColor.getcolor(ink, self.mode)
159
+ if self.palette and isinstance(ink, tuple):
160
+ ink = self.palette.getcolor(ink, self._image)
161
+ result_ink = self.draw.draw_ink(ink)
162
+ if fill is not None:
163
+ if isinstance(fill, str):
164
+ fill = ImageColor.getcolor(fill, self.mode)
165
+ if self.palette and isinstance(fill, tuple):
166
+ fill = self.palette.getcolor(fill, self._image)
167
+ result_fill = self.draw.draw_ink(fill)
168
+ return result_ink, result_fill
169
+
170
+ def arc(
171
+ self,
172
+ xy: Coords,
173
+ start: float,
174
+ end: float,
175
+ fill: _Ink | None = None,
176
+ width: int = 1,
177
+ ) -> None:
178
+ """Draw an arc."""
179
+ ink, fill = self._getink(fill)
180
+ if ink is not None:
181
+ self.draw.draw_arc(xy, start, end, ink, width)
182
+
183
+ def bitmap(
184
+ self, xy: Sequence[int], bitmap: Image.Image, fill: _Ink | None = None
185
+ ) -> None:
186
+ """Draw a bitmap."""
187
+ bitmap.load()
188
+ ink, fill = self._getink(fill)
189
+ if ink is None:
190
+ ink = fill
191
+ if ink is not None:
192
+ self.draw.draw_bitmap(xy, bitmap.im, ink)
193
+
194
+ def chord(
195
+ self,
196
+ xy: Coords,
197
+ start: float,
198
+ end: float,
199
+ fill: _Ink | None = None,
200
+ outline: _Ink | None = None,
201
+ width: int = 1,
202
+ ) -> None:
203
+ """Draw a chord."""
204
+ ink, fill_ink = self._getink(outline, fill)
205
+ if fill_ink is not None:
206
+ self.draw.draw_chord(xy, start, end, fill_ink, 1)
207
+ if ink is not None and ink != fill_ink and width != 0:
208
+ self.draw.draw_chord(xy, start, end, ink, 0, width)
209
+
210
+ def ellipse(
211
+ self,
212
+ xy: Coords,
213
+ fill: _Ink | None = None,
214
+ outline: _Ink | None = None,
215
+ width: int = 1,
216
+ ) -> None:
217
+ """Draw an ellipse."""
218
+ ink, fill_ink = self._getink(outline, fill)
219
+ if fill_ink is not None:
220
+ self.draw.draw_ellipse(xy, fill_ink, 1)
221
+ if ink is not None and ink != fill_ink and width != 0:
222
+ self.draw.draw_ellipse(xy, ink, 0, width)
223
+
224
+ def circle(
225
+ self,
226
+ xy: Sequence[float],
227
+ radius: float,
228
+ fill: _Ink | None = None,
229
+ outline: _Ink | None = None,
230
+ width: int = 1,
231
+ ) -> None:
232
+ """Draw a circle given center coordinates and a radius."""
233
+ ellipse_xy = (xy[0] - radius, xy[1] - radius, xy[0] + radius, xy[1] + radius)
234
+ self.ellipse(ellipse_xy, fill, outline, width)
235
+
236
+ def line(
237
+ self,
238
+ xy: Coords,
239
+ fill: _Ink | None = None,
240
+ width: int = 0,
241
+ joint: str | None = None,
242
+ ) -> None:
243
+ """Draw a line, or a connected sequence of line segments."""
244
+ ink = self._getink(fill)[0]
245
+ if ink is not None:
246
+ self.draw.draw_lines(xy, ink, width)
247
+ if joint == "curve" and width > 4:
248
+ points: Sequence[Sequence[float]]
249
+ if isinstance(xy[0], (list, tuple)):
250
+ points = cast(Sequence[Sequence[float]], xy)
251
+ else:
252
+ points = [
253
+ cast(Sequence[float], tuple(xy[i : i + 2]))
254
+ for i in range(0, len(xy), 2)
255
+ ]
256
+ for i in range(1, len(points) - 1):
257
+ point = points[i]
258
+ angles = [
259
+ math.degrees(math.atan2(end[0] - start[0], start[1] - end[1]))
260
+ % 360
261
+ for start, end in (
262
+ (points[i - 1], point),
263
+ (point, points[i + 1]),
264
+ )
265
+ ]
266
+ if angles[0] == angles[1]:
267
+ # This is a straight line, so no joint is required
268
+ continue
269
+
270
+ def coord_at_angle(
271
+ coord: Sequence[float], angle: float
272
+ ) -> tuple[float, ...]:
273
+ x, y = coord
274
+ angle -= 90
275
+ distance = width / 2 - 1
276
+ return tuple(
277
+ p + (math.floor(p_d) if p_d > 0 else math.ceil(p_d))
278
+ for p, p_d in (
279
+ (x, distance * math.cos(math.radians(angle))),
280
+ (y, distance * math.sin(math.radians(angle))),
281
+ )
282
+ )
283
+
284
+ flipped = (
285
+ angles[1] > angles[0] and angles[1] - 180 > angles[0]
286
+ ) or (angles[1] < angles[0] and angles[1] + 180 > angles[0])
287
+ coords = [
288
+ (point[0] - width / 2 + 1, point[1] - width / 2 + 1),
289
+ (point[0] + width / 2 - 1, point[1] + width / 2 - 1),
290
+ ]
291
+ if flipped:
292
+ start, end = (angles[1] + 90, angles[0] + 90)
293
+ else:
294
+ start, end = (angles[0] - 90, angles[1] - 90)
295
+ self.pieslice(coords, start - 90, end - 90, fill)
296
+
297
+ if width > 8:
298
+ # Cover potential gaps between the line and the joint
299
+ if flipped:
300
+ gap_coords = [
301
+ coord_at_angle(point, angles[0] + 90),
302
+ point,
303
+ coord_at_angle(point, angles[1] + 90),
304
+ ]
305
+ else:
306
+ gap_coords = [
307
+ coord_at_angle(point, angles[0] - 90),
308
+ point,
309
+ coord_at_angle(point, angles[1] - 90),
310
+ ]
311
+ self.line(gap_coords, fill, width=3)
312
+
313
+ def shape(
314
+ self,
315
+ shape: Image.core._Outline,
316
+ fill: _Ink | None = None,
317
+ outline: _Ink | None = None,
318
+ ) -> None:
319
+ """(Experimental) Draw a shape."""
320
+ shape.close()
321
+ ink, fill_ink = self._getink(outline, fill)
322
+ if fill_ink is not None:
323
+ self.draw.draw_outline(shape, fill_ink, 1)
324
+ if ink is not None and ink != fill_ink:
325
+ self.draw.draw_outline(shape, ink, 0)
326
+
327
+ def pieslice(
328
+ self,
329
+ xy: Coords,
330
+ start: float,
331
+ end: float,
332
+ fill: _Ink | None = None,
333
+ outline: _Ink | None = None,
334
+ width: int = 1,
335
+ ) -> None:
336
+ """Draw a pieslice."""
337
+ ink, fill_ink = self._getink(outline, fill)
338
+ if fill_ink is not None:
339
+ self.draw.draw_pieslice(xy, start, end, fill_ink, 1)
340
+ if ink is not None and ink != fill_ink and width != 0:
341
+ self.draw.draw_pieslice(xy, start, end, ink, 0, width)
342
+
343
+ def point(self, xy: Coords, fill: _Ink | None = None) -> None:
344
+ """Draw one or more individual pixels."""
345
+ ink, fill = self._getink(fill)
346
+ if ink is not None:
347
+ self.draw.draw_points(xy, ink)
348
+
349
+ def polygon(
350
+ self,
351
+ xy: Coords,
352
+ fill: _Ink | None = None,
353
+ outline: _Ink | None = None,
354
+ width: int = 1,
355
+ ) -> None:
356
+ """Draw a polygon."""
357
+ ink, fill_ink = self._getink(outline, fill)
358
+ if fill_ink is not None:
359
+ self.draw.draw_polygon(xy, fill_ink, 1)
360
+ if ink is not None and ink != fill_ink and width != 0:
361
+ if width == 1:
362
+ self.draw.draw_polygon(xy, ink, 0, width)
363
+ elif self.im is not None:
364
+ # To avoid expanding the polygon outwards,
365
+ # use the fill as a mask
366
+ mask = Image.new("1", self.im.size)
367
+ mask_ink = self._getink(1)[0]
368
+ draw = Draw(mask)
369
+ draw.draw.draw_polygon(xy, mask_ink, 1)
370
+
371
+ self.draw.draw_polygon(xy, ink, 0, width * 2 - 1, mask.im)
372
+
373
+ def regular_polygon(
374
+ self,
375
+ bounding_circle: Sequence[Sequence[float] | float],
376
+ n_sides: int,
377
+ rotation: float = 0,
378
+ fill: _Ink | None = None,
379
+ outline: _Ink | None = None,
380
+ width: int = 1,
381
+ ) -> None:
382
+ """Draw a regular polygon."""
383
+ xy = _compute_regular_polygon_vertices(bounding_circle, n_sides, rotation)
384
+ self.polygon(xy, fill, outline, width)
385
+
386
+ def rectangle(
387
+ self,
388
+ xy: Coords,
389
+ fill: _Ink | None = None,
390
+ outline: _Ink | None = None,
391
+ width: int = 1,
392
+ ) -> None:
393
+ """Draw a rectangle."""
394
+ ink, fill_ink = self._getink(outline, fill)
395
+ if fill_ink is not None:
396
+ self.draw.draw_rectangle(xy, fill_ink, 1)
397
+ if ink is not None and ink != fill_ink and width != 0:
398
+ self.draw.draw_rectangle(xy, ink, 0, width)
399
+
400
+ def rounded_rectangle(
401
+ self,
402
+ xy: Coords,
403
+ radius: float = 0,
404
+ fill: _Ink | None = None,
405
+ outline: _Ink | None = None,
406
+ width: int = 1,
407
+ *,
408
+ corners: tuple[bool, bool, bool, bool] | None = None,
409
+ ) -> None:
410
+ """Draw a rounded rectangle."""
411
+ if isinstance(xy[0], (list, tuple)):
412
+ (x0, y0), (x1, y1) = cast(Sequence[Sequence[float]], xy)
413
+ else:
414
+ x0, y0, x1, y1 = cast(Sequence[float], xy)
415
+ if x1 < x0:
416
+ msg = "x1 must be greater than or equal to x0"
417
+ raise ValueError(msg)
418
+ if y1 < y0:
419
+ msg = "y1 must be greater than or equal to y0"
420
+ raise ValueError(msg)
421
+ if corners is None:
422
+ corners = (True, True, True, True)
423
+
424
+ d = radius * 2
425
+
426
+ x0 = round(x0)
427
+ y0 = round(y0)
428
+ x1 = round(x1)
429
+ y1 = round(y1)
430
+ full_x, full_y = False, False
431
+ if all(corners):
432
+ full_x = d >= x1 - x0 - 1
433
+ if full_x:
434
+ # The two left and two right corners are joined
435
+ d = x1 - x0
436
+ full_y = d >= y1 - y0 - 1
437
+ if full_y:
438
+ # The two top and two bottom corners are joined
439
+ d = y1 - y0
440
+ if full_x and full_y:
441
+ # If all corners are joined, that is a circle
442
+ return self.ellipse(xy, fill, outline, width)
443
+
444
+ if d == 0 or not any(corners):
445
+ # If the corners have no curve,
446
+ # or there are no corners,
447
+ # that is a rectangle
448
+ return self.rectangle(xy, fill, outline, width)
449
+
450
+ r = int(d // 2)
451
+ ink, fill_ink = self._getink(outline, fill)
452
+
453
+ def draw_corners(pieslice: bool) -> None:
454
+ parts: tuple[tuple[tuple[float, float, float, float], int, int], ...]
455
+ if full_x:
456
+ # Draw top and bottom halves
457
+ parts = (
458
+ ((x0, y0, x0 + d, y0 + d), 180, 360),
459
+ ((x0, y1 - d, x0 + d, y1), 0, 180),
460
+ )
461
+ elif full_y:
462
+ # Draw left and right halves
463
+ parts = (
464
+ ((x0, y0, x0 + d, y0 + d), 90, 270),
465
+ ((x1 - d, y0, x1, y0 + d), 270, 90),
466
+ )
467
+ else:
468
+ # Draw four separate corners
469
+ parts = tuple(
470
+ part
471
+ for i, part in enumerate(
472
+ (
473
+ ((x0, y0, x0 + d, y0 + d), 180, 270),
474
+ ((x1 - d, y0, x1, y0 + d), 270, 360),
475
+ ((x1 - d, y1 - d, x1, y1), 0, 90),
476
+ ((x0, y1 - d, x0 + d, y1), 90, 180),
477
+ )
478
+ )
479
+ if corners[i]
480
+ )
481
+ for part in parts:
482
+ if pieslice:
483
+ self.draw.draw_pieslice(*(part + (fill_ink, 1)))
484
+ else:
485
+ self.draw.draw_arc(*(part + (ink, width)))
486
+
487
+ if fill_ink is not None:
488
+ draw_corners(True)
489
+
490
+ if full_x:
491
+ self.draw.draw_rectangle((x0, y0 + r + 1, x1, y1 - r - 1), fill_ink, 1)
492
+ elif x1 - r - 1 > x0 + r + 1:
493
+ self.draw.draw_rectangle((x0 + r + 1, y0, x1 - r - 1, y1), fill_ink, 1)
494
+ if not full_x and not full_y:
495
+ left = [x0, y0, x0 + r, y1]
496
+ if corners[0]:
497
+ left[1] += r + 1
498
+ if corners[3]:
499
+ left[3] -= r + 1
500
+ self.draw.draw_rectangle(left, fill_ink, 1)
501
+
502
+ right = [x1 - r, y0, x1, y1]
503
+ if corners[1]:
504
+ right[1] += r + 1
505
+ if corners[2]:
506
+ right[3] -= r + 1
507
+ self.draw.draw_rectangle(right, fill_ink, 1)
508
+ if ink is not None and ink != fill_ink and width != 0:
509
+ draw_corners(False)
510
+
511
+ if not full_x:
512
+ top = [x0, y0, x1, y0 + width - 1]
513
+ if corners[0]:
514
+ top[0] += r + 1
515
+ if corners[1]:
516
+ top[2] -= r + 1
517
+ self.draw.draw_rectangle(top, ink, 1)
518
+
519
+ bottom = [x0, y1 - width + 1, x1, y1]
520
+ if corners[3]:
521
+ bottom[0] += r + 1
522
+ if corners[2]:
523
+ bottom[2] -= r + 1
524
+ self.draw.draw_rectangle(bottom, ink, 1)
525
+ if not full_y:
526
+ left = [x0, y0, x0 + width - 1, y1]
527
+ if corners[0]:
528
+ left[1] += r + 1
529
+ if corners[3]:
530
+ left[3] -= r + 1
531
+ self.draw.draw_rectangle(left, ink, 1)
532
+
533
+ right = [x1 - width + 1, y0, x1, y1]
534
+ if corners[1]:
535
+ right[1] += r + 1
536
+ if corners[2]:
537
+ right[3] -= r + 1
538
+ self.draw.draw_rectangle(right, ink, 1)
539
+
540
+ def _multiline_check(self, text: AnyStr) -> bool:
541
+ split_character = "\n" if isinstance(text, str) else b"\n"
542
+
543
+ return split_character in text
544
+
545
+ def text(
546
+ self,
547
+ xy: tuple[float, float],
548
+ text: AnyStr,
549
+ fill: _Ink | None = None,
550
+ font: (
551
+ ImageFont.ImageFont
552
+ | ImageFont.FreeTypeFont
553
+ | ImageFont.TransposedFont
554
+ | None
555
+ ) = None,
556
+ anchor: str | None = None,
557
+ spacing: float = 4,
558
+ align: str = "left",
559
+ direction: str | None = None,
560
+ features: list[str] | None = None,
561
+ language: str | None = None,
562
+ stroke_width: float = 0,
563
+ stroke_fill: _Ink | None = None,
564
+ embedded_color: bool = False,
565
+ *args: Any,
566
+ **kwargs: Any,
567
+ ) -> None:
568
+ """Draw text."""
569
+ if embedded_color and self.mode not in ("RGB", "RGBA"):
570
+ msg = "Embedded color supported only in RGB and RGBA modes"
571
+ raise ValueError(msg)
572
+
573
+ if font is None:
574
+ font = self._getfont(kwargs.get("font_size"))
575
+
576
+ if self._multiline_check(text):
577
+ return self.multiline_text(
578
+ xy,
579
+ text,
580
+ fill,
581
+ font,
582
+ anchor,
583
+ spacing,
584
+ align,
585
+ direction,
586
+ features,
587
+ language,
588
+ stroke_width,
589
+ stroke_fill,
590
+ embedded_color,
591
+ )
592
+
593
+ def getink(fill: _Ink | None) -> int:
594
+ ink, fill_ink = self._getink(fill)
595
+ if ink is None:
596
+ assert fill_ink is not None
597
+ return fill_ink
598
+ return ink
599
+
600
+ def draw_text(ink: int, stroke_width: float = 0) -> None:
601
+ mode = self.fontmode
602
+ if stroke_width == 0 and embedded_color:
603
+ mode = "RGBA"
604
+ coord = []
605
+ for i in range(2):
606
+ coord.append(int(xy[i]))
607
+ start = (math.modf(xy[0])[0], math.modf(xy[1])[0])
608
+ try:
609
+ mask, offset = font.getmask2( # type: ignore[union-attr,misc]
610
+ text,
611
+ mode,
612
+ direction=direction,
613
+ features=features,
614
+ language=language,
615
+ stroke_width=stroke_width,
616
+ stroke_filled=True,
617
+ anchor=anchor,
618
+ ink=ink,
619
+ start=start,
620
+ *args,
621
+ **kwargs,
622
+ )
623
+ coord = [coord[0] + offset[0], coord[1] + offset[1]]
624
+ except AttributeError:
625
+ try:
626
+ mask = font.getmask( # type: ignore[misc]
627
+ text,
628
+ mode,
629
+ direction,
630
+ features,
631
+ language,
632
+ stroke_width,
633
+ anchor,
634
+ ink,
635
+ start=start,
636
+ *args,
637
+ **kwargs,
638
+ )
639
+ except TypeError:
640
+ mask = font.getmask(text)
641
+ if mode == "RGBA":
642
+ # font.getmask2(mode="RGBA") returns color in RGB bands and mask in A
643
+ # extract mask and set text alpha
644
+ color, mask = mask, mask.getband(3)
645
+ ink_alpha = struct.pack("i", ink)[3]
646
+ color.fillband(3, ink_alpha)
647
+ x, y = coord
648
+ if self.im is not None:
649
+ self.im.paste(
650
+ color, (x, y, x + mask.size[0], y + mask.size[1]), mask
651
+ )
652
+ else:
653
+ self.draw.draw_bitmap(coord, mask, ink)
654
+
655
+ ink = getink(fill)
656
+ if ink is not None:
657
+ stroke_ink = None
658
+ if stroke_width:
659
+ stroke_ink = getink(stroke_fill) if stroke_fill is not None else ink
660
+
661
+ if stroke_ink is not None:
662
+ # Draw stroked text
663
+ draw_text(stroke_ink, stroke_width)
664
+
665
+ # Draw normal text
666
+ if ink != stroke_ink:
667
+ draw_text(ink)
668
+ else:
669
+ # Only draw normal text
670
+ draw_text(ink)
671
+
672
+ def _prepare_multiline_text(
673
+ self,
674
+ xy: tuple[float, float],
675
+ text: AnyStr,
676
+ font: (
677
+ ImageFont.ImageFont
678
+ | ImageFont.FreeTypeFont
679
+ | ImageFont.TransposedFont
680
+ | None
681
+ ),
682
+ anchor: str | None,
683
+ spacing: float,
684
+ align: str,
685
+ direction: str | None,
686
+ features: list[str] | None,
687
+ language: str | None,
688
+ stroke_width: float,
689
+ embedded_color: bool,
690
+ font_size: float | None,
691
+ ) -> tuple[
692
+ ImageFont.ImageFont | ImageFont.FreeTypeFont | ImageFont.TransposedFont,
693
+ list[tuple[tuple[float, float], str, AnyStr]],
694
+ ]:
695
+ if anchor is None:
696
+ anchor = "lt" if direction == "ttb" else "la"
697
+ elif len(anchor) != 2:
698
+ msg = "anchor must be a 2 character string"
699
+ raise ValueError(msg)
700
+ elif anchor[1] in "tb" and direction != "ttb":
701
+ msg = "anchor not supported for multiline text"
702
+ raise ValueError(msg)
703
+
704
+ if font is None:
705
+ font = self._getfont(font_size)
706
+
707
+ lines = text.split("\n" if isinstance(text, str) else b"\n")
708
+ line_spacing = (
709
+ self.textbbox((0, 0), "A", font, stroke_width=stroke_width)[3]
710
+ + stroke_width
711
+ + spacing
712
+ )
713
+
714
+ top = xy[1]
715
+ parts = []
716
+ if direction == "ttb":
717
+ left = xy[0]
718
+ for line in lines:
719
+ parts.append(((left, top), anchor, line))
720
+ left += line_spacing
721
+ else:
722
+ widths = []
723
+ max_width: float = 0
724
+ for line in lines:
725
+ line_width = self.textlength(
726
+ line,
727
+ font,
728
+ direction=direction,
729
+ features=features,
730
+ language=language,
731
+ embedded_color=embedded_color,
732
+ )
733
+ widths.append(line_width)
734
+ max_width = max(max_width, line_width)
735
+
736
+ if anchor[1] == "m":
737
+ top -= (len(lines) - 1) * line_spacing / 2.0
738
+ elif anchor[1] == "d":
739
+ top -= (len(lines) - 1) * line_spacing
740
+
741
+ for idx, line in enumerate(lines):
742
+ left = xy[0]
743
+ width_difference = max_width - widths[idx]
744
+
745
+ # align by align parameter
746
+ if align in ("left", "justify"):
747
+ pass
748
+ elif align == "center":
749
+ left += width_difference / 2.0
750
+ elif align == "right":
751
+ left += width_difference
752
+ else:
753
+ msg = 'align must be "left", "center", "right" or "justify"'
754
+ raise ValueError(msg)
755
+
756
+ if (
757
+ align == "justify"
758
+ and width_difference != 0
759
+ and idx != len(lines) - 1
760
+ ):
761
+ words = line.split(" " if isinstance(text, str) else b" ")
762
+ if len(words) > 1:
763
+ # align left by anchor
764
+ if anchor[0] == "m":
765
+ left -= max_width / 2.0
766
+ elif anchor[0] == "r":
767
+ left -= max_width
768
+
769
+ word_widths = [
770
+ self.textlength(
771
+ word,
772
+ font,
773
+ direction=direction,
774
+ features=features,
775
+ language=language,
776
+ embedded_color=embedded_color,
777
+ )
778
+ for word in words
779
+ ]
780
+ word_anchor = "l" + anchor[1]
781
+ width_difference = max_width - sum(word_widths)
782
+ for i, word in enumerate(words):
783
+ parts.append(((left, top), word_anchor, word))
784
+ left += word_widths[i] + width_difference / (len(words) - 1)
785
+ top += line_spacing
786
+ continue
787
+
788
+ # align left by anchor
789
+ if anchor[0] == "m":
790
+ left -= width_difference / 2.0
791
+ elif anchor[0] == "r":
792
+ left -= width_difference
793
+ parts.append(((left, top), anchor, line))
794
+ top += line_spacing
795
+
796
+ return font, parts
797
+
798
+ def multiline_text(
799
+ self,
800
+ xy: tuple[float, float],
801
+ text: AnyStr,
802
+ fill: _Ink | None = None,
803
+ font: (
804
+ ImageFont.ImageFont
805
+ | ImageFont.FreeTypeFont
806
+ | ImageFont.TransposedFont
807
+ | None
808
+ ) = None,
809
+ anchor: str | None = None,
810
+ spacing: float = 4,
811
+ align: str = "left",
812
+ direction: str | None = None,
813
+ features: list[str] | None = None,
814
+ language: str | None = None,
815
+ stroke_width: float = 0,
816
+ stroke_fill: _Ink | None = None,
817
+ embedded_color: bool = False,
818
+ *,
819
+ font_size: float | None = None,
820
+ ) -> None:
821
+ font, lines = self._prepare_multiline_text(
822
+ xy,
823
+ text,
824
+ font,
825
+ anchor,
826
+ spacing,
827
+ align,
828
+ direction,
829
+ features,
830
+ language,
831
+ stroke_width,
832
+ embedded_color,
833
+ font_size,
834
+ )
835
+
836
+ for xy, anchor, line in lines:
837
+ self.text(
838
+ xy,
839
+ line,
840
+ fill,
841
+ font,
842
+ anchor,
843
+ direction=direction,
844
+ features=features,
845
+ language=language,
846
+ stroke_width=stroke_width,
847
+ stroke_fill=stroke_fill,
848
+ embedded_color=embedded_color,
849
+ )
850
+
851
+ def textlength(
852
+ self,
853
+ text: AnyStr,
854
+ font: (
855
+ ImageFont.ImageFont
856
+ | ImageFont.FreeTypeFont
857
+ | ImageFont.TransposedFont
858
+ | None
859
+ ) = None,
860
+ direction: str | None = None,
861
+ features: list[str] | None = None,
862
+ language: str | None = None,
863
+ embedded_color: bool = False,
864
+ *,
865
+ font_size: float | None = None,
866
+ ) -> float:
867
+ """Get the length of a given string, in pixels with 1/64 precision."""
868
+ if self._multiline_check(text):
869
+ msg = "can't measure length of multiline text"
870
+ raise ValueError(msg)
871
+ if embedded_color and self.mode not in ("RGB", "RGBA"):
872
+ msg = "Embedded color supported only in RGB and RGBA modes"
873
+ raise ValueError(msg)
874
+
875
+ if font is None:
876
+ font = self._getfont(font_size)
877
+ mode = "RGBA" if embedded_color else self.fontmode
878
+ return font.getlength(text, mode, direction, features, language)
879
+
880
+ def textbbox(
881
+ self,
882
+ xy: tuple[float, float],
883
+ text: AnyStr,
884
+ font: (
885
+ ImageFont.ImageFont
886
+ | ImageFont.FreeTypeFont
887
+ | ImageFont.TransposedFont
888
+ | None
889
+ ) = None,
890
+ anchor: str | None = None,
891
+ spacing: float = 4,
892
+ align: str = "left",
893
+ direction: str | None = None,
894
+ features: list[str] | None = None,
895
+ language: str | None = None,
896
+ stroke_width: float = 0,
897
+ embedded_color: bool = False,
898
+ *,
899
+ font_size: float | None = None,
900
+ ) -> tuple[float, float, float, float]:
901
+ """Get the bounding box of a given string, in pixels."""
902
+ if embedded_color and self.mode not in ("RGB", "RGBA"):
903
+ msg = "Embedded color supported only in RGB and RGBA modes"
904
+ raise ValueError(msg)
905
+
906
+ if font is None:
907
+ font = self._getfont(font_size)
908
+
909
+ if self._multiline_check(text):
910
+ return self.multiline_textbbox(
911
+ xy,
912
+ text,
913
+ font,
914
+ anchor,
915
+ spacing,
916
+ align,
917
+ direction,
918
+ features,
919
+ language,
920
+ stroke_width,
921
+ embedded_color,
922
+ )
923
+
924
+ mode = "RGBA" if embedded_color else self.fontmode
925
+ bbox = font.getbbox(
926
+ text, mode, direction, features, language, stroke_width, anchor
927
+ )
928
+ return bbox[0] + xy[0], bbox[1] + xy[1], bbox[2] + xy[0], bbox[3] + xy[1]
929
+
930
+ def multiline_textbbox(
931
+ self,
932
+ xy: tuple[float, float],
933
+ text: AnyStr,
934
+ font: (
935
+ ImageFont.ImageFont
936
+ | ImageFont.FreeTypeFont
937
+ | ImageFont.TransposedFont
938
+ | None
939
+ ) = None,
940
+ anchor: str | None = None,
941
+ spacing: float = 4,
942
+ align: str = "left",
943
+ direction: str | None = None,
944
+ features: list[str] | None = None,
945
+ language: str | None = None,
946
+ stroke_width: float = 0,
947
+ embedded_color: bool = False,
948
+ *,
949
+ font_size: float | None = None,
950
+ ) -> tuple[float, float, float, float]:
951
+ font, lines = self._prepare_multiline_text(
952
+ xy,
953
+ text,
954
+ font,
955
+ anchor,
956
+ spacing,
957
+ align,
958
+ direction,
959
+ features,
960
+ language,
961
+ stroke_width,
962
+ embedded_color,
963
+ font_size,
964
+ )
965
+
966
+ bbox: tuple[float, float, float, float] | None = None
967
+
968
+ for xy, anchor, line in lines:
969
+ bbox_line = self.textbbox(
970
+ xy,
971
+ line,
972
+ font,
973
+ anchor,
974
+ direction=direction,
975
+ features=features,
976
+ language=language,
977
+ stroke_width=stroke_width,
978
+ embedded_color=embedded_color,
979
+ )
980
+ if bbox is None:
981
+ bbox = bbox_line
982
+ else:
983
+ bbox = (
984
+ min(bbox[0], bbox_line[0]),
985
+ min(bbox[1], bbox_line[1]),
986
+ max(bbox[2], bbox_line[2]),
987
+ max(bbox[3], bbox_line[3]),
988
+ )
989
+
990
+ if bbox is None:
991
+ return xy[0], xy[1], xy[0], xy[1]
992
+ return bbox
993
+
994
+
995
+ def Draw(im: Image.Image, mode: str | None = None) -> ImageDraw:
996
+ """
997
+ A simple 2D drawing interface for PIL images.
998
+
999
+ :param im: The image to draw in.
1000
+ :param mode: Optional mode to use for color values. For RGB
1001
+ images, this argument can be RGB or RGBA (to blend the
1002
+ drawing into the image). For all other modes, this argument
1003
+ must be the same as the image mode. If omitted, the mode
1004
+ defaults to the mode of the image.
1005
+ """
1006
+ try:
1007
+ return getattr(im, "getdraw")(mode)
1008
+ except AttributeError:
1009
+ return ImageDraw(im, mode)
1010
+
1011
+
1012
+ def getdraw(
1013
+ im: Image.Image | None = None, hints: list[str] | None = None
1014
+ ) -> tuple[ImageDraw2.Draw | None, ModuleType]:
1015
+ """
1016
+ :param im: The image to draw in.
1017
+ :param hints: An optional list of hints. Deprecated.
1018
+ :returns: A (drawing context, drawing resource factory) tuple.
1019
+ """
1020
+ if hints is not None:
1021
+ deprecate("'hints' parameter", 12)
1022
+ from . import ImageDraw2
1023
+
1024
+ draw = ImageDraw2.Draw(im) if im is not None else None
1025
+ return draw, ImageDraw2
1026
+
1027
+
1028
+ def floodfill(
1029
+ image: Image.Image,
1030
+ xy: tuple[int, int],
1031
+ value: float | tuple[int, ...],
1032
+ border: float | tuple[int, ...] | None = None,
1033
+ thresh: float = 0,
1034
+ ) -> None:
1035
+ """
1036
+ .. warning:: This method is experimental.
1037
+
1038
+ Fills a bounded region with a given color.
1039
+
1040
+ :param image: Target image.
1041
+ :param xy: Seed position (a 2-item coordinate tuple). See
1042
+ :ref:`coordinate-system`.
1043
+ :param value: Fill color.
1044
+ :param border: Optional border value. If given, the region consists of
1045
+ pixels with a color different from the border color. If not given,
1046
+ the region consists of pixels having the same color as the seed
1047
+ pixel.
1048
+ :param thresh: Optional threshold value which specifies a maximum
1049
+ tolerable difference of a pixel value from the 'background' in
1050
+ order for it to be replaced. Useful for filling regions of
1051
+ non-homogeneous, but similar, colors.
1052
+ """
1053
+ # based on an implementation by Eric S. Raymond
1054
+ # amended by yo1995 @20180806
1055
+ pixel = image.load()
1056
+ assert pixel is not None
1057
+ x, y = xy
1058
+ try:
1059
+ background = pixel[x, y]
1060
+ if _color_diff(value, background) <= thresh:
1061
+ return # seed point already has fill color
1062
+ pixel[x, y] = value
1063
+ except (ValueError, IndexError):
1064
+ return # seed point outside image
1065
+ edge = {(x, y)}
1066
+ # use a set to keep record of current and previous edge pixels
1067
+ # to reduce memory consumption
1068
+ full_edge = set()
1069
+ while edge:
1070
+ new_edge = set()
1071
+ for x, y in edge: # 4 adjacent method
1072
+ for s, t in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)):
1073
+ # If already processed, or if a coordinate is negative, skip
1074
+ if (s, t) in full_edge or s < 0 or t < 0:
1075
+ continue
1076
+ try:
1077
+ p = pixel[s, t]
1078
+ except (ValueError, IndexError):
1079
+ pass
1080
+ else:
1081
+ full_edge.add((s, t))
1082
+ if border is None:
1083
+ fill = _color_diff(p, background) <= thresh
1084
+ else:
1085
+ fill = p not in (value, border)
1086
+ if fill:
1087
+ pixel[s, t] = value
1088
+ new_edge.add((s, t))
1089
+ full_edge = edge # discard pixels processed
1090
+ edge = new_edge
1091
+
1092
+
1093
+ def _compute_regular_polygon_vertices(
1094
+ bounding_circle: Sequence[Sequence[float] | float], n_sides: int, rotation: float
1095
+ ) -> list[tuple[float, float]]:
1096
+ """
1097
+ Generate a list of vertices for a 2D regular polygon.
1098
+
1099
+ :param bounding_circle: The bounding circle is a sequence defined
1100
+ by a point and radius. The polygon is inscribed in this circle.
1101
+ (e.g. ``bounding_circle=(x, y, r)`` or ``((x, y), r)``)
1102
+ :param n_sides: Number of sides
1103
+ (e.g. ``n_sides=3`` for a triangle, ``6`` for a hexagon)
1104
+ :param rotation: Apply an arbitrary rotation to the polygon
1105
+ (e.g. ``rotation=90``, applies a 90 degree rotation)
1106
+ :return: List of regular polygon vertices
1107
+ (e.g. ``[(25, 50), (50, 50), (50, 25), (25, 25)]``)
1108
+
1109
+ How are the vertices computed?
1110
+ 1. Compute the following variables
1111
+ - theta: Angle between the apothem & the nearest polygon vertex
1112
+ - side_length: Length of each polygon edge
1113
+ - centroid: Center of bounding circle (1st, 2nd elements of bounding_circle)
1114
+ - polygon_radius: Polygon radius (last element of bounding_circle)
1115
+ - angles: Location of each polygon vertex in polar grid
1116
+ (e.g. A square with 0 degree rotation => [225.0, 315.0, 45.0, 135.0])
1117
+
1118
+ 2. For each angle in angles, get the polygon vertex at that angle
1119
+ The vertex is computed using the equation below.
1120
+ X= xcos(φ) + ysin(φ)
1121
+ Y= −xsin(φ) + ycos(φ)
1122
+
1123
+ Note:
1124
+ φ = angle in degrees
1125
+ x = 0
1126
+ y = polygon_radius
1127
+
1128
+ The formula above assumes rotation around the origin.
1129
+ In our case, we are rotating around the centroid.
1130
+ To account for this, we use the formula below
1131
+ X = xcos(φ) + ysin(φ) + centroid_x
1132
+ Y = −xsin(φ) + ycos(φ) + centroid_y
1133
+ """
1134
+ # 1. Error Handling
1135
+ # 1.1 Check `n_sides` has an appropriate value
1136
+ if not isinstance(n_sides, int):
1137
+ msg = "n_sides should be an int" # type: ignore[unreachable]
1138
+ raise TypeError(msg)
1139
+ if n_sides < 3:
1140
+ msg = "n_sides should be an int > 2"
1141
+ raise ValueError(msg)
1142
+
1143
+ # 1.2 Check `bounding_circle` has an appropriate value
1144
+ if not isinstance(bounding_circle, (list, tuple)):
1145
+ msg = "bounding_circle should be a sequence"
1146
+ raise TypeError(msg)
1147
+
1148
+ if len(bounding_circle) == 3:
1149
+ if not all(isinstance(i, (int, float)) for i in bounding_circle):
1150
+ msg = "bounding_circle should only contain numeric data"
1151
+ raise ValueError(msg)
1152
+
1153
+ *centroid, polygon_radius = cast(list[float], list(bounding_circle))
1154
+ elif len(bounding_circle) == 2 and isinstance(bounding_circle[0], (list, tuple)):
1155
+ if not all(
1156
+ isinstance(i, (int, float)) for i in bounding_circle[0]
1157
+ ) or not isinstance(bounding_circle[1], (int, float)):
1158
+ msg = "bounding_circle should only contain numeric data"
1159
+ raise ValueError(msg)
1160
+
1161
+ if len(bounding_circle[0]) != 2:
1162
+ msg = "bounding_circle centre should contain 2D coordinates (e.g. (x, y))"
1163
+ raise ValueError(msg)
1164
+
1165
+ centroid = cast(list[float], list(bounding_circle[0]))
1166
+ polygon_radius = cast(float, bounding_circle[1])
1167
+ else:
1168
+ msg = (
1169
+ "bounding_circle should contain 2D coordinates "
1170
+ "and a radius (e.g. (x, y, r) or ((x, y), r) )"
1171
+ )
1172
+ raise ValueError(msg)
1173
+
1174
+ if polygon_radius <= 0:
1175
+ msg = "bounding_circle radius should be > 0"
1176
+ raise ValueError(msg)
1177
+
1178
+ # 1.3 Check `rotation` has an appropriate value
1179
+ if not isinstance(rotation, (int, float)):
1180
+ msg = "rotation should be an int or float" # type: ignore[unreachable]
1181
+ raise ValueError(msg)
1182
+
1183
+ # 2. Define Helper Functions
1184
+ def _apply_rotation(point: list[float], degrees: float) -> tuple[float, float]:
1185
+ return (
1186
+ round(
1187
+ point[0] * math.cos(math.radians(360 - degrees))
1188
+ - point[1] * math.sin(math.radians(360 - degrees))
1189
+ + centroid[0],
1190
+ 2,
1191
+ ),
1192
+ round(
1193
+ point[1] * math.cos(math.radians(360 - degrees))
1194
+ + point[0] * math.sin(math.radians(360 - degrees))
1195
+ + centroid[1],
1196
+ 2,
1197
+ ),
1198
+ )
1199
+
1200
+ def _compute_polygon_vertex(angle: float) -> tuple[float, float]:
1201
+ start_point = [polygon_radius, 0]
1202
+ return _apply_rotation(start_point, angle)
1203
+
1204
+ def _get_angles(n_sides: int, rotation: float) -> list[float]:
1205
+ angles = []
1206
+ degrees = 360 / n_sides
1207
+ # Start with the bottom left polygon vertex
1208
+ current_angle = (270 - 0.5 * degrees) + rotation
1209
+ for _ in range(n_sides):
1210
+ angles.append(current_angle)
1211
+ current_angle += degrees
1212
+ if current_angle > 360:
1213
+ current_angle -= 360
1214
+ return angles
1215
+
1216
+ # 3. Variable Declarations
1217
+ angles = _get_angles(n_sides, rotation)
1218
+
1219
+ # 4. Compute Vertices
1220
+ return [_compute_polygon_vertex(angle) for angle in angles]
1221
+
1222
+
1223
+ def _color_diff(
1224
+ color1: float | tuple[int, ...], color2: float | tuple[int, ...]
1225
+ ) -> float:
1226
+ """
1227
+ Uses 1-norm distance to calculate difference between two values.
1228
+ """
1229
+ first = color1 if isinstance(color1, tuple) else (color1,)
1230
+ second = color2 if isinstance(color2, tuple) else (color2,)
1231
+
1232
+ return sum(abs(first[i] - second[i]) for i in range(len(second)))
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/ImageDraw2.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library
3
+ # $Id$
4
+ #
5
+ # WCK-style drawing interface operations
6
+ #
7
+ # History:
8
+ # 2003-12-07 fl created
9
+ # 2005-05-15 fl updated; added to PIL as ImageDraw2
10
+ # 2005-05-15 fl added text support
11
+ # 2005-05-20 fl added arc/chord/pieslice support
12
+ #
13
+ # Copyright (c) 2003-2005 by Secret Labs AB
14
+ # Copyright (c) 2003-2005 by Fredrik Lundh
15
+ #
16
+ # See the README file for information on usage and redistribution.
17
+ #
18
+
19
+
20
+ """
21
+ (Experimental) WCK-style drawing interface operations
22
+
23
+ .. seealso:: :py:mod:`PIL.ImageDraw`
24
+ """
25
+ from __future__ import annotations
26
+
27
+ from typing import Any, AnyStr, BinaryIO
28
+
29
+ from . import Image, ImageColor, ImageDraw, ImageFont, ImagePath
30
+ from ._typing import Coords, StrOrBytesPath
31
+
32
+
33
+ class Pen:
34
+ """Stores an outline color and width."""
35
+
36
+ def __init__(self, color: str, width: int = 1, opacity: int = 255) -> None:
37
+ self.color = ImageColor.getrgb(color)
38
+ self.width = width
39
+
40
+
41
+ class Brush:
42
+ """Stores a fill color"""
43
+
44
+ def __init__(self, color: str, opacity: int = 255) -> None:
45
+ self.color = ImageColor.getrgb(color)
46
+
47
+
48
+ class Font:
49
+ """Stores a TrueType font and color"""
50
+
51
+ def __init__(
52
+ self, color: str, file: StrOrBytesPath | BinaryIO, size: float = 12
53
+ ) -> None:
54
+ # FIXME: add support for bitmap fonts
55
+ self.color = ImageColor.getrgb(color)
56
+ self.font = ImageFont.truetype(file, size)
57
+
58
+
59
+ class Draw:
60
+ """
61
+ (Experimental) WCK-style drawing interface
62
+ """
63
+
64
+ def __init__(
65
+ self,
66
+ image: Image.Image | str,
67
+ size: tuple[int, int] | list[int] | None = None,
68
+ color: float | tuple[float, ...] | str | None = None,
69
+ ) -> None:
70
+ if isinstance(image, str):
71
+ if size is None:
72
+ msg = "If image argument is mode string, size must be a list or tuple"
73
+ raise ValueError(msg)
74
+ image = Image.new(image, size, color)
75
+ self.draw = ImageDraw.Draw(image)
76
+ self.image = image
77
+ self.transform: tuple[float, float, float, float, float, float] | None = None
78
+
79
+ def flush(self) -> Image.Image:
80
+ return self.image
81
+
82
+ def render(
83
+ self,
84
+ op: str,
85
+ xy: Coords,
86
+ pen: Pen | Brush | None,
87
+ brush: Brush | Pen | None = None,
88
+ **kwargs: Any,
89
+ ) -> None:
90
+ # handle color arguments
91
+ outline = fill = None
92
+ width = 1
93
+ if isinstance(pen, Pen):
94
+ outline = pen.color
95
+ width = pen.width
96
+ elif isinstance(brush, Pen):
97
+ outline = brush.color
98
+ width = brush.width
99
+ if isinstance(brush, Brush):
100
+ fill = brush.color
101
+ elif isinstance(pen, Brush):
102
+ fill = pen.color
103
+ # handle transformation
104
+ if self.transform:
105
+ path = ImagePath.Path(xy)
106
+ path.transform(self.transform)
107
+ xy = path
108
+ # render the item
109
+ if op in ("arc", "line"):
110
+ kwargs.setdefault("fill", outline)
111
+ else:
112
+ kwargs.setdefault("fill", fill)
113
+ kwargs.setdefault("outline", outline)
114
+ if op == "line":
115
+ kwargs.setdefault("width", width)
116
+ getattr(self.draw, op)(xy, **kwargs)
117
+
118
+ def settransform(self, offset: tuple[float, float]) -> None:
119
+ """Sets a transformation offset."""
120
+ (xoffset, yoffset) = offset
121
+ self.transform = (1, 0, xoffset, 0, 1, yoffset)
122
+
123
+ def arc(
124
+ self,
125
+ xy: Coords,
126
+ pen: Pen | Brush | None,
127
+ start: float,
128
+ end: float,
129
+ *options: Any,
130
+ ) -> None:
131
+ """
132
+ Draws an arc (a portion of a circle outline) between the start and end
133
+ angles, inside the given bounding box.
134
+
135
+ .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.arc`
136
+ """
137
+ self.render("arc", xy, pen, *options, start=start, end=end)
138
+
139
+ def chord(
140
+ self,
141
+ xy: Coords,
142
+ pen: Pen | Brush | None,
143
+ start: float,
144
+ end: float,
145
+ *options: Any,
146
+ ) -> None:
147
+ """
148
+ Same as :py:meth:`~PIL.ImageDraw2.Draw.arc`, but connects the end points
149
+ with a straight line.
150
+
151
+ .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.chord`
152
+ """
153
+ self.render("chord", xy, pen, *options, start=start, end=end)
154
+
155
+ def ellipse(self, xy: Coords, pen: Pen | Brush | None, *options: Any) -> None:
156
+ """
157
+ Draws an ellipse inside the given bounding box.
158
+
159
+ .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.ellipse`
160
+ """
161
+ self.render("ellipse", xy, pen, *options)
162
+
163
+ def line(self, xy: Coords, pen: Pen | Brush | None, *options: Any) -> None:
164
+ """
165
+ Draws a line between the coordinates in the ``xy`` list.
166
+
167
+ .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.line`
168
+ """
169
+ self.render("line", xy, pen, *options)
170
+
171
+ def pieslice(
172
+ self,
173
+ xy: Coords,
174
+ pen: Pen | Brush | None,
175
+ start: float,
176
+ end: float,
177
+ *options: Any,
178
+ ) -> None:
179
+ """
180
+ Same as arc, but also draws straight lines between the end points and the
181
+ center of the bounding box.
182
+
183
+ .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.pieslice`
184
+ """
185
+ self.render("pieslice", xy, pen, *options, start=start, end=end)
186
+
187
+ def polygon(self, xy: Coords, pen: Pen | Brush | None, *options: Any) -> None:
188
+ """
189
+ Draws a polygon.
190
+
191
+ The polygon outline consists of straight lines between the given
192
+ coordinates, plus a straight line between the last and the first
193
+ coordinate.
194
+
195
+
196
+ .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.polygon`
197
+ """
198
+ self.render("polygon", xy, pen, *options)
199
+
200
+ def rectangle(self, xy: Coords, pen: Pen | Brush | None, *options: Any) -> None:
201
+ """
202
+ Draws a rectangle.
203
+
204
+ .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.rectangle`
205
+ """
206
+ self.render("rectangle", xy, pen, *options)
207
+
208
+ def text(self, xy: tuple[float, float], text: AnyStr, font: Font) -> None:
209
+ """
210
+ Draws the string at the given position.
211
+
212
+ .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.text`
213
+ """
214
+ if self.transform:
215
+ path = ImagePath.Path(xy)
216
+ path.transform(self.transform)
217
+ xy = path
218
+ self.draw.text(xy, text, font=font.font, fill=font.color)
219
+
220
+ def textbbox(
221
+ self, xy: tuple[float, float], text: AnyStr, font: Font
222
+ ) -> tuple[float, float, float, float]:
223
+ """
224
+ Returns bounding box (in pixels) of given text.
225
+
226
+ :return: ``(left, top, right, bottom)`` bounding box
227
+
228
+ .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.textbbox`
229
+ """
230
+ if self.transform:
231
+ path = ImagePath.Path(xy)
232
+ path.transform(self.transform)
233
+ xy = path
234
+ return self.draw.textbbox(xy, text, font=font.font)
235
+
236
+ def textlength(self, text: AnyStr, font: Font) -> float:
237
+ """
238
+ Returns length (in pixels) of given text.
239
+ This is the amount by which following text should be offset.
240
+
241
+ .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.textlength`
242
+ """
243
+ return self.draw.textlength(text, font=font.font)
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/ImageEnhance.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # image enhancement classes
6
+ #
7
+ # For a background, see "Image Processing By Interpolation and
8
+ # Extrapolation", Paul Haeberli and Douglas Voorhies. Available
9
+ # at http://www.graficaobscura.com/interp/index.html
10
+ #
11
+ # History:
12
+ # 1996-03-23 fl Created
13
+ # 2009-06-16 fl Fixed mean calculation
14
+ #
15
+ # Copyright (c) Secret Labs AB 1997.
16
+ # Copyright (c) Fredrik Lundh 1996.
17
+ #
18
+ # See the README file for information on usage and redistribution.
19
+ #
20
+ from __future__ import annotations
21
+
22
+ from . import Image, ImageFilter, ImageStat
23
+
24
+
25
+ class _Enhance:
26
+ image: Image.Image
27
+ degenerate: Image.Image
28
+
29
+ def enhance(self, factor: float) -> Image.Image:
30
+ """
31
+ Returns an enhanced image.
32
+
33
+ :param factor: A floating point value controlling the enhancement.
34
+ Factor 1.0 always returns a copy of the original image,
35
+ lower factors mean less color (brightness, contrast,
36
+ etc), and higher values more. There are no restrictions
37
+ on this value.
38
+ :rtype: :py:class:`~PIL.Image.Image`
39
+ """
40
+ return Image.blend(self.degenerate, self.image, factor)
41
+
42
+
43
+ class Color(_Enhance):
44
+ """Adjust image color balance.
45
+
46
+ This class can be used to adjust the colour balance of an image, in
47
+ a manner similar to the controls on a colour TV set. An enhancement
48
+ factor of 0.0 gives a black and white image. A factor of 1.0 gives
49
+ the original image.
50
+ """
51
+
52
+ def __init__(self, image: Image.Image) -> None:
53
+ self.image = image
54
+ self.intermediate_mode = "L"
55
+ if "A" in image.getbands():
56
+ self.intermediate_mode = "LA"
57
+
58
+ if self.intermediate_mode != image.mode:
59
+ image = image.convert(self.intermediate_mode).convert(image.mode)
60
+ self.degenerate = image
61
+
62
+
63
+ class Contrast(_Enhance):
64
+ """Adjust image contrast.
65
+
66
+ This class can be used to control the contrast of an image, similar
67
+ to the contrast control on a TV set. An enhancement factor of 0.0
68
+ gives a solid gray image. A factor of 1.0 gives the original image.
69
+ """
70
+
71
+ def __init__(self, image: Image.Image) -> None:
72
+ self.image = image
73
+ if image.mode != "L":
74
+ image = image.convert("L")
75
+ mean = int(ImageStat.Stat(image).mean[0] + 0.5)
76
+ self.degenerate = Image.new("L", image.size, mean)
77
+ if self.degenerate.mode != self.image.mode:
78
+ self.degenerate = self.degenerate.convert(self.image.mode)
79
+
80
+ if "A" in self.image.getbands():
81
+ self.degenerate.putalpha(self.image.getchannel("A"))
82
+
83
+
84
+ class Brightness(_Enhance):
85
+ """Adjust image brightness.
86
+
87
+ This class can be used to control the brightness of an image. An
88
+ enhancement factor of 0.0 gives a black image. A factor of 1.0 gives the
89
+ original image.
90
+ """
91
+
92
+ def __init__(self, image: Image.Image) -> None:
93
+ self.image = image
94
+ self.degenerate = Image.new(image.mode, image.size, 0)
95
+
96
+ if "A" in image.getbands():
97
+ self.degenerate.putalpha(image.getchannel("A"))
98
+
99
+
100
+ class Sharpness(_Enhance):
101
+ """Adjust image sharpness.
102
+
103
+ This class can be used to adjust the sharpness of an image. An
104
+ enhancement factor of 0.0 gives a blurred image, a factor of 1.0 gives the
105
+ original image, and a factor of 2.0 gives a sharpened image.
106
+ """
107
+
108
+ def __init__(self, image: Image.Image) -> None:
109
+ self.image = image
110
+ self.degenerate = image.filter(ImageFilter.SMOOTH)
111
+
112
+ if "A" in image.getbands():
113
+ self.degenerate.putalpha(image.getchannel("A"))
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/ImageFile.py ADDED
@@ -0,0 +1,922 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # base class for image file handlers
6
+ #
7
+ # history:
8
+ # 1995-09-09 fl Created
9
+ # 1996-03-11 fl Fixed load mechanism.
10
+ # 1996-04-15 fl Added pcx/xbm decoders.
11
+ # 1996-04-30 fl Added encoders.
12
+ # 1996-12-14 fl Added load helpers
13
+ # 1997-01-11 fl Use encode_to_file where possible
14
+ # 1997-08-27 fl Flush output in _save
15
+ # 1998-03-05 fl Use memory mapping for some modes
16
+ # 1999-02-04 fl Use memory mapping also for "I;16" and "I;16B"
17
+ # 1999-05-31 fl Added image parser
18
+ # 2000-10-12 fl Set readonly flag on memory-mapped images
19
+ # 2002-03-20 fl Use better messages for common decoder errors
20
+ # 2003-04-21 fl Fall back on mmap/map_buffer if map is not available
21
+ # 2003-10-30 fl Added StubImageFile class
22
+ # 2004-02-25 fl Made incremental parser more robust
23
+ #
24
+ # Copyright (c) 1997-2004 by Secret Labs AB
25
+ # Copyright (c) 1995-2004 by Fredrik Lundh
26
+ #
27
+ # See the README file for information on usage and redistribution.
28
+ #
29
+ from __future__ import annotations
30
+
31
+ import abc
32
+ import io
33
+ import itertools
34
+ import logging
35
+ import os
36
+ import struct
37
+ from typing import IO, Any, NamedTuple, cast
38
+
39
+ from . import ExifTags, Image
40
+ from ._deprecate import deprecate
41
+ from ._util import DeferredError, is_path
42
+
43
+ TYPE_CHECKING = False
44
+ if TYPE_CHECKING:
45
+ from ._typing import StrOrBytesPath
46
+
47
+ logger = logging.getLogger(__name__)
48
+
49
+ MAXBLOCK = 65536
50
+
51
+ SAFEBLOCK = 1024 * 1024
52
+
53
+ LOAD_TRUNCATED_IMAGES = False
54
+ """Whether or not to load truncated image files. User code may change this."""
55
+
56
+ ERRORS = {
57
+ -1: "image buffer overrun error",
58
+ -2: "decoding error",
59
+ -3: "unknown error",
60
+ -8: "bad configuration",
61
+ -9: "out of memory error",
62
+ }
63
+ """
64
+ Dict of known error codes returned from :meth:`.PyDecoder.decode`,
65
+ :meth:`.PyEncoder.encode` :meth:`.PyEncoder.encode_to_pyfd` and
66
+ :meth:`.PyEncoder.encode_to_file`.
67
+ """
68
+
69
+
70
+ #
71
+ # --------------------------------------------------------------------
72
+ # Helpers
73
+
74
+
75
+ def _get_oserror(error: int, *, encoder: bool) -> OSError:
76
+ try:
77
+ msg = Image.core.getcodecstatus(error)
78
+ except AttributeError:
79
+ msg = ERRORS.get(error)
80
+ if not msg:
81
+ msg = f"{'encoder' if encoder else 'decoder'} error {error}"
82
+ msg += f" when {'writing' if encoder else 'reading'} image file"
83
+ return OSError(msg)
84
+
85
+
86
+ def raise_oserror(error: int) -> OSError:
87
+ deprecate(
88
+ "raise_oserror",
89
+ 12,
90
+ action="It is only useful for translating error codes returned by a codec's "
91
+ "decode() method, which ImageFile already does automatically.",
92
+ )
93
+ raise _get_oserror(error, encoder=False)
94
+
95
+
96
+ def _tilesort(t: _Tile) -> int:
97
+ # sort on offset
98
+ return t[2]
99
+
100
+
101
+ class _Tile(NamedTuple):
102
+ codec_name: str
103
+ extents: tuple[int, int, int, int] | None
104
+ offset: int = 0
105
+ args: tuple[Any, ...] | str | None = None
106
+
107
+
108
+ #
109
+ # --------------------------------------------------------------------
110
+ # ImageFile base class
111
+
112
+
113
+ class ImageFile(Image.Image):
114
+ """Base class for image file format handlers."""
115
+
116
+ def __init__(
117
+ self, fp: StrOrBytesPath | IO[bytes], filename: str | bytes | None = None
118
+ ) -> None:
119
+ super().__init__()
120
+
121
+ self._min_frame = 0
122
+
123
+ self.custom_mimetype: str | None = None
124
+
125
+ self.tile: list[_Tile] = []
126
+ """ A list of tile descriptors """
127
+
128
+ self.readonly = 1 # until we know better
129
+
130
+ self.decoderconfig: tuple[Any, ...] = ()
131
+ self.decodermaxblock = MAXBLOCK
132
+
133
+ if is_path(fp):
134
+ # filename
135
+ self.fp = open(fp, "rb")
136
+ self.filename = os.fspath(fp)
137
+ self._exclusive_fp = True
138
+ else:
139
+ # stream
140
+ self.fp = cast(IO[bytes], fp)
141
+ self.filename = filename if filename is not None else ""
142
+ # can be overridden
143
+ self._exclusive_fp = False
144
+
145
+ try:
146
+ try:
147
+ self._open()
148
+ except (
149
+ IndexError, # end of data
150
+ TypeError, # end of data (ord)
151
+ KeyError, # unsupported mode
152
+ EOFError, # got header but not the first frame
153
+ struct.error,
154
+ ) as v:
155
+ raise SyntaxError(v) from v
156
+
157
+ if not self.mode or self.size[0] <= 0 or self.size[1] <= 0:
158
+ msg = "not identified by this driver"
159
+ raise SyntaxError(msg)
160
+ except BaseException:
161
+ # close the file only if we have opened it this constructor
162
+ if self._exclusive_fp:
163
+ self.fp.close()
164
+ raise
165
+
166
+ def _open(self) -> None:
167
+ pass
168
+
169
+ def _close_fp(self):
170
+ if getattr(self, "_fp", False) and not isinstance(self._fp, DeferredError):
171
+ if self._fp != self.fp:
172
+ self._fp.close()
173
+ self._fp = DeferredError(ValueError("Operation on closed image"))
174
+ if self.fp:
175
+ self.fp.close()
176
+
177
+ def close(self) -> None:
178
+ """
179
+ Closes the file pointer, if possible.
180
+
181
+ This operation will destroy the image core and release its memory.
182
+ The image data will be unusable afterward.
183
+
184
+ This function is required to close images that have multiple frames or
185
+ have not had their file read and closed by the
186
+ :py:meth:`~PIL.Image.Image.load` method. See :ref:`file-handling` for
187
+ more information.
188
+ """
189
+ try:
190
+ self._close_fp()
191
+ self.fp = None
192
+ except Exception as msg:
193
+ logger.debug("Error closing: %s", msg)
194
+
195
+ super().close()
196
+
197
+ def get_child_images(self) -> list[ImageFile]:
198
+ child_images = []
199
+ exif = self.getexif()
200
+ ifds = []
201
+ if ExifTags.Base.SubIFDs in exif:
202
+ subifd_offsets = exif[ExifTags.Base.SubIFDs]
203
+ if subifd_offsets:
204
+ if not isinstance(subifd_offsets, tuple):
205
+ subifd_offsets = (subifd_offsets,)
206
+ for subifd_offset in subifd_offsets:
207
+ ifds.append((exif._get_ifd_dict(subifd_offset), subifd_offset))
208
+ ifd1 = exif.get_ifd(ExifTags.IFD.IFD1)
209
+ if ifd1 and ifd1.get(ExifTags.Base.JpegIFOffset):
210
+ assert exif._info is not None
211
+ ifds.append((ifd1, exif._info.next))
212
+
213
+ offset = None
214
+ for ifd, ifd_offset in ifds:
215
+ assert self.fp is not None
216
+ current_offset = self.fp.tell()
217
+ if offset is None:
218
+ offset = current_offset
219
+
220
+ fp = self.fp
221
+ if ifd is not None:
222
+ thumbnail_offset = ifd.get(ExifTags.Base.JpegIFOffset)
223
+ if thumbnail_offset is not None:
224
+ thumbnail_offset += getattr(self, "_exif_offset", 0)
225
+ self.fp.seek(thumbnail_offset)
226
+
227
+ length = ifd.get(ExifTags.Base.JpegIFByteCount)
228
+ assert isinstance(length, int)
229
+ data = self.fp.read(length)
230
+ fp = io.BytesIO(data)
231
+
232
+ with Image.open(fp) as im:
233
+ from . import TiffImagePlugin
234
+
235
+ if thumbnail_offset is None and isinstance(
236
+ im, TiffImagePlugin.TiffImageFile
237
+ ):
238
+ im._frame_pos = [ifd_offset]
239
+ im._seek(0)
240
+ im.load()
241
+ child_images.append(im)
242
+
243
+ if offset is not None:
244
+ assert self.fp is not None
245
+ self.fp.seek(offset)
246
+ return child_images
247
+
248
+ def get_format_mimetype(self) -> str | None:
249
+ if self.custom_mimetype:
250
+ return self.custom_mimetype
251
+ if self.format is not None:
252
+ return Image.MIME.get(self.format.upper())
253
+ return None
254
+
255
+ def __getstate__(self) -> list[Any]:
256
+ return super().__getstate__() + [self.filename]
257
+
258
+ def __setstate__(self, state: list[Any]) -> None:
259
+ self.tile = []
260
+ if len(state) > 5:
261
+ self.filename = state[5]
262
+ super().__setstate__(state)
263
+
264
+ def verify(self) -> None:
265
+ """Check file integrity"""
266
+
267
+ # raise exception if something's wrong. must be called
268
+ # directly after open, and closes file when finished.
269
+ if self._exclusive_fp:
270
+ self.fp.close()
271
+ self.fp = None
272
+
273
+ def load(self) -> Image.core.PixelAccess | None:
274
+ """Load image data based on tile list"""
275
+
276
+ if not self.tile and self._im is None:
277
+ msg = "cannot load this image"
278
+ raise OSError(msg)
279
+
280
+ pixel = Image.Image.load(self)
281
+ if not self.tile:
282
+ return pixel
283
+
284
+ self.map: mmap.mmap | None = None
285
+ use_mmap = self.filename and len(self.tile) == 1
286
+
287
+ readonly = 0
288
+
289
+ # look for read/seek overrides
290
+ if hasattr(self, "load_read"):
291
+ read = self.load_read
292
+ # don't use mmap if there are custom read/seek functions
293
+ use_mmap = False
294
+ else:
295
+ read = self.fp.read
296
+
297
+ if hasattr(self, "load_seek"):
298
+ seek = self.load_seek
299
+ use_mmap = False
300
+ else:
301
+ seek = self.fp.seek
302
+
303
+ if use_mmap:
304
+ # try memory mapping
305
+ decoder_name, extents, offset, args = self.tile[0]
306
+ if isinstance(args, str):
307
+ args = (args, 0, 1)
308
+ if (
309
+ decoder_name == "raw"
310
+ and isinstance(args, tuple)
311
+ and len(args) >= 3
312
+ and args[0] == self.mode
313
+ and args[0] in Image._MAPMODES
314
+ ):
315
+ try:
316
+ # use mmap, if possible
317
+ import mmap
318
+
319
+ with open(self.filename) as fp:
320
+ self.map = mmap.mmap(fp.fileno(), 0, access=mmap.ACCESS_READ)
321
+ if offset + self.size[1] * args[1] > self.map.size():
322
+ msg = "buffer is not large enough"
323
+ raise OSError(msg)
324
+ self.im = Image.core.map_buffer(
325
+ self.map, self.size, decoder_name, offset, args
326
+ )
327
+ readonly = 1
328
+ # After trashing self.im,
329
+ # we might need to reload the palette data.
330
+ if self.palette:
331
+ self.palette.dirty = 1
332
+ except (AttributeError, OSError, ImportError):
333
+ self.map = None
334
+
335
+ self.load_prepare()
336
+ err_code = -3 # initialize to unknown error
337
+ if not self.map:
338
+ # sort tiles in file order
339
+ self.tile.sort(key=_tilesort)
340
+
341
+ # FIXME: This is a hack to handle TIFF's JpegTables tag.
342
+ prefix = getattr(self, "tile_prefix", b"")
343
+
344
+ # Remove consecutive duplicates that only differ by their offset
345
+ self.tile = [
346
+ list(tiles)[-1]
347
+ for _, tiles in itertools.groupby(
348
+ self.tile, lambda tile: (tile[0], tile[1], tile[3])
349
+ )
350
+ ]
351
+ for i, (decoder_name, extents, offset, args) in enumerate(self.tile):
352
+ seek(offset)
353
+ decoder = Image._getdecoder(
354
+ self.mode, decoder_name, args, self.decoderconfig
355
+ )
356
+ try:
357
+ decoder.setimage(self.im, extents)
358
+ if decoder.pulls_fd:
359
+ decoder.setfd(self.fp)
360
+ err_code = decoder.decode(b"")[1]
361
+ else:
362
+ b = prefix
363
+ while True:
364
+ read_bytes = self.decodermaxblock
365
+ if i + 1 < len(self.tile):
366
+ next_offset = self.tile[i + 1].offset
367
+ if next_offset > offset:
368
+ read_bytes = next_offset - offset
369
+ try:
370
+ s = read(read_bytes)
371
+ except (IndexError, struct.error) as e:
372
+ # truncated png/gif
373
+ if LOAD_TRUNCATED_IMAGES:
374
+ break
375
+ else:
376
+ msg = "image file is truncated"
377
+ raise OSError(msg) from e
378
+
379
+ if not s: # truncated jpeg
380
+ if LOAD_TRUNCATED_IMAGES:
381
+ break
382
+ else:
383
+ msg = (
384
+ "image file is truncated "
385
+ f"({len(b)} bytes not processed)"
386
+ )
387
+ raise OSError(msg)
388
+
389
+ b = b + s
390
+ n, err_code = decoder.decode(b)
391
+ if n < 0:
392
+ break
393
+ b = b[n:]
394
+ finally:
395
+ # Need to cleanup here to prevent leaks
396
+ decoder.cleanup()
397
+
398
+ self.tile = []
399
+ self.readonly = readonly
400
+
401
+ self.load_end()
402
+
403
+ if self._exclusive_fp and self._close_exclusive_fp_after_loading:
404
+ self.fp.close()
405
+ self.fp = None
406
+
407
+ if not self.map and not LOAD_TRUNCATED_IMAGES and err_code < 0:
408
+ # still raised if decoder fails to return anything
409
+ raise _get_oserror(err_code, encoder=False)
410
+
411
+ return Image.Image.load(self)
412
+
413
+ def load_prepare(self) -> None:
414
+ # create image memory if necessary
415
+ if self._im is None:
416
+ self.im = Image.core.new(self.mode, self.size)
417
+ # create palette (optional)
418
+ if self.mode == "P":
419
+ Image.Image.load(self)
420
+
421
+ def load_end(self) -> None:
422
+ # may be overridden
423
+ pass
424
+
425
+ # may be defined for contained formats
426
+ # def load_seek(self, pos: int) -> None:
427
+ # pass
428
+
429
+ # may be defined for blocked formats (e.g. PNG)
430
+ # def load_read(self, read_bytes: int) -> bytes:
431
+ # pass
432
+
433
+ def _seek_check(self, frame: int) -> bool:
434
+ if (
435
+ frame < self._min_frame
436
+ # Only check upper limit on frames if additional seek operations
437
+ # are not required to do so
438
+ or (
439
+ not (hasattr(self, "_n_frames") and self._n_frames is None)
440
+ and frame >= getattr(self, "n_frames") + self._min_frame
441
+ )
442
+ ):
443
+ msg = "attempt to seek outside sequence"
444
+ raise EOFError(msg)
445
+
446
+ return self.tell() != frame
447
+
448
+
449
+ class StubHandler(abc.ABC):
450
+ def open(self, im: StubImageFile) -> None:
451
+ pass
452
+
453
+ @abc.abstractmethod
454
+ def load(self, im: StubImageFile) -> Image.Image:
455
+ pass
456
+
457
+
458
+ class StubImageFile(ImageFile, metaclass=abc.ABCMeta):
459
+ """
460
+ Base class for stub image loaders.
461
+
462
+ A stub loader is an image loader that can identify files of a
463
+ certain format, but relies on external code to load the file.
464
+ """
465
+
466
+ @abc.abstractmethod
467
+ def _open(self) -> None:
468
+ pass
469
+
470
+ def load(self) -> Image.core.PixelAccess | None:
471
+ loader = self._load()
472
+ if loader is None:
473
+ msg = f"cannot find loader for this {self.format} file"
474
+ raise OSError(msg)
475
+ image = loader.load(self)
476
+ assert image is not None
477
+ # become the other object (!)
478
+ self.__class__ = image.__class__ # type: ignore[assignment]
479
+ self.__dict__ = image.__dict__
480
+ return image.load()
481
+
482
+ @abc.abstractmethod
483
+ def _load(self) -> StubHandler | None:
484
+ """(Hook) Find actual image loader."""
485
+ pass
486
+
487
+
488
+ class Parser:
489
+ """
490
+ Incremental image parser. This class implements the standard
491
+ feed/close consumer interface.
492
+ """
493
+
494
+ incremental = None
495
+ image: Image.Image | None = None
496
+ data: bytes | None = None
497
+ decoder: Image.core.ImagingDecoder | PyDecoder | None = None
498
+ offset = 0
499
+ finished = 0
500
+
501
+ def reset(self) -> None:
502
+ """
503
+ (Consumer) Reset the parser. Note that you can only call this
504
+ method immediately after you've created a parser; parser
505
+ instances cannot be reused.
506
+ """
507
+ assert self.data is None, "cannot reuse parsers"
508
+
509
+ def feed(self, data: bytes) -> None:
510
+ """
511
+ (Consumer) Feed data to the parser.
512
+
513
+ :param data: A string buffer.
514
+ :exception OSError: If the parser failed to parse the image file.
515
+ """
516
+ # collect data
517
+
518
+ if self.finished:
519
+ return
520
+
521
+ if self.data is None:
522
+ self.data = data
523
+ else:
524
+ self.data = self.data + data
525
+
526
+ # parse what we have
527
+ if self.decoder:
528
+ if self.offset > 0:
529
+ # skip header
530
+ skip = min(len(self.data), self.offset)
531
+ self.data = self.data[skip:]
532
+ self.offset = self.offset - skip
533
+ if self.offset > 0 or not self.data:
534
+ return
535
+
536
+ n, e = self.decoder.decode(self.data)
537
+
538
+ if n < 0:
539
+ # end of stream
540
+ self.data = None
541
+ self.finished = 1
542
+ if e < 0:
543
+ # decoding error
544
+ self.image = None
545
+ raise _get_oserror(e, encoder=False)
546
+ else:
547
+ # end of image
548
+ return
549
+ self.data = self.data[n:]
550
+
551
+ elif self.image:
552
+ # if we end up here with no decoder, this file cannot
553
+ # be incrementally parsed. wait until we've gotten all
554
+ # available data
555
+ pass
556
+
557
+ else:
558
+ # attempt to open this file
559
+ try:
560
+ with io.BytesIO(self.data) as fp:
561
+ im = Image.open(fp)
562
+ except OSError:
563
+ pass # not enough data
564
+ else:
565
+ flag = hasattr(im, "load_seek") or hasattr(im, "load_read")
566
+ if flag or len(im.tile) != 1:
567
+ # custom load code, or multiple tiles
568
+ self.decode = None
569
+ else:
570
+ # initialize decoder
571
+ im.load_prepare()
572
+ d, e, o, a = im.tile[0]
573
+ im.tile = []
574
+ self.decoder = Image._getdecoder(im.mode, d, a, im.decoderconfig)
575
+ self.decoder.setimage(im.im, e)
576
+
577
+ # calculate decoder offset
578
+ self.offset = o
579
+ if self.offset <= len(self.data):
580
+ self.data = self.data[self.offset :]
581
+ self.offset = 0
582
+
583
+ self.image = im
584
+
585
+ def __enter__(self) -> Parser:
586
+ return self
587
+
588
+ def __exit__(self, *args: object) -> None:
589
+ self.close()
590
+
591
+ def close(self) -> Image.Image:
592
+ """
593
+ (Consumer) Close the stream.
594
+
595
+ :returns: An image object.
596
+ :exception OSError: If the parser failed to parse the image file either
597
+ because it cannot be identified or cannot be
598
+ decoded.
599
+ """
600
+ # finish decoding
601
+ if self.decoder:
602
+ # get rid of what's left in the buffers
603
+ self.feed(b"")
604
+ self.data = self.decoder = None
605
+ if not self.finished:
606
+ msg = "image was incomplete"
607
+ raise OSError(msg)
608
+ if not self.image:
609
+ msg = "cannot parse this image"
610
+ raise OSError(msg)
611
+ if self.data:
612
+ # incremental parsing not possible; reopen the file
613
+ # not that we have all data
614
+ with io.BytesIO(self.data) as fp:
615
+ try:
616
+ self.image = Image.open(fp)
617
+ finally:
618
+ self.image.load()
619
+ return self.image
620
+
621
+
622
+ # --------------------------------------------------------------------
623
+
624
+
625
+ def _save(im: Image.Image, fp: IO[bytes], tile: list[_Tile], bufsize: int = 0) -> None:
626
+ """Helper to save image based on tile list
627
+
628
+ :param im: Image object.
629
+ :param fp: File object.
630
+ :param tile: Tile list.
631
+ :param bufsize: Optional buffer size
632
+ """
633
+
634
+ im.load()
635
+ if not hasattr(im, "encoderconfig"):
636
+ im.encoderconfig = ()
637
+ tile.sort(key=_tilesort)
638
+ # FIXME: make MAXBLOCK a configuration parameter
639
+ # It would be great if we could have the encoder specify what it needs
640
+ # But, it would need at least the image size in most cases. RawEncode is
641
+ # a tricky case.
642
+ bufsize = max(MAXBLOCK, bufsize, im.size[0] * 4) # see RawEncode.c
643
+ try:
644
+ fh = fp.fileno()
645
+ fp.flush()
646
+ _encode_tile(im, fp, tile, bufsize, fh)
647
+ except (AttributeError, io.UnsupportedOperation) as exc:
648
+ _encode_tile(im, fp, tile, bufsize, None, exc)
649
+ if hasattr(fp, "flush"):
650
+ fp.flush()
651
+
652
+
653
+ def _encode_tile(
654
+ im: Image.Image,
655
+ fp: IO[bytes],
656
+ tile: list[_Tile],
657
+ bufsize: int,
658
+ fh: int | None,
659
+ exc: BaseException | None = None,
660
+ ) -> None:
661
+ for encoder_name, extents, offset, args in tile:
662
+ if offset > 0:
663
+ fp.seek(offset)
664
+ encoder = Image._getencoder(im.mode, encoder_name, args, im.encoderconfig)
665
+ try:
666
+ encoder.setimage(im.im, extents)
667
+ if encoder.pushes_fd:
668
+ encoder.setfd(fp)
669
+ errcode = encoder.encode_to_pyfd()[1]
670
+ else:
671
+ if exc:
672
+ # compress to Python file-compatible object
673
+ while True:
674
+ errcode, data = encoder.encode(bufsize)[1:]
675
+ fp.write(data)
676
+ if errcode:
677
+ break
678
+ else:
679
+ # slight speedup: compress to real file object
680
+ assert fh is not None
681
+ errcode = encoder.encode_to_file(fh, bufsize)
682
+ if errcode < 0:
683
+ raise _get_oserror(errcode, encoder=True) from exc
684
+ finally:
685
+ encoder.cleanup()
686
+
687
+
688
+ def _safe_read(fp: IO[bytes], size: int) -> bytes:
689
+ """
690
+ Reads large blocks in a safe way. Unlike fp.read(n), this function
691
+ doesn't trust the user. If the requested size is larger than
692
+ SAFEBLOCK, the file is read block by block.
693
+
694
+ :param fp: File handle. Must implement a <b>read</b> method.
695
+ :param size: Number of bytes to read.
696
+ :returns: A string containing <i>size</i> bytes of data.
697
+
698
+ Raises an OSError if the file is truncated and the read cannot be completed
699
+
700
+ """
701
+ if size <= 0:
702
+ return b""
703
+ if size <= SAFEBLOCK:
704
+ data = fp.read(size)
705
+ if len(data) < size:
706
+ msg = "Truncated File Read"
707
+ raise OSError(msg)
708
+ return data
709
+ blocks: list[bytes] = []
710
+ remaining_size = size
711
+ while remaining_size > 0:
712
+ block = fp.read(min(remaining_size, SAFEBLOCK))
713
+ if not block:
714
+ break
715
+ blocks.append(block)
716
+ remaining_size -= len(block)
717
+ if sum(len(block) for block in blocks) < size:
718
+ msg = "Truncated File Read"
719
+ raise OSError(msg)
720
+ return b"".join(blocks)
721
+
722
+
723
+ class PyCodecState:
724
+ def __init__(self) -> None:
725
+ self.xsize = 0
726
+ self.ysize = 0
727
+ self.xoff = 0
728
+ self.yoff = 0
729
+
730
+ def extents(self) -> tuple[int, int, int, int]:
731
+ return self.xoff, self.yoff, self.xoff + self.xsize, self.yoff + self.ysize
732
+
733
+
734
+ class PyCodec:
735
+ fd: IO[bytes] | None
736
+
737
+ def __init__(self, mode: str, *args: Any) -> None:
738
+ self.im: Image.core.ImagingCore | None = None
739
+ self.state = PyCodecState()
740
+ self.fd = None
741
+ self.mode = mode
742
+ self.init(args)
743
+
744
+ def init(self, args: tuple[Any, ...]) -> None:
745
+ """
746
+ Override to perform codec specific initialization
747
+
748
+ :param args: Tuple of arg items from the tile entry
749
+ :returns: None
750
+ """
751
+ self.args = args
752
+
753
+ def cleanup(self) -> None:
754
+ """
755
+ Override to perform codec specific cleanup
756
+
757
+ :returns: None
758
+ """
759
+ pass
760
+
761
+ def setfd(self, fd: IO[bytes]) -> None:
762
+ """
763
+ Called from ImageFile to set the Python file-like object
764
+
765
+ :param fd: A Python file-like object
766
+ :returns: None
767
+ """
768
+ self.fd = fd
769
+
770
+ def setimage(
771
+ self,
772
+ im: Image.core.ImagingCore,
773
+ extents: tuple[int, int, int, int] | None = None,
774
+ ) -> None:
775
+ """
776
+ Called from ImageFile to set the core output image for the codec
777
+
778
+ :param im: A core image object
779
+ :param extents: a 4 tuple of (x0, y0, x1, y1) defining the rectangle
780
+ for this tile
781
+ :returns: None
782
+ """
783
+
784
+ # following c code
785
+ self.im = im
786
+
787
+ if extents:
788
+ (x0, y0, x1, y1) = extents
789
+ else:
790
+ (x0, y0, x1, y1) = (0, 0, 0, 0)
791
+
792
+ if x0 == 0 and x1 == 0:
793
+ self.state.xsize, self.state.ysize = self.im.size
794
+ else:
795
+ self.state.xoff = x0
796
+ self.state.yoff = y0
797
+ self.state.xsize = x1 - x0
798
+ self.state.ysize = y1 - y0
799
+
800
+ if self.state.xsize <= 0 or self.state.ysize <= 0:
801
+ msg = "Size cannot be negative"
802
+ raise ValueError(msg)
803
+
804
+ if (
805
+ self.state.xsize + self.state.xoff > self.im.size[0]
806
+ or self.state.ysize + self.state.yoff > self.im.size[1]
807
+ ):
808
+ msg = "Tile cannot extend outside image"
809
+ raise ValueError(msg)
810
+
811
+
812
+ class PyDecoder(PyCodec):
813
+ """
814
+ Python implementation of a format decoder. Override this class and
815
+ add the decoding logic in the :meth:`decode` method.
816
+
817
+ See :ref:`Writing Your Own File Codec in Python<file-codecs-py>`
818
+ """
819
+
820
+ _pulls_fd = False
821
+
822
+ @property
823
+ def pulls_fd(self) -> bool:
824
+ return self._pulls_fd
825
+
826
+ def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:
827
+ """
828
+ Override to perform the decoding process.
829
+
830
+ :param buffer: A bytes object with the data to be decoded.
831
+ :returns: A tuple of ``(bytes consumed, errcode)``.
832
+ If finished with decoding return -1 for the bytes consumed.
833
+ Err codes are from :data:`.ImageFile.ERRORS`.
834
+ """
835
+ msg = "unavailable in base decoder"
836
+ raise NotImplementedError(msg)
837
+
838
+ def set_as_raw(
839
+ self, data: bytes, rawmode: str | None = None, extra: tuple[Any, ...] = ()
840
+ ) -> None:
841
+ """
842
+ Convenience method to set the internal image from a stream of raw data
843
+
844
+ :param data: Bytes to be set
845
+ :param rawmode: The rawmode to be used for the decoder.
846
+ If not specified, it will default to the mode of the image
847
+ :param extra: Extra arguments for the decoder.
848
+ :returns: None
849
+ """
850
+
851
+ if not rawmode:
852
+ rawmode = self.mode
853
+ d = Image._getdecoder(self.mode, "raw", rawmode, extra)
854
+ assert self.im is not None
855
+ d.setimage(self.im, self.state.extents())
856
+ s = d.decode(data)
857
+
858
+ if s[0] >= 0:
859
+ msg = "not enough image data"
860
+ raise ValueError(msg)
861
+ if s[1] != 0:
862
+ msg = "cannot decode image data"
863
+ raise ValueError(msg)
864
+
865
+
866
+ class PyEncoder(PyCodec):
867
+ """
868
+ Python implementation of a format encoder. Override this class and
869
+ add the decoding logic in the :meth:`encode` method.
870
+
871
+ See :ref:`Writing Your Own File Codec in Python<file-codecs-py>`
872
+ """
873
+
874
+ _pushes_fd = False
875
+
876
+ @property
877
+ def pushes_fd(self) -> bool:
878
+ return self._pushes_fd
879
+
880
+ def encode(self, bufsize: int) -> tuple[int, int, bytes]:
881
+ """
882
+ Override to perform the encoding process.
883
+
884
+ :param bufsize: Buffer size.
885
+ :returns: A tuple of ``(bytes encoded, errcode, bytes)``.
886
+ If finished with encoding return 1 for the error code.
887
+ Err codes are from :data:`.ImageFile.ERRORS`.
888
+ """
889
+ msg = "unavailable in base encoder"
890
+ raise NotImplementedError(msg)
891
+
892
+ def encode_to_pyfd(self) -> tuple[int, int]:
893
+ """
894
+ If ``pushes_fd`` is ``True``, then this method will be used,
895
+ and ``encode()`` will only be called once.
896
+
897
+ :returns: A tuple of ``(bytes consumed, errcode)``.
898
+ Err codes are from :data:`.ImageFile.ERRORS`.
899
+ """
900
+ if not self.pushes_fd:
901
+ return 0, -8 # bad configuration
902
+ bytes_consumed, errcode, data = self.encode(0)
903
+ if data:
904
+ assert self.fd is not None
905
+ self.fd.write(data)
906
+ return bytes_consumed, errcode
907
+
908
+ def encode_to_file(self, fh: int, bufsize: int) -> int:
909
+ """
910
+ :param fh: File handle.
911
+ :param bufsize: Buffer size.
912
+
913
+ :returns: If finished successfully, return 0.
914
+ Otherwise, return an error code. Err codes are from
915
+ :data:`.ImageFile.ERRORS`.
916
+ """
917
+ errcode = 0
918
+ while errcode == 0:
919
+ status, errcode, buf = self.encode(bufsize)
920
+ if status > 0:
921
+ os.write(fh, buf[status:])
922
+ return errcode
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/ImageFilter.py ADDED
@@ -0,0 +1,604 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 Any, Callable, cast
24
+
25
+ TYPE_CHECKING = False
26
+ if TYPE_CHECKING:
27
+ from . import _imaging
28
+ from ._typing import NumpyArray
29
+
30
+
31
+ class Filter(abc.ABC):
32
+ @abc.abstractmethod
33
+ def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
34
+ pass
35
+
36
+
37
+ class MultibandFilter(Filter):
38
+ pass
39
+
40
+
41
+ class BuiltinFilter(MultibandFilter):
42
+ filterargs: tuple[Any, ...]
43
+
44
+ def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
45
+ if image.mode == "P":
46
+ msg = "cannot filter palette images"
47
+ raise ValueError(msg)
48
+ return image.filter(*self.filterargs)
49
+
50
+
51
+ class Kernel(BuiltinFilter):
52
+ """
53
+ Create a convolution kernel. This only supports 3x3 and 5x5 integer and floating
54
+ point kernels.
55
+
56
+ Kernels can only be applied to "L" and "RGB" images.
57
+
58
+ :param size: Kernel size, given as (width, height). This must be (3,3) or (5,5).
59
+ :param kernel: A sequence containing kernel weights. The kernel will be flipped
60
+ vertically before being applied to the image.
61
+ :param scale: Scale factor. If given, the result for each pixel is divided by this
62
+ value. The default is the sum of the kernel weights.
63
+ :param offset: Offset. If given, this value is added to the result, after it has
64
+ been divided by the scale factor.
65
+ """
66
+
67
+ name = "Kernel"
68
+
69
+ def __init__(
70
+ self,
71
+ size: tuple[int, int],
72
+ kernel: Sequence[float],
73
+ scale: float | None = None,
74
+ offset: float = 0,
75
+ ) -> None:
76
+ if scale is None:
77
+ # default scale is sum of kernel
78
+ scale = functools.reduce(lambda a, b: a + b, kernel)
79
+ if size[0] * size[1] != len(kernel):
80
+ msg = "not enough coefficients in kernel"
81
+ raise ValueError(msg)
82
+ self.filterargs = size, scale, offset, kernel
83
+
84
+
85
+ class RankFilter(Filter):
86
+ """
87
+ Create a rank filter. The rank filter sorts all pixels in
88
+ a window of the given size, and returns the ``rank``'th value.
89
+
90
+ :param size: The kernel size, in pixels.
91
+ :param rank: What pixel value to pick. Use 0 for a min filter,
92
+ ``size * size / 2`` for a median filter, ``size * size - 1``
93
+ for a max filter, etc.
94
+ """
95
+
96
+ name = "Rank"
97
+
98
+ def __init__(self, size: int, rank: int) -> None:
99
+ self.size = size
100
+ self.rank = rank
101
+
102
+ def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
103
+ if image.mode == "P":
104
+ msg = "cannot filter palette images"
105
+ raise ValueError(msg)
106
+ image = image.expand(self.size // 2, self.size // 2)
107
+ return image.rankfilter(self.size, self.rank)
108
+
109
+
110
+ class MedianFilter(RankFilter):
111
+ """
112
+ Create a median filter. Picks the median pixel value in a window with the
113
+ given size.
114
+
115
+ :param size: The kernel size, in pixels.
116
+ """
117
+
118
+ name = "Median"
119
+
120
+ def __init__(self, size: int = 3) -> None:
121
+ self.size = size
122
+ self.rank = size * size // 2
123
+
124
+
125
+ class MinFilter(RankFilter):
126
+ """
127
+ Create a min filter. Picks the lowest pixel value in a window with the
128
+ given size.
129
+
130
+ :param size: The kernel size, in pixels.
131
+ """
132
+
133
+ name = "Min"
134
+
135
+ def __init__(self, size: int = 3) -> None:
136
+ self.size = size
137
+ self.rank = 0
138
+
139
+
140
+ class MaxFilter(RankFilter):
141
+ """
142
+ Create a max filter. Picks the largest pixel value in a window with the
143
+ given size.
144
+
145
+ :param size: The kernel size, in pixels.
146
+ """
147
+
148
+ name = "Max"
149
+
150
+ def __init__(self, size: int = 3) -> None:
151
+ self.size = size
152
+ self.rank = size * size - 1
153
+
154
+
155
+ class ModeFilter(Filter):
156
+ """
157
+ Create a mode filter. Picks the most frequent pixel value in a box with the
158
+ given size. Pixel values that occur only once or twice are ignored; if no
159
+ pixel value occurs more than twice, the original pixel value is preserved.
160
+
161
+ :param size: The kernel size, in pixels.
162
+ """
163
+
164
+ name = "Mode"
165
+
166
+ def __init__(self, size: int = 3) -> None:
167
+ self.size = size
168
+
169
+ def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
170
+ return image.modefilter(self.size)
171
+
172
+
173
+ class GaussianBlur(MultibandFilter):
174
+ """Blurs the image with a sequence of extended box filters, which
175
+ approximates a Gaussian kernel. For details on accuracy see
176
+ <https://www.mia.uni-saarland.de/Publications/gwosdek-ssvm11.pdf>
177
+
178
+ :param radius: Standard deviation of the Gaussian kernel. Either a sequence of two
179
+ numbers for x and y, or a single number for both.
180
+ """
181
+
182
+ name = "GaussianBlur"
183
+
184
+ def __init__(self, radius: float | Sequence[float] = 2) -> None:
185
+ self.radius = radius
186
+
187
+ def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
188
+ xy = self.radius
189
+ if isinstance(xy, (int, float)):
190
+ xy = (xy, xy)
191
+ if xy == (0, 0):
192
+ return image.copy()
193
+ return image.gaussian_blur(xy)
194
+
195
+
196
+ class BoxBlur(MultibandFilter):
197
+ """Blurs the image by setting each pixel to the average value of the pixels
198
+ in a square box extending radius pixels in each direction.
199
+ Supports float radius of arbitrary size. Uses an optimized implementation
200
+ which runs in linear time relative to the size of the image
201
+ for any radius value.
202
+
203
+ :param radius: Size of the box in a direction. Either a sequence of two numbers for
204
+ x and y, or a single number for both.
205
+
206
+ Radius 0 does not blur, returns an identical image.
207
+ Radius 1 takes 1 pixel in each direction, i.e. 9 pixels in total.
208
+ """
209
+
210
+ name = "BoxBlur"
211
+
212
+ def __init__(self, radius: float | Sequence[float]) -> None:
213
+ xy = radius if isinstance(radius, (tuple, list)) else (radius, radius)
214
+ if xy[0] < 0 or xy[1] < 0:
215
+ msg = "radius must be >= 0"
216
+ raise ValueError(msg)
217
+ self.radius = radius
218
+
219
+ def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
220
+ xy = self.radius
221
+ if isinstance(xy, (int, float)):
222
+ xy = (xy, xy)
223
+ if xy == (0, 0):
224
+ return image.copy()
225
+ return image.box_blur(xy)
226
+
227
+
228
+ class UnsharpMask(MultibandFilter):
229
+ """Unsharp mask filter.
230
+
231
+ See Wikipedia's entry on `digital unsharp masking`_ for an explanation of
232
+ the parameters.
233
+
234
+ :param radius: Blur Radius
235
+ :param percent: Unsharp strength, in percent
236
+ :param threshold: Threshold controls the minimum brightness change that
237
+ will be sharpened
238
+
239
+ .. _digital unsharp masking: https://en.wikipedia.org/wiki/Unsharp_masking#Digital_unsharp_masking
240
+
241
+ """
242
+
243
+ name = "UnsharpMask"
244
+
245
+ def __init__(
246
+ self, radius: float = 2, percent: int = 150, threshold: int = 3
247
+ ) -> None:
248
+ self.radius = radius
249
+ self.percent = percent
250
+ self.threshold = threshold
251
+
252
+ def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
253
+ return image.unsharp_mask(self.radius, self.percent, self.threshold)
254
+
255
+
256
+ class BLUR(BuiltinFilter):
257
+ name = "Blur"
258
+ # fmt: off
259
+ filterargs = (5, 5), 16, 0, (
260
+ 1, 1, 1, 1, 1,
261
+ 1, 0, 0, 0, 1,
262
+ 1, 0, 0, 0, 1,
263
+ 1, 0, 0, 0, 1,
264
+ 1, 1, 1, 1, 1,
265
+ )
266
+ # fmt: on
267
+
268
+
269
+ class CONTOUR(BuiltinFilter):
270
+ name = "Contour"
271
+ # fmt: off
272
+ filterargs = (3, 3), 1, 255, (
273
+ -1, -1, -1,
274
+ -1, 8, -1,
275
+ -1, -1, -1,
276
+ )
277
+ # fmt: on
278
+
279
+
280
+ class DETAIL(BuiltinFilter):
281
+ name = "Detail"
282
+ # fmt: off
283
+ filterargs = (3, 3), 6, 0, (
284
+ 0, -1, 0,
285
+ -1, 10, -1,
286
+ 0, -1, 0,
287
+ )
288
+ # fmt: on
289
+
290
+
291
+ class EDGE_ENHANCE(BuiltinFilter):
292
+ name = "Edge-enhance"
293
+ # fmt: off
294
+ filterargs = (3, 3), 2, 0, (
295
+ -1, -1, -1,
296
+ -1, 10, -1,
297
+ -1, -1, -1,
298
+ )
299
+ # fmt: on
300
+
301
+
302
+ class EDGE_ENHANCE_MORE(BuiltinFilter):
303
+ name = "Edge-enhance More"
304
+ # fmt: off
305
+ filterargs = (3, 3), 1, 0, (
306
+ -1, -1, -1,
307
+ -1, 9, -1,
308
+ -1, -1, -1,
309
+ )
310
+ # fmt: on
311
+
312
+
313
+ class EMBOSS(BuiltinFilter):
314
+ name = "Emboss"
315
+ # fmt: off
316
+ filterargs = (3, 3), 1, 128, (
317
+ -1, 0, 0,
318
+ 0, 1, 0,
319
+ 0, 0, 0,
320
+ )
321
+ # fmt: on
322
+
323
+
324
+ class FIND_EDGES(BuiltinFilter):
325
+ name = "Find Edges"
326
+ # fmt: off
327
+ filterargs = (3, 3), 1, 0, (
328
+ -1, -1, -1,
329
+ -1, 8, -1,
330
+ -1, -1, -1,
331
+ )
332
+ # fmt: on
333
+
334
+
335
+ class SHARPEN(BuiltinFilter):
336
+ name = "Sharpen"
337
+ # fmt: off
338
+ filterargs = (3, 3), 16, 0, (
339
+ -2, -2, -2,
340
+ -2, 32, -2,
341
+ -2, -2, -2,
342
+ )
343
+ # fmt: on
344
+
345
+
346
+ class SMOOTH(BuiltinFilter):
347
+ name = "Smooth"
348
+ # fmt: off
349
+ filterargs = (3, 3), 13, 0, (
350
+ 1, 1, 1,
351
+ 1, 5, 1,
352
+ 1, 1, 1,
353
+ )
354
+ # fmt: on
355
+
356
+
357
+ class SMOOTH_MORE(BuiltinFilter):
358
+ name = "Smooth More"
359
+ # fmt: off
360
+ filterargs = (5, 5), 100, 0, (
361
+ 1, 1, 1, 1, 1,
362
+ 1, 5, 5, 5, 1,
363
+ 1, 5, 44, 5, 1,
364
+ 1, 5, 5, 5, 1,
365
+ 1, 1, 1, 1, 1,
366
+ )
367
+ # fmt: on
368
+
369
+
370
+ class Color3DLUT(MultibandFilter):
371
+ """Three-dimensional color lookup table.
372
+
373
+ Transforms 3-channel pixels using the values of the channels as coordinates
374
+ in the 3D lookup table and interpolating the nearest elements.
375
+
376
+ This method allows you to apply almost any color transformation
377
+ in constant time by using pre-calculated decimated tables.
378
+
379
+ .. versionadded:: 5.2.0
380
+
381
+ :param size: Size of the table. One int or tuple of (int, int, int).
382
+ Minimal size in any dimension is 2, maximum is 65.
383
+ :param table: Flat lookup table. A list of ``channels * size**3``
384
+ float elements or a list of ``size**3`` channels-sized
385
+ tuples with floats. Channels are changed first,
386
+ then first dimension, then second, then third.
387
+ Value 0.0 corresponds lowest value of output, 1.0 highest.
388
+ :param channels: Number of channels in the table. Could be 3 or 4.
389
+ Default is 3.
390
+ :param target_mode: A mode for the result image. Should have not less
391
+ than ``channels`` channels. Default is ``None``,
392
+ which means that mode wouldn't be changed.
393
+ """
394
+
395
+ name = "Color 3D LUT"
396
+
397
+ def __init__(
398
+ self,
399
+ size: int | tuple[int, int, int],
400
+ table: Sequence[float] | Sequence[Sequence[int]] | NumpyArray,
401
+ channels: int = 3,
402
+ target_mode: str | None = None,
403
+ **kwargs: bool,
404
+ ) -> None:
405
+ if channels not in (3, 4):
406
+ msg = "Only 3 or 4 output channels are supported"
407
+ raise ValueError(msg)
408
+ self.size = size = self._check_size(size)
409
+ self.channels = channels
410
+ self.mode = target_mode
411
+
412
+ # Hidden flag `_copy_table=False` could be used to avoid extra copying
413
+ # of the table if the table is specially made for the constructor.
414
+ copy_table = kwargs.get("_copy_table", True)
415
+ items = size[0] * size[1] * size[2]
416
+ wrong_size = False
417
+
418
+ numpy: ModuleType | None = None
419
+ if hasattr(table, "shape"):
420
+ try:
421
+ import numpy
422
+ except ImportError:
423
+ pass
424
+
425
+ if numpy and isinstance(table, numpy.ndarray):
426
+ numpy_table: NumpyArray = table
427
+ if copy_table:
428
+ numpy_table = numpy_table.copy()
429
+
430
+ if numpy_table.shape in [
431
+ (items * channels,),
432
+ (items, channels),
433
+ (size[2], size[1], size[0], channels),
434
+ ]:
435
+ table = numpy_table.reshape(items * channels)
436
+ else:
437
+ wrong_size = True
438
+
439
+ else:
440
+ if copy_table:
441
+ table = list(table)
442
+
443
+ # Convert to a flat list
444
+ if table and isinstance(table[0], (list, tuple)):
445
+ raw_table = cast(Sequence[Sequence[int]], table)
446
+ flat_table: list[int] = []
447
+ for pixel in raw_table:
448
+ if len(pixel) != channels:
449
+ msg = (
450
+ "The elements of the table should "
451
+ f"have a length of {channels}."
452
+ )
453
+ raise ValueError(msg)
454
+ flat_table.extend(pixel)
455
+ table = flat_table
456
+
457
+ if wrong_size or len(table) != items * channels:
458
+ msg = (
459
+ "The table should have either channels * size**3 float items "
460
+ "or size**3 items of channels-sized tuples with floats. "
461
+ f"Table should be: {channels}x{size[0]}x{size[1]}x{size[2]}. "
462
+ f"Actual length: {len(table)}"
463
+ )
464
+ raise ValueError(msg)
465
+ self.table = table
466
+
467
+ @staticmethod
468
+ def _check_size(size: Any) -> tuple[int, int, int]:
469
+ try:
470
+ _, _, _ = size
471
+ except ValueError as e:
472
+ msg = "Size should be either an integer or a tuple of three integers."
473
+ raise ValueError(msg) from e
474
+ except TypeError:
475
+ size = (size, size, size)
476
+ size = tuple(int(x) for x in size)
477
+ for size_1d in size:
478
+ if not 2 <= size_1d <= 65:
479
+ msg = "Size should be in [2, 65] range."
480
+ raise ValueError(msg)
481
+ return size
482
+
483
+ @classmethod
484
+ def generate(
485
+ cls,
486
+ size: int | tuple[int, int, int],
487
+ callback: Callable[[float, float, float], tuple[float, ...]],
488
+ channels: int = 3,
489
+ target_mode: str | None = None,
490
+ ) -> Color3DLUT:
491
+ """Generates new LUT using provided callback.
492
+
493
+ :param size: Size of the table. Passed to the constructor.
494
+ :param callback: Function with three parameters which correspond
495
+ three color channels. Will be called ``size**3``
496
+ times with values from 0.0 to 1.0 and should return
497
+ a tuple with ``channels`` elements.
498
+ :param channels: The number of channels which should return callback.
499
+ :param target_mode: Passed to the constructor of the resulting
500
+ lookup table.
501
+ """
502
+ size_1d, size_2d, size_3d = cls._check_size(size)
503
+ if channels not in (3, 4):
504
+ msg = "Only 3 or 4 output channels are supported"
505
+ raise ValueError(msg)
506
+
507
+ table: list[float] = [0] * (size_1d * size_2d * size_3d * channels)
508
+ idx_out = 0
509
+ for b in range(size_3d):
510
+ for g in range(size_2d):
511
+ for r in range(size_1d):
512
+ table[idx_out : idx_out + channels] = callback(
513
+ r / (size_1d - 1), g / (size_2d - 1), b / (size_3d - 1)
514
+ )
515
+ idx_out += channels
516
+
517
+ return cls(
518
+ (size_1d, size_2d, size_3d),
519
+ table,
520
+ channels=channels,
521
+ target_mode=target_mode,
522
+ _copy_table=False,
523
+ )
524
+
525
+ def transform(
526
+ self,
527
+ callback: Callable[..., tuple[float, ...]],
528
+ with_normals: bool = False,
529
+ channels: int | None = None,
530
+ target_mode: str | None = None,
531
+ ) -> Color3DLUT:
532
+ """Transforms the table values using provided callback and returns
533
+ a new LUT with altered values.
534
+
535
+ :param callback: A function which takes old lookup table values
536
+ and returns a new set of values. The number
537
+ of arguments which function should take is
538
+ ``self.channels`` or ``3 + self.channels``
539
+ if ``with_normals`` flag is set.
540
+ Should return a tuple of ``self.channels`` or
541
+ ``channels`` elements if it is set.
542
+ :param with_normals: If true, ``callback`` will be called with
543
+ coordinates in the color cube as the first
544
+ three arguments. Otherwise, ``callback``
545
+ will be called only with actual color values.
546
+ :param channels: The number of channels in the resulting lookup table.
547
+ :param target_mode: Passed to the constructor of the resulting
548
+ lookup table.
549
+ """
550
+ if channels not in (None, 3, 4):
551
+ msg = "Only 3 or 4 output channels are supported"
552
+ raise ValueError(msg)
553
+ ch_in = self.channels
554
+ ch_out = channels or ch_in
555
+ size_1d, size_2d, size_3d = self.size
556
+
557
+ table: list[float] = [0] * (size_1d * size_2d * size_3d * ch_out)
558
+ idx_in = 0
559
+ idx_out = 0
560
+ for b in range(size_3d):
561
+ for g in range(size_2d):
562
+ for r in range(size_1d):
563
+ values = self.table[idx_in : idx_in + ch_in]
564
+ if with_normals:
565
+ values = callback(
566
+ r / (size_1d - 1),
567
+ g / (size_2d - 1),
568
+ b / (size_3d - 1),
569
+ *values,
570
+ )
571
+ else:
572
+ values = callback(*values)
573
+ table[idx_out : idx_out + ch_out] = values
574
+ idx_in += ch_in
575
+ idx_out += ch_out
576
+
577
+ return type(self)(
578
+ self.size,
579
+ table,
580
+ channels=ch_out,
581
+ target_mode=target_mode or self.mode,
582
+ _copy_table=False,
583
+ )
584
+
585
+ def __repr__(self) -> str:
586
+ r = [
587
+ f"{self.__class__.__name__} from {self.table.__class__.__name__}",
588
+ "size={:d}x{:d}x{:d}".format(*self.size),
589
+ f"channels={self.channels:d}",
590
+ ]
591
+ if self.mode:
592
+ r.append(f"target_mode={self.mode}")
593
+ return "<{}>".format(" ".join(r))
594
+
595
+ def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
596
+ from . import Image
597
+
598
+ return image.color_lut_3d(
599
+ self.mode or image.mode,
600
+ Image.Resampling.BILINEAR,
601
+ self.channels,
602
+ self.size,
603
+ self.table,
604
+ )
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/ImageFont.py ADDED
@@ -0,0 +1,1339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # PIL raster font management
6
+ #
7
+ # History:
8
+ # 1996-08-07 fl created (experimental)
9
+ # 1997-08-25 fl minor adjustments to handle fonts from pilfont 0.3
10
+ # 1999-02-06 fl rewrote most font management stuff in C
11
+ # 1999-03-17 fl take pth files into account in load_path (from Richard Jones)
12
+ # 2001-02-17 fl added freetype support
13
+ # 2001-05-09 fl added TransposedFont wrapper class
14
+ # 2002-03-04 fl make sure we have a "L" or "1" font
15
+ # 2002-12-04 fl skip non-directory entries in the system path
16
+ # 2003-04-29 fl add embedded default font
17
+ # 2003-09-27 fl added support for truetype charmap encodings
18
+ #
19
+ # Todo:
20
+ # Adapt to PILFONT2 format (16-bit fonts, compressed, single file)
21
+ #
22
+ # Copyright (c) 1997-2003 by Secret Labs AB
23
+ # Copyright (c) 1996-2003 by Fredrik Lundh
24
+ #
25
+ # See the README file for information on usage and redistribution.
26
+ #
27
+
28
+ from __future__ import annotations
29
+
30
+ import base64
31
+ import os
32
+ import sys
33
+ import warnings
34
+ from enum import IntEnum
35
+ from io import BytesIO
36
+ from types import ModuleType
37
+ from typing import IO, Any, BinaryIO, TypedDict, cast
38
+
39
+ from . import Image, features
40
+ from ._typing import StrOrBytesPath
41
+ from ._util import DeferredError, is_path
42
+
43
+ TYPE_CHECKING = False
44
+ if TYPE_CHECKING:
45
+ from . import ImageFile
46
+ from ._imaging import ImagingFont
47
+ from ._imagingft import Font
48
+
49
+
50
+ class Axis(TypedDict):
51
+ minimum: int | None
52
+ default: int | None
53
+ maximum: int | None
54
+ name: bytes | None
55
+
56
+
57
+ class Layout(IntEnum):
58
+ BASIC = 0
59
+ RAQM = 1
60
+
61
+
62
+ MAX_STRING_LENGTH = 1_000_000
63
+
64
+
65
+ core: ModuleType | DeferredError
66
+ try:
67
+ from . import _imagingft as core
68
+ except ImportError as ex:
69
+ core = DeferredError.new(ex)
70
+
71
+
72
+ def _string_length_check(text: str | bytes | bytearray) -> None:
73
+ if MAX_STRING_LENGTH is not None and len(text) > MAX_STRING_LENGTH:
74
+ msg = "too many characters in string"
75
+ raise ValueError(msg)
76
+
77
+
78
+ # FIXME: add support for pilfont2 format (see FontFile.py)
79
+
80
+ # --------------------------------------------------------------------
81
+ # Font metrics format:
82
+ # "PILfont" LF
83
+ # fontdescriptor LF
84
+ # (optional) key=value... LF
85
+ # "DATA" LF
86
+ # binary data: 256*10*2 bytes (dx, dy, dstbox, srcbox)
87
+ #
88
+ # To place a character, cut out srcbox and paste at dstbox,
89
+ # relative to the character position. Then move the character
90
+ # position according to dx, dy.
91
+ # --------------------------------------------------------------------
92
+
93
+
94
+ class ImageFont:
95
+ """PIL font wrapper"""
96
+
97
+ font: ImagingFont
98
+
99
+ def _load_pilfont(self, filename: str) -> None:
100
+ with open(filename, "rb") as fp:
101
+ image: ImageFile.ImageFile | None = None
102
+ root = os.path.splitext(filename)[0]
103
+
104
+ for ext in (".png", ".gif", ".pbm"):
105
+ if image:
106
+ image.close()
107
+ try:
108
+ fullname = root + ext
109
+ image = Image.open(fullname)
110
+ except Exception:
111
+ pass
112
+ else:
113
+ if image and image.mode in ("1", "L"):
114
+ break
115
+ else:
116
+ if image:
117
+ image.close()
118
+
119
+ msg = f"cannot find glyph data file {root}.{{gif|pbm|png}}"
120
+ raise OSError(msg)
121
+
122
+ self.file = fullname
123
+
124
+ self._load_pilfont_data(fp, image)
125
+ image.close()
126
+
127
+ def _load_pilfont_data(self, file: IO[bytes], image: Image.Image) -> None:
128
+ # read PILfont header
129
+ if file.readline() != b"PILfont\n":
130
+ msg = "Not a PILfont file"
131
+ raise SyntaxError(msg)
132
+ file.readline().split(b";")
133
+ self.info = [] # FIXME: should be a dictionary
134
+ while True:
135
+ s = file.readline()
136
+ if not s or s == b"DATA\n":
137
+ break
138
+ self.info.append(s)
139
+
140
+ # read PILfont metrics
141
+ data = file.read(256 * 20)
142
+
143
+ # check image
144
+ if image.mode not in ("1", "L"):
145
+ msg = "invalid font image mode"
146
+ raise TypeError(msg)
147
+
148
+ image.load()
149
+
150
+ self.font = Image.core.font(image.im, data)
151
+
152
+ def getmask(
153
+ self, text: str | bytes, mode: str = "", *args: Any, **kwargs: Any
154
+ ) -> Image.core.ImagingCore:
155
+ """
156
+ Create a bitmap for the text.
157
+
158
+ If the font uses antialiasing, the bitmap should have mode ``L`` and use a
159
+ maximum value of 255. Otherwise, it should have mode ``1``.
160
+
161
+ :param text: Text to render.
162
+ :param mode: Used by some graphics drivers to indicate what mode the
163
+ driver prefers; if empty, the renderer may return either
164
+ mode. Note that the mode is always a string, to simplify
165
+ C-level implementations.
166
+
167
+ .. versionadded:: 1.1.5
168
+
169
+ :return: An internal PIL storage memory instance as defined by the
170
+ :py:mod:`PIL.Image.core` interface module.
171
+ """
172
+ _string_length_check(text)
173
+ Image._decompression_bomb_check(self.font.getsize(text))
174
+ return self.font.getmask(text, mode)
175
+
176
+ def getbbox(
177
+ self, text: str | bytes | bytearray, *args: Any, **kwargs: Any
178
+ ) -> tuple[int, int, int, int]:
179
+ """
180
+ Returns bounding box (in pixels) of given text.
181
+
182
+ .. versionadded:: 9.2.0
183
+
184
+ :param text: Text to render.
185
+
186
+ :return: ``(left, top, right, bottom)`` bounding box
187
+ """
188
+ _string_length_check(text)
189
+ width, height = self.font.getsize(text)
190
+ return 0, 0, width, height
191
+
192
+ def getlength(
193
+ self, text: str | bytes | bytearray, *args: Any, **kwargs: Any
194
+ ) -> int:
195
+ """
196
+ Returns length (in pixels) of given text.
197
+ This is the amount by which following text should be offset.
198
+
199
+ .. versionadded:: 9.2.0
200
+ """
201
+ _string_length_check(text)
202
+ width, height = self.font.getsize(text)
203
+ return width
204
+
205
+
206
+ ##
207
+ # Wrapper for FreeType fonts. Application code should use the
208
+ # <b>truetype</b> factory function to create font objects.
209
+
210
+
211
+ class FreeTypeFont:
212
+ """FreeType font wrapper (requires _imagingft service)"""
213
+
214
+ font: Font
215
+ font_bytes: bytes
216
+
217
+ def __init__(
218
+ self,
219
+ font: StrOrBytesPath | BinaryIO,
220
+ size: float = 10,
221
+ index: int = 0,
222
+ encoding: str = "",
223
+ layout_engine: Layout | None = None,
224
+ ) -> None:
225
+ # FIXME: use service provider instead
226
+
227
+ if isinstance(core, DeferredError):
228
+ raise core.ex
229
+
230
+ if size <= 0:
231
+ msg = f"font size must be greater than 0, not {size}"
232
+ raise ValueError(msg)
233
+
234
+ self.path = font
235
+ self.size = size
236
+ self.index = index
237
+ self.encoding = encoding
238
+
239
+ try:
240
+ from packaging.version import parse as parse_version
241
+ except ImportError:
242
+ pass
243
+ else:
244
+ if freetype_version := features.version_module("freetype2"):
245
+ if parse_version(freetype_version) < parse_version("2.9.1"):
246
+ warnings.warn(
247
+ "Support for FreeType 2.9.0 is deprecated and will be removed "
248
+ "in Pillow 12 (2025-10-15). Please upgrade to FreeType 2.9.1 "
249
+ "or newer, preferably FreeType 2.10.4 which fixes "
250
+ "CVE-2020-15999.",
251
+ DeprecationWarning,
252
+ )
253
+
254
+ if layout_engine not in (Layout.BASIC, Layout.RAQM):
255
+ layout_engine = Layout.BASIC
256
+ if core.HAVE_RAQM:
257
+ layout_engine = Layout.RAQM
258
+ elif layout_engine == Layout.RAQM and not core.HAVE_RAQM:
259
+ warnings.warn(
260
+ "Raqm layout was requested, but Raqm is not available. "
261
+ "Falling back to basic layout."
262
+ )
263
+ layout_engine = Layout.BASIC
264
+
265
+ self.layout_engine = layout_engine
266
+
267
+ def load_from_bytes(f: IO[bytes]) -> None:
268
+ self.font_bytes = f.read()
269
+ self.font = core.getfont(
270
+ "", size, index, encoding, self.font_bytes, layout_engine
271
+ )
272
+
273
+ if is_path(font):
274
+ font = os.fspath(font)
275
+ if sys.platform == "win32":
276
+ font_bytes_path = font if isinstance(font, bytes) else font.encode()
277
+ try:
278
+ font_bytes_path.decode("ascii")
279
+ except UnicodeDecodeError:
280
+ # FreeType cannot load fonts with non-ASCII characters on Windows
281
+ # So load it into memory first
282
+ with open(font, "rb") as f:
283
+ load_from_bytes(f)
284
+ return
285
+ self.font = core.getfont(
286
+ font, size, index, encoding, layout_engine=layout_engine
287
+ )
288
+ else:
289
+ load_from_bytes(cast(IO[bytes], font))
290
+
291
+ def __getstate__(self) -> list[Any]:
292
+ return [self.path, self.size, self.index, self.encoding, self.layout_engine]
293
+
294
+ def __setstate__(self, state: list[Any]) -> None:
295
+ path, size, index, encoding, layout_engine = state
296
+ FreeTypeFont.__init__(self, path, size, index, encoding, layout_engine)
297
+
298
+ def getname(self) -> tuple[str | None, str | None]:
299
+ """
300
+ :return: A tuple of the font family (e.g. Helvetica) and the font style
301
+ (e.g. Bold)
302
+ """
303
+ return self.font.family, self.font.style
304
+
305
+ def getmetrics(self) -> tuple[int, int]:
306
+ """
307
+ :return: A tuple of the font ascent (the distance from the baseline to
308
+ the highest outline point) and descent (the distance from the
309
+ baseline to the lowest outline point, a negative value)
310
+ """
311
+ return self.font.ascent, self.font.descent
312
+
313
+ def getlength(
314
+ self,
315
+ text: str | bytes,
316
+ mode: str = "",
317
+ direction: str | None = None,
318
+ features: list[str] | None = None,
319
+ language: str | None = None,
320
+ ) -> float:
321
+ """
322
+ Returns length (in pixels with 1/64 precision) of given text when rendered
323
+ in font with provided direction, features, and language.
324
+
325
+ This is the amount by which following text should be offset.
326
+ Text bounding box may extend past the length in some fonts,
327
+ e.g. when using italics or accents.
328
+
329
+ The result is returned as a float; it is a whole number if using basic layout.
330
+
331
+ Note that the sum of two lengths may not equal the length of a concatenated
332
+ string due to kerning. If you need to adjust for kerning, include the following
333
+ character and subtract its length.
334
+
335
+ For example, instead of ::
336
+
337
+ hello = font.getlength("Hello")
338
+ world = font.getlength("World")
339
+ hello_world = hello + world # not adjusted for kerning
340
+ assert hello_world == font.getlength("HelloWorld") # may fail
341
+
342
+ use ::
343
+
344
+ hello = font.getlength("HelloW") - font.getlength("W") # adjusted for kerning
345
+ world = font.getlength("World")
346
+ hello_world = hello + world # adjusted for kerning
347
+ assert hello_world == font.getlength("HelloWorld") # True
348
+
349
+ or disable kerning with (requires libraqm) ::
350
+
351
+ hello = draw.textlength("Hello", font, features=["-kern"])
352
+ world = draw.textlength("World", font, features=["-kern"])
353
+ hello_world = hello + world # kerning is disabled, no need to adjust
354
+ assert hello_world == draw.textlength("HelloWorld", font, features=["-kern"])
355
+
356
+ .. versionadded:: 8.0.0
357
+
358
+ :param text: Text to measure.
359
+ :param mode: Used by some graphics drivers to indicate what mode the
360
+ driver prefers; if empty, the renderer may return either
361
+ mode. Note that the mode is always a string, to simplify
362
+ C-level implementations.
363
+
364
+ :param direction: Direction of the text. It can be 'rtl' (right to
365
+ left), 'ltr' (left to right) or 'ttb' (top to bottom).
366
+ Requires libraqm.
367
+
368
+ :param features: A list of OpenType font features to be used during text
369
+ layout. This is usually used to turn on optional
370
+ font features that are not enabled by default,
371
+ for example 'dlig' or 'ss01', but can be also
372
+ used to turn off default font features for
373
+ example '-liga' to disable ligatures or '-kern'
374
+ to disable kerning. To get all supported
375
+ features, see
376
+ https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist
377
+ Requires libraqm.
378
+
379
+ :param language: Language of the text. Different languages may use
380
+ different glyph shapes or ligatures. This parameter tells
381
+ the font which language the text is in, and to apply the
382
+ correct substitutions as appropriate, if available.
383
+ It should be a `BCP 47 language code
384
+ <https://www.w3.org/International/articles/language-tags/>`_
385
+ Requires libraqm.
386
+
387
+ :return: Either width for horizontal text, or height for vertical text.
388
+ """
389
+ _string_length_check(text)
390
+ return self.font.getlength(text, mode, direction, features, language) / 64
391
+
392
+ def getbbox(
393
+ self,
394
+ text: str | bytes,
395
+ mode: str = "",
396
+ direction: str | None = None,
397
+ features: list[str] | None = None,
398
+ language: str | None = None,
399
+ stroke_width: float = 0,
400
+ anchor: str | None = None,
401
+ ) -> tuple[float, float, float, float]:
402
+ """
403
+ Returns bounding box (in pixels) of given text relative to given anchor
404
+ when rendered in font with provided direction, features, and language.
405
+
406
+ Use :py:meth:`getlength()` to get the offset of following text with
407
+ 1/64 pixel precision. The bounding box includes extra margins for
408
+ some fonts, e.g. italics or accents.
409
+
410
+ .. versionadded:: 8.0.0
411
+
412
+ :param text: Text to render.
413
+ :param mode: Used by some graphics drivers to indicate what mode the
414
+ driver prefers; if empty, the renderer may return either
415
+ mode. Note that the mode is always a string, to simplify
416
+ C-level implementations.
417
+
418
+ :param direction: Direction of the text. It can be 'rtl' (right to
419
+ left), 'ltr' (left to right) or 'ttb' (top to bottom).
420
+ Requires libraqm.
421
+
422
+ :param features: A list of OpenType font features to be used during text
423
+ layout. This is usually used to turn on optional
424
+ font features that are not enabled by default,
425
+ for example 'dlig' or 'ss01', but can be also
426
+ used to turn off default font features for
427
+ example '-liga' to disable ligatures or '-kern'
428
+ to disable kerning. To get all supported
429
+ features, see
430
+ https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist
431
+ Requires libraqm.
432
+
433
+ :param language: Language of the text. Different languages may use
434
+ different glyph shapes or ligatures. This parameter tells
435
+ the font which language the text is in, and to apply the
436
+ correct substitutions as appropriate, if available.
437
+ It should be a `BCP 47 language code
438
+ <https://www.w3.org/International/articles/language-tags/>`_
439
+ Requires libraqm.
440
+
441
+ :param stroke_width: The width of the text stroke.
442
+
443
+ :param anchor: The text anchor alignment. Determines the relative location of
444
+ the anchor to the text. The default alignment is top left,
445
+ specifically ``la`` for horizontal text and ``lt`` for
446
+ vertical text. See :ref:`text-anchors` for details.
447
+
448
+ :return: ``(left, top, right, bottom)`` bounding box
449
+ """
450
+ _string_length_check(text)
451
+ size, offset = self.font.getsize(
452
+ text, mode, direction, features, language, anchor
453
+ )
454
+ left, top = offset[0] - stroke_width, offset[1] - stroke_width
455
+ width, height = size[0] + 2 * stroke_width, size[1] + 2 * stroke_width
456
+ return left, top, left + width, top + height
457
+
458
+ def getmask(
459
+ self,
460
+ text: str | bytes,
461
+ mode: str = "",
462
+ direction: str | None = None,
463
+ features: list[str] | None = None,
464
+ language: str | None = None,
465
+ stroke_width: float = 0,
466
+ anchor: str | None = None,
467
+ ink: int = 0,
468
+ start: tuple[float, float] | None = None,
469
+ ) -> Image.core.ImagingCore:
470
+ """
471
+ Create a bitmap for the text.
472
+
473
+ If the font uses antialiasing, the bitmap should have mode ``L`` and use a
474
+ maximum value of 255. If the font has embedded color data, the bitmap
475
+ should have mode ``RGBA``. Otherwise, it should have mode ``1``.
476
+
477
+ :param text: Text to render.
478
+ :param mode: Used by some graphics drivers to indicate what mode the
479
+ driver prefers; if empty, the renderer may return either
480
+ mode. Note that the mode is always a string, to simplify
481
+ C-level implementations.
482
+
483
+ .. versionadded:: 1.1.5
484
+
485
+ :param direction: Direction of the text. It can be 'rtl' (right to
486
+ left), 'ltr' (left to right) or 'ttb' (top to bottom).
487
+ Requires libraqm.
488
+
489
+ .. versionadded:: 4.2.0
490
+
491
+ :param features: A list of OpenType font features to be used during text
492
+ layout. This is usually used to turn on optional
493
+ font features that are not enabled by default,
494
+ for example 'dlig' or 'ss01', but can be also
495
+ used to turn off default font features for
496
+ example '-liga' to disable ligatures or '-kern'
497
+ to disable kerning. To get all supported
498
+ features, see
499
+ https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist
500
+ Requires libraqm.
501
+
502
+ .. versionadded:: 4.2.0
503
+
504
+ :param language: Language of the text. Different languages may use
505
+ different glyph shapes or ligatures. This parameter tells
506
+ the font which language the text is in, and to apply the
507
+ correct substitutions as appropriate, if available.
508
+ It should be a `BCP 47 language code
509
+ <https://www.w3.org/International/articles/language-tags/>`_
510
+ Requires libraqm.
511
+
512
+ .. versionadded:: 6.0.0
513
+
514
+ :param stroke_width: The width of the text stroke.
515
+
516
+ .. versionadded:: 6.2.0
517
+
518
+ :param anchor: The text anchor alignment. Determines the relative location of
519
+ the anchor to the text. The default alignment is top left,
520
+ specifically ``la`` for horizontal text and ``lt`` for
521
+ vertical text. See :ref:`text-anchors` for details.
522
+
523
+ .. versionadded:: 8.0.0
524
+
525
+ :param ink: Foreground ink for rendering in RGBA mode.
526
+
527
+ .. versionadded:: 8.0.0
528
+
529
+ :param start: Tuple of horizontal and vertical offset, as text may render
530
+ differently when starting at fractional coordinates.
531
+
532
+ .. versionadded:: 9.4.0
533
+
534
+ :return: An internal PIL storage memory instance as defined by the
535
+ :py:mod:`PIL.Image.core` interface module.
536
+ """
537
+ return self.getmask2(
538
+ text,
539
+ mode,
540
+ direction=direction,
541
+ features=features,
542
+ language=language,
543
+ stroke_width=stroke_width,
544
+ anchor=anchor,
545
+ ink=ink,
546
+ start=start,
547
+ )[0]
548
+
549
+ def getmask2(
550
+ self,
551
+ text: str | bytes,
552
+ mode: str = "",
553
+ direction: str | None = None,
554
+ features: list[str] | None = None,
555
+ language: str | None = None,
556
+ stroke_width: float = 0,
557
+ anchor: str | None = None,
558
+ ink: int = 0,
559
+ start: tuple[float, float] | None = None,
560
+ *args: Any,
561
+ **kwargs: Any,
562
+ ) -> tuple[Image.core.ImagingCore, tuple[int, int]]:
563
+ """
564
+ Create a bitmap for the text.
565
+
566
+ If the font uses antialiasing, the bitmap should have mode ``L`` and use a
567
+ maximum value of 255. If the font has embedded color data, the bitmap
568
+ should have mode ``RGBA``. Otherwise, it should have mode ``1``.
569
+
570
+ :param text: Text to render.
571
+ :param mode: Used by some graphics drivers to indicate what mode the
572
+ driver prefers; if empty, the renderer may return either
573
+ mode. Note that the mode is always a string, to simplify
574
+ C-level implementations.
575
+
576
+ .. versionadded:: 1.1.5
577
+
578
+ :param direction: Direction of the text. It can be 'rtl' (right to
579
+ left), 'ltr' (left to right) or 'ttb' (top to bottom).
580
+ Requires libraqm.
581
+
582
+ .. versionadded:: 4.2.0
583
+
584
+ :param features: A list of OpenType font features to be used during text
585
+ layout. This is usually used to turn on optional
586
+ font features that are not enabled by default,
587
+ for example 'dlig' or 'ss01', but can be also
588
+ used to turn off default font features for
589
+ example '-liga' to disable ligatures or '-kern'
590
+ to disable kerning. To get all supported
591
+ features, see
592
+ https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist
593
+ Requires libraqm.
594
+
595
+ .. versionadded:: 4.2.0
596
+
597
+ :param language: Language of the text. Different languages may use
598
+ different glyph shapes or ligatures. This parameter tells
599
+ the font which language the text is in, and to apply the
600
+ correct substitutions as appropriate, if available.
601
+ It should be a `BCP 47 language code
602
+ <https://www.w3.org/International/articles/language-tags/>`_
603
+ Requires libraqm.
604
+
605
+ .. versionadded:: 6.0.0
606
+
607
+ :param stroke_width: The width of the text stroke.
608
+
609
+ .. versionadded:: 6.2.0
610
+
611
+ :param anchor: The text anchor alignment. Determines the relative location of
612
+ the anchor to the text. The default alignment is top left,
613
+ specifically ``la`` for horizontal text and ``lt`` for
614
+ vertical text. See :ref:`text-anchors` for details.
615
+
616
+ .. versionadded:: 8.0.0
617
+
618
+ :param ink: Foreground ink for rendering in RGBA mode.
619
+
620
+ .. versionadded:: 8.0.0
621
+
622
+ :param start: Tuple of horizontal and vertical offset, as text may render
623
+ differently when starting at fractional coordinates.
624
+
625
+ .. versionadded:: 9.4.0
626
+
627
+ :return: A tuple of an internal PIL storage memory instance as defined by the
628
+ :py:mod:`PIL.Image.core` interface module, and the text offset, the
629
+ gap between the starting coordinate and the first marking
630
+ """
631
+ _string_length_check(text)
632
+ if start is None:
633
+ start = (0, 0)
634
+
635
+ def fill(width: int, height: int) -> Image.core.ImagingCore:
636
+ size = (width, height)
637
+ Image._decompression_bomb_check(size)
638
+ return Image.core.fill("RGBA" if mode == "RGBA" else "L", size)
639
+
640
+ return self.font.render(
641
+ text,
642
+ fill,
643
+ mode,
644
+ direction,
645
+ features,
646
+ language,
647
+ stroke_width,
648
+ kwargs.get("stroke_filled", False),
649
+ anchor,
650
+ ink,
651
+ start,
652
+ )
653
+
654
+ def font_variant(
655
+ self,
656
+ font: StrOrBytesPath | BinaryIO | None = None,
657
+ size: float | None = None,
658
+ index: int | None = None,
659
+ encoding: str | None = None,
660
+ layout_engine: Layout | None = None,
661
+ ) -> FreeTypeFont:
662
+ """
663
+ Create a copy of this FreeTypeFont object,
664
+ using any specified arguments to override the settings.
665
+
666
+ Parameters are identical to the parameters used to initialize this
667
+ object.
668
+
669
+ :return: A FreeTypeFont object.
670
+ """
671
+ if font is None:
672
+ try:
673
+ font = BytesIO(self.font_bytes)
674
+ except AttributeError:
675
+ font = self.path
676
+ return FreeTypeFont(
677
+ font=font,
678
+ size=self.size if size is None else size,
679
+ index=self.index if index is None else index,
680
+ encoding=self.encoding if encoding is None else encoding,
681
+ layout_engine=layout_engine or self.layout_engine,
682
+ )
683
+
684
+ def get_variation_names(self) -> list[bytes]:
685
+ """
686
+ :returns: A list of the named styles in a variation font.
687
+ :exception OSError: If the font is not a variation font.
688
+ """
689
+ try:
690
+ names = self.font.getvarnames()
691
+ except AttributeError as e:
692
+ msg = "FreeType 2.9.1 or greater is required"
693
+ raise NotImplementedError(msg) from e
694
+ return [name.replace(b"\x00", b"") for name in names]
695
+
696
+ def set_variation_by_name(self, name: str | bytes) -> None:
697
+ """
698
+ :param name: The name of the style.
699
+ :exception OSError: If the font is not a variation font.
700
+ """
701
+ names = self.get_variation_names()
702
+ if not isinstance(name, bytes):
703
+ name = name.encode()
704
+ index = names.index(name) + 1
705
+
706
+ if index == getattr(self, "_last_variation_index", None):
707
+ # When the same name is set twice in a row,
708
+ # there is an 'unknown freetype error'
709
+ # https://savannah.nongnu.org/bugs/?56186
710
+ return
711
+ self._last_variation_index = index
712
+
713
+ self.font.setvarname(index)
714
+
715
+ def get_variation_axes(self) -> list[Axis]:
716
+ """
717
+ :returns: A list of the axes in a variation font.
718
+ :exception OSError: If the font is not a variation font.
719
+ """
720
+ try:
721
+ axes = self.font.getvaraxes()
722
+ except AttributeError as e:
723
+ msg = "FreeType 2.9.1 or greater is required"
724
+ raise NotImplementedError(msg) from e
725
+ for axis in axes:
726
+ if axis["name"]:
727
+ axis["name"] = axis["name"].replace(b"\x00", b"")
728
+ return axes
729
+
730
+ def set_variation_by_axes(self, axes: list[float]) -> None:
731
+ """
732
+ :param axes: A list of values for each axis.
733
+ :exception OSError: If the font is not a variation font.
734
+ """
735
+ try:
736
+ self.font.setvaraxes(axes)
737
+ except AttributeError as e:
738
+ msg = "FreeType 2.9.1 or greater is required"
739
+ raise NotImplementedError(msg) from e
740
+
741
+
742
+ class TransposedFont:
743
+ """Wrapper for writing rotated or mirrored text"""
744
+
745
+ def __init__(
746
+ self, font: ImageFont | FreeTypeFont, orientation: Image.Transpose | None = None
747
+ ):
748
+ """
749
+ Wrapper that creates a transposed font from any existing font
750
+ object.
751
+
752
+ :param font: A font object.
753
+ :param orientation: An optional orientation. If given, this should
754
+ be one of Image.Transpose.FLIP_LEFT_RIGHT, Image.Transpose.FLIP_TOP_BOTTOM,
755
+ Image.Transpose.ROTATE_90, Image.Transpose.ROTATE_180, or
756
+ Image.Transpose.ROTATE_270.
757
+ """
758
+ self.font = font
759
+ self.orientation = orientation # any 'transpose' argument, or None
760
+
761
+ def getmask(
762
+ self, text: str | bytes, mode: str = "", *args: Any, **kwargs: Any
763
+ ) -> Image.core.ImagingCore:
764
+ im = self.font.getmask(text, mode, *args, **kwargs)
765
+ if self.orientation is not None:
766
+ return im.transpose(self.orientation)
767
+ return im
768
+
769
+ def getbbox(
770
+ self, text: str | bytes, *args: Any, **kwargs: Any
771
+ ) -> tuple[int, int, float, float]:
772
+ # TransposedFont doesn't support getmask2, move top-left point to (0, 0)
773
+ # this has no effect on ImageFont and simulates anchor="lt" for FreeTypeFont
774
+ left, top, right, bottom = self.font.getbbox(text, *args, **kwargs)
775
+ width = right - left
776
+ height = bottom - top
777
+ if self.orientation in (Image.Transpose.ROTATE_90, Image.Transpose.ROTATE_270):
778
+ return 0, 0, height, width
779
+ return 0, 0, width, height
780
+
781
+ def getlength(self, text: str | bytes, *args: Any, **kwargs: Any) -> float:
782
+ if self.orientation in (Image.Transpose.ROTATE_90, Image.Transpose.ROTATE_270):
783
+ msg = "text length is undefined for text rotated by 90 or 270 degrees"
784
+ raise ValueError(msg)
785
+ return self.font.getlength(text, *args, **kwargs)
786
+
787
+
788
+ def load(filename: str) -> ImageFont:
789
+ """
790
+ Load a font file. This function loads a font object from the given
791
+ bitmap font file, and returns the corresponding font object. For loading TrueType
792
+ or OpenType fonts instead, see :py:func:`~PIL.ImageFont.truetype`.
793
+
794
+ :param filename: Name of font file.
795
+ :return: A font object.
796
+ :exception OSError: If the file could not be read.
797
+ """
798
+ f = ImageFont()
799
+ f._load_pilfont(filename)
800
+ return f
801
+
802
+
803
+ def truetype(
804
+ font: StrOrBytesPath | BinaryIO,
805
+ size: float = 10,
806
+ index: int = 0,
807
+ encoding: str = "",
808
+ layout_engine: Layout | None = None,
809
+ ) -> FreeTypeFont:
810
+ """
811
+ Load a TrueType or OpenType font from a file or file-like object,
812
+ and create a font object. This function loads a font object from the given
813
+ file or file-like object, and creates a font object for a font of the given
814
+ size. For loading bitmap fonts instead, see :py:func:`~PIL.ImageFont.load`
815
+ and :py:func:`~PIL.ImageFont.load_path`.
816
+
817
+ Pillow uses FreeType to open font files. On Windows, be aware that FreeType
818
+ will keep the file open as long as the FreeTypeFont object exists. Windows
819
+ limits the number of files that can be open in C at once to 512, so if many
820
+ fonts are opened simultaneously and that limit is approached, an
821
+ ``OSError`` may be thrown, reporting that FreeType "cannot open resource".
822
+ A workaround would be to copy the file(s) into memory, and open that instead.
823
+
824
+ This function requires the _imagingft service.
825
+
826
+ :param font: A filename or file-like object containing a TrueType font.
827
+ If the file is not found in this filename, the loader may also
828
+ search in other directories, such as:
829
+
830
+ * The :file:`fonts/` directory on Windows,
831
+ * :file:`/Library/Fonts/`, :file:`/System/Library/Fonts/`
832
+ and :file:`~/Library/Fonts/` on macOS.
833
+ * :file:`~/.local/share/fonts`, :file:`/usr/local/share/fonts`,
834
+ and :file:`/usr/share/fonts` on Linux; or those specified by
835
+ the ``XDG_DATA_HOME`` and ``XDG_DATA_DIRS`` environment variables
836
+ for user-installed and system-wide fonts, respectively.
837
+
838
+ :param size: The requested size, in pixels.
839
+ :param index: Which font face to load (default is first available face).
840
+ :param encoding: Which font encoding to use (default is Unicode). Possible
841
+ encodings include (see the FreeType documentation for more
842
+ information):
843
+
844
+ * "unic" (Unicode)
845
+ * "symb" (Microsoft Symbol)
846
+ * "ADOB" (Adobe Standard)
847
+ * "ADBE" (Adobe Expert)
848
+ * "ADBC" (Adobe Custom)
849
+ * "armn" (Apple Roman)
850
+ * "sjis" (Shift JIS)
851
+ * "gb " (PRC)
852
+ * "big5"
853
+ * "wans" (Extended Wansung)
854
+ * "joha" (Johab)
855
+ * "lat1" (Latin-1)
856
+
857
+ This specifies the character set to use. It does not alter the
858
+ encoding of any text provided in subsequent operations.
859
+ :param layout_engine: Which layout engine to use, if available:
860
+ :attr:`.ImageFont.Layout.BASIC` or :attr:`.ImageFont.Layout.RAQM`.
861
+ If it is available, Raqm layout will be used by default.
862
+ Otherwise, basic layout will be used.
863
+
864
+ Raqm layout is recommended for all non-English text. If Raqm layout
865
+ is not required, basic layout will have better performance.
866
+
867
+ You can check support for Raqm layout using
868
+ :py:func:`PIL.features.check_feature` with ``feature="raqm"``.
869
+
870
+ .. versionadded:: 4.2.0
871
+ :return: A font object.
872
+ :exception OSError: If the file could not be read.
873
+ :exception ValueError: If the font size is not greater than zero.
874
+ """
875
+
876
+ def freetype(font: StrOrBytesPath | BinaryIO) -> FreeTypeFont:
877
+ return FreeTypeFont(font, size, index, encoding, layout_engine)
878
+
879
+ try:
880
+ return freetype(font)
881
+ except OSError:
882
+ if not is_path(font):
883
+ raise
884
+ ttf_filename = os.path.basename(font)
885
+
886
+ dirs = []
887
+ if sys.platform == "win32":
888
+ # check the windows font repository
889
+ # NOTE: must use uppercase WINDIR, to work around bugs in
890
+ # 1.5.2's os.environ.get()
891
+ windir = os.environ.get("WINDIR")
892
+ if windir:
893
+ dirs.append(os.path.join(windir, "fonts"))
894
+ elif sys.platform in ("linux", "linux2"):
895
+ data_home = os.environ.get("XDG_DATA_HOME")
896
+ if not data_home:
897
+ # The freedesktop spec defines the following default directory for
898
+ # when XDG_DATA_HOME is unset or empty. This user-level directory
899
+ # takes precedence over system-level directories.
900
+ data_home = os.path.expanduser("~/.local/share")
901
+ xdg_dirs = [data_home]
902
+
903
+ data_dirs = os.environ.get("XDG_DATA_DIRS")
904
+ if not data_dirs:
905
+ # Similarly, defaults are defined for the system-level directories
906
+ data_dirs = "/usr/local/share:/usr/share"
907
+ xdg_dirs += data_dirs.split(":")
908
+
909
+ dirs += [os.path.join(xdg_dir, "fonts") for xdg_dir in xdg_dirs]
910
+ elif sys.platform == "darwin":
911
+ dirs += [
912
+ "/Library/Fonts",
913
+ "/System/Library/Fonts",
914
+ os.path.expanduser("~/Library/Fonts"),
915
+ ]
916
+
917
+ ext = os.path.splitext(ttf_filename)[1]
918
+ first_font_with_a_different_extension = None
919
+ for directory in dirs:
920
+ for walkroot, walkdir, walkfilenames in os.walk(directory):
921
+ for walkfilename in walkfilenames:
922
+ if ext and walkfilename == ttf_filename:
923
+ return freetype(os.path.join(walkroot, walkfilename))
924
+ elif not ext and os.path.splitext(walkfilename)[0] == ttf_filename:
925
+ fontpath = os.path.join(walkroot, walkfilename)
926
+ if os.path.splitext(fontpath)[1] == ".ttf":
927
+ return freetype(fontpath)
928
+ if not ext and first_font_with_a_different_extension is None:
929
+ first_font_with_a_different_extension = fontpath
930
+ if first_font_with_a_different_extension:
931
+ return freetype(first_font_with_a_different_extension)
932
+ raise
933
+
934
+
935
+ def load_path(filename: str | bytes) -> ImageFont:
936
+ """
937
+ Load font file. Same as :py:func:`~PIL.ImageFont.load`, but searches for a
938
+ bitmap font along the Python path.
939
+
940
+ :param filename: Name of font file.
941
+ :return: A font object.
942
+ :exception OSError: If the file could not be read.
943
+ """
944
+ if not isinstance(filename, str):
945
+ filename = filename.decode("utf-8")
946
+ for directory in sys.path:
947
+ try:
948
+ return load(os.path.join(directory, filename))
949
+ except OSError:
950
+ pass
951
+ msg = f'cannot find font file "{filename}" in sys.path'
952
+ if os.path.exists(filename):
953
+ msg += f', did you mean ImageFont.load("{filename}") instead?'
954
+
955
+ raise OSError(msg)
956
+
957
+
958
+ def load_default_imagefont() -> ImageFont:
959
+ f = ImageFont()
960
+ f._load_pilfont_data(
961
+ # courB08
962
+ BytesIO(
963
+ base64.b64decode(
964
+ b"""
965
+ UElMZm9udAo7Ozs7OzsxMDsKREFUQQoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
966
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
967
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
968
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
969
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
970
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
971
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
972
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
973
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
974
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
975
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
976
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAAA//8AAQAAAAAAAAABAAEA
977
+ BgAAAAH/+gADAAAAAQAAAAMABgAGAAAAAf/6AAT//QADAAAABgADAAYAAAAA//kABQABAAYAAAAL
978
+ AAgABgAAAAD/+AAFAAEACwAAABAACQAGAAAAAP/5AAUAAAAQAAAAFQAHAAYAAP////oABQAAABUA
979
+ AAAbAAYABgAAAAH/+QAE//wAGwAAAB4AAwAGAAAAAf/5AAQAAQAeAAAAIQAIAAYAAAAB//kABAAB
980
+ ACEAAAAkAAgABgAAAAD/+QAE//0AJAAAACgABAAGAAAAAP/6AAX//wAoAAAALQAFAAYAAAAB//8A
981
+ BAACAC0AAAAwAAMABgAAAAD//AAF//0AMAAAADUAAQAGAAAAAf//AAMAAAA1AAAANwABAAYAAAAB
982
+ //kABQABADcAAAA7AAgABgAAAAD/+QAFAAAAOwAAAEAABwAGAAAAAP/5AAYAAABAAAAARgAHAAYA
983
+ AAAA//kABQAAAEYAAABLAAcABgAAAAD/+QAFAAAASwAAAFAABwAGAAAAAP/5AAYAAABQAAAAVgAH
984
+ AAYAAAAA//kABQAAAFYAAABbAAcABgAAAAD/+QAFAAAAWwAAAGAABwAGAAAAAP/5AAUAAABgAAAA
985
+ ZQAHAAYAAAAA//kABQAAAGUAAABqAAcABgAAAAD/+QAFAAAAagAAAG8ABwAGAAAAAf/8AAMAAABv
986
+ AAAAcQAEAAYAAAAA//wAAwACAHEAAAB0AAYABgAAAAD/+gAE//8AdAAAAHgABQAGAAAAAP/7AAT/
987
+ /gB4AAAAfAADAAYAAAAB//oABf//AHwAAACAAAUABgAAAAD/+gAFAAAAgAAAAIUABgAGAAAAAP/5
988
+ AAYAAQCFAAAAiwAIAAYAAP////oABgAAAIsAAACSAAYABgAA////+gAFAAAAkgAAAJgABgAGAAAA
989
+ AP/6AAUAAACYAAAAnQAGAAYAAP////oABQAAAJ0AAACjAAYABgAA////+gAFAAAAowAAAKkABgAG
990
+ AAD////6AAUAAACpAAAArwAGAAYAAAAA//oABQAAAK8AAAC0AAYABgAA////+gAGAAAAtAAAALsA
991
+ BgAGAAAAAP/6AAQAAAC7AAAAvwAGAAYAAP////oABQAAAL8AAADFAAYABgAA////+gAGAAAAxQAA
992
+ AMwABgAGAAD////6AAUAAADMAAAA0gAGAAYAAP////oABQAAANIAAADYAAYABgAA////+gAGAAAA
993
+ 2AAAAN8ABgAGAAAAAP/6AAUAAADfAAAA5AAGAAYAAP////oABQAAAOQAAADqAAYABgAAAAD/+gAF
994
+ AAEA6gAAAO8ABwAGAAD////6AAYAAADvAAAA9gAGAAYAAAAA//oABQAAAPYAAAD7AAYABgAA////
995
+ +gAFAAAA+wAAAQEABgAGAAD////6AAYAAAEBAAABCAAGAAYAAP////oABgAAAQgAAAEPAAYABgAA
996
+ ////+gAGAAABDwAAARYABgAGAAAAAP/6AAYAAAEWAAABHAAGAAYAAP////oABgAAARwAAAEjAAYA
997
+ BgAAAAD/+gAFAAABIwAAASgABgAGAAAAAf/5AAQAAQEoAAABKwAIAAYAAAAA//kABAABASsAAAEv
998
+ AAgABgAAAAH/+QAEAAEBLwAAATIACAAGAAAAAP/5AAX//AEyAAABNwADAAYAAAAAAAEABgACATcA
999
+ AAE9AAEABgAAAAH/+QAE//wBPQAAAUAAAwAGAAAAAP/7AAYAAAFAAAABRgAFAAYAAP////kABQAA
1000
+ AUYAAAFMAAcABgAAAAD/+wAFAAABTAAAAVEABQAGAAAAAP/5AAYAAAFRAAABVwAHAAYAAAAA//sA
1001
+ BQAAAVcAAAFcAAUABgAAAAD/+QAFAAABXAAAAWEABwAGAAAAAP/7AAYAAgFhAAABZwAHAAYAAP//
1002
+ //kABQAAAWcAAAFtAAcABgAAAAD/+QAGAAABbQAAAXMABwAGAAAAAP/5AAQAAgFzAAABdwAJAAYA
1003
+ AP////kABgAAAXcAAAF+AAcABgAAAAD/+QAGAAABfgAAAYQABwAGAAD////7AAUAAAGEAAABigAF
1004
+ AAYAAP////sABQAAAYoAAAGQAAUABgAAAAD/+wAFAAABkAAAAZUABQAGAAD////7AAUAAgGVAAAB
1005
+ mwAHAAYAAAAA//sABgACAZsAAAGhAAcABgAAAAD/+wAGAAABoQAAAacABQAGAAAAAP/7AAYAAAGn
1006
+ AAABrQAFAAYAAAAA//kABgAAAa0AAAGzAAcABgAA////+wAGAAABswAAAboABQAGAAD////7AAUA
1007
+ AAG6AAABwAAFAAYAAP////sABgAAAcAAAAHHAAUABgAAAAD/+wAGAAABxwAAAc0ABQAGAAD////7
1008
+ AAYAAgHNAAAB1AAHAAYAAAAA//sABQAAAdQAAAHZAAUABgAAAAH/+QAFAAEB2QAAAd0ACAAGAAAA
1009
+ Av/6AAMAAQHdAAAB3gAHAAYAAAAA//kABAABAd4AAAHiAAgABgAAAAD/+wAF//0B4gAAAecAAgAA
1010
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
1011
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
1012
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
1013
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
1014
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
1015
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
1016
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
1017
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
1018
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
1019
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
1020
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
1021
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAAB
1022
+ //sAAwACAecAAAHpAAcABgAAAAD/+QAFAAEB6QAAAe4ACAAGAAAAAP/5AAYAAAHuAAAB9AAHAAYA
1023
+ AAAA//oABf//AfQAAAH5AAUABgAAAAD/+QAGAAAB+QAAAf8ABwAGAAAAAv/5AAMAAgH/AAACAAAJ
1024
+ AAYAAAAA//kABQABAgAAAAIFAAgABgAAAAH/+gAE//sCBQAAAggAAQAGAAAAAP/5AAYAAAIIAAAC
1025
+ DgAHAAYAAAAB//kABf/+Ag4AAAISAAUABgAA////+wAGAAACEgAAAhkABQAGAAAAAP/7AAX//gIZ
1026
+ AAACHgADAAYAAAAA//wABf/9Ah4AAAIjAAEABgAAAAD/+QAHAAACIwAAAioABwAGAAAAAP/6AAT/
1027
+ +wIqAAACLgABAAYAAAAA//kABP/8Ai4AAAIyAAMABgAAAAD/+gAFAAACMgAAAjcABgAGAAAAAf/5
1028
+ AAT//QI3AAACOgAEAAYAAAAB//kABP/9AjoAAAI9AAQABgAAAAL/+QAE//sCPQAAAj8AAgAGAAD/
1029
+ ///7AAYAAgI/AAACRgAHAAYAAAAA//kABgABAkYAAAJMAAgABgAAAAH//AAD//0CTAAAAk4AAQAG
1030
+ AAAAAf//AAQAAgJOAAACUQADAAYAAAAB//kABP/9AlEAAAJUAAQABgAAAAH/+QAF//4CVAAAAlgA
1031
+ BQAGAAD////7AAYAAAJYAAACXwAFAAYAAP////kABgAAAl8AAAJmAAcABgAA////+QAGAAACZgAA
1032
+ Am0ABwAGAAD////5AAYAAAJtAAACdAAHAAYAAAAA//sABQACAnQAAAJ5AAcABgAA////9wAGAAAC
1033
+ eQAAAoAACQAGAAD////3AAYAAAKAAAAChwAJAAYAAP////cABgAAAocAAAKOAAkABgAA////9wAG
1034
+ AAACjgAAApUACQAGAAD////4AAYAAAKVAAACnAAIAAYAAP////cABgAAApwAAAKjAAkABgAA////
1035
+ +gAGAAACowAAAqoABgAGAAAAAP/6AAUAAgKqAAACrwAIAAYAAP////cABQAAAq8AAAK1AAkABgAA
1036
+ ////9wAFAAACtQAAArsACQAGAAD////3AAUAAAK7AAACwQAJAAYAAP////gABQAAAsEAAALHAAgA
1037
+ BgAAAAD/9wAEAAACxwAAAssACQAGAAAAAP/3AAQAAALLAAACzwAJAAYAAAAA//cABAAAAs8AAALT
1038
+ AAkABgAAAAD/+AAEAAAC0wAAAtcACAAGAAD////6AAUAAALXAAAC3QAGAAYAAP////cABgAAAt0A
1039
+ AALkAAkABgAAAAD/9wAFAAAC5AAAAukACQAGAAAAAP/3AAUAAALpAAAC7gAJAAYAAAAA//cABQAA
1040
+ Au4AAALzAAkABgAAAAD/9wAFAAAC8wAAAvgACQAGAAAAAP/4AAUAAAL4AAAC/QAIAAYAAAAA//oA
1041
+ Bf//Av0AAAMCAAUABgAA////+gAGAAADAgAAAwkABgAGAAD////3AAYAAAMJAAADEAAJAAYAAP//
1042
+ //cABgAAAxAAAAMXAAkABgAA////9wAGAAADFwAAAx4ACQAGAAD////4AAYAAAAAAAoABwASAAYA
1043
+ AP////cABgAAAAcACgAOABMABgAA////+gAFAAAADgAKABQAEAAGAAD////6AAYAAAAUAAoAGwAQ
1044
+ AAYAAAAA//gABgAAABsACgAhABIABgAAAAD/+AAGAAAAIQAKACcAEgAGAAAAAP/4AAYAAAAnAAoA
1045
+ LQASAAYAAAAA//gABgAAAC0ACgAzABIABgAAAAD/+QAGAAAAMwAKADkAEQAGAAAAAP/3AAYAAAA5
1046
+ AAoAPwATAAYAAP////sABQAAAD8ACgBFAA8ABgAAAAD/+wAFAAIARQAKAEoAEQAGAAAAAP/4AAUA
1047
+ AABKAAoATwASAAYAAAAA//gABQAAAE8ACgBUABIABgAAAAD/+AAFAAAAVAAKAFkAEgAGAAAAAP/5
1048
+ AAUAAABZAAoAXgARAAYAAAAA//gABgAAAF4ACgBkABIABgAAAAD/+AAGAAAAZAAKAGoAEgAGAAAA
1049
+ AP/4AAYAAABqAAoAcAASAAYAAAAA//kABgAAAHAACgB2ABEABgAAAAD/+AAFAAAAdgAKAHsAEgAG
1050
+ AAD////4AAYAAAB7AAoAggASAAYAAAAA//gABQAAAIIACgCHABIABgAAAAD/+AAFAAAAhwAKAIwA
1051
+ EgAGAAAAAP/4AAUAAACMAAoAkQASAAYAAAAA//gABQAAAJEACgCWABIABgAAAAD/+QAFAAAAlgAK
1052
+ AJsAEQAGAAAAAP/6AAX//wCbAAoAoAAPAAYAAAAA//oABQABAKAACgClABEABgAA////+AAGAAAA
1053
+ pQAKAKwAEgAGAAD////4AAYAAACsAAoAswASAAYAAP////gABgAAALMACgC6ABIABgAA////+QAG
1054
+ AAAAugAKAMEAEQAGAAD////4AAYAAgDBAAoAyAAUAAYAAP////kABQACAMgACgDOABMABgAA////
1055
+ +QAGAAIAzgAKANUAEw==
1056
+ """
1057
+ )
1058
+ ),
1059
+ Image.open(
1060
+ BytesIO(
1061
+ base64.b64decode(
1062
+ b"""
1063
+ iVBORw0KGgoAAAANSUhEUgAAAx4AAAAUAQAAAAArMtZoAAAEwElEQVR4nABlAJr/AHVE4czCI/4u
1064
+ Mc4b7vuds/xzjz5/3/7u/n9vMe7vnfH/9++vPn/xyf5zhxzjt8GHw8+2d83u8x27199/nxuQ6Od9
1065
+ M43/5z2I+9n9ZtmDBwMQECDRQw/eQIQohJXxpBCNVE6QCCAAAAD//wBlAJr/AgALyj1t/wINwq0g
1066
+ LeNZUworuN1cjTPIzrTX6ofHWeo3v336qPzfEwRmBnHTtf95/fglZK5N0PDgfRTslpGBvz7LFc4F
1067
+ IUXBWQGjQ5MGCx34EDFPwXiY4YbYxavpnhHFrk14CDAAAAD//wBlAJr/AgKqRooH2gAgPeggvUAA
1068
+ Bu2WfgPoAwzRAABAAAAAAACQgLz/3Uv4Gv+gX7BJgDeeGP6AAAD1NMDzKHD7ANWr3loYbxsAD791
1069
+ NAADfcoIDyP44K/jv4Y63/Z+t98Ovt+ub4T48LAAAAD//wBlAJr/AuplMlADJAAAAGuAphWpqhMx
1070
+ in0A/fRvAYBABPgBwBUgABBQ/sYAyv9g0bCHgOLoGAAAAAAAREAAwI7nr0ArYpow7aX8//9LaP/9
1071
+ SjdavWA8ePHeBIKB//81/83ndznOaXx379wAAAD//wBlAJr/AqDxW+D3AABAAbUh/QMnbQag/gAY
1072
+ AYDAAACgtgD/gOqAAAB5IA/8AAAk+n9w0AAA8AAAmFRJuPo27ciC0cD5oeW4E7KA/wD3ECMAn2tt
1073
+ y8PgwH8AfAxFzC0JzeAMtratAsC/ffwAAAD//wBlAJr/BGKAyCAA4AAAAvgeYTAwHd1kmQF5chkG
1074
+ ABoMIHcL5xVpTfQbUqzlAAAErwAQBgAAEOClA5D9il08AEh/tUzdCBsXkbgACED+woQg8Si9VeqY
1075
+ lODCn7lmF6NhnAEYgAAA/NMIAAAAAAD//2JgjLZgVGBg5Pv/Tvpc8hwGBjYGJADjHDrAwPzAjv/H
1076
+ /Wf3PzCwtzcwHmBgYGcwbZz8wHaCAQMDOwMDQ8MCBgYOC3W7mp+f0w+wHOYxO3OG+e376hsMZjk3
1077
+ AAAAAP//YmCMY2A4wMAIN5e5gQETPD6AZisDAwMDgzSDAAPjByiHcQMDAwMDg1nOze1lByRu5/47
1078
+ c4859311AYNZzg0AAAAA//9iYGDBYihOIIMuwIjGL39/fwffA8b//xv/P2BPtzzHwCBjUQAAAAD/
1079
+ /yLFBrIBAAAA//9i1HhcwdhizX7u8NZNzyLbvT97bfrMf/QHI8evOwcSqGUJAAAA//9iYBB81iSw
1080
+ pEE170Qrg5MIYydHqwdDQRMrAwcVrQAAAAD//2J4x7j9AAMDn8Q/BgYLBoaiAwwMjPdvMDBYM1Tv
1081
+ oJodAAAAAP//Yqo/83+dxePWlxl3npsel9lvLfPcqlE9725C+acfVLMEAAAA//9i+s9gwCoaaGMR
1082
+ evta/58PTEWzr21hufPjA8N+qlnBwAAAAAD//2JiWLci5v1+HmFXDqcnULE/MxgYGBj+f6CaJQAA
1083
+ AAD//2Ji2FrkY3iYpYC5qDeGgeEMAwPDvwQBBoYvcTwOVLMEAAAA//9isDBgkP///0EOg9z35v//
1084
+ Gc/eeW7BwPj5+QGZhANUswMAAAD//2JgqGBgYGBgqEMXlvhMPUsAAAAA//8iYDd1AAAAAP//AwDR
1085
+ w7IkEbzhVQAAAABJRU5ErkJggg==
1086
+ """
1087
+ )
1088
+ )
1089
+ ),
1090
+ )
1091
+ return f
1092
+
1093
+
1094
+ def load_default(size: float | None = None) -> FreeTypeFont | ImageFont:
1095
+ """If FreeType support is available, load a version of Aileron Regular,
1096
+ https://dotcolon.net/fonts/aileron, with a more limited character set.
1097
+
1098
+ Otherwise, load a "better than nothing" font.
1099
+
1100
+ .. versionadded:: 1.1.4
1101
+
1102
+ :param size: The font size of Aileron Regular.
1103
+
1104
+ .. versionadded:: 10.1.0
1105
+
1106
+ :return: A font object.
1107
+ """
1108
+ if isinstance(core, ModuleType) or size is not None:
1109
+ return truetype(
1110
+ BytesIO(
1111
+ base64.b64decode(
1112
+ b"""
1113
+ AAEAAAAPAIAAAwBwRkZUTYwDlUAAADFoAAAAHEdERUYAqADnAAAo8AAAACRHUE9ThhmITwAAKfgAA
1114
+ AduR1NVQnHxefoAACkUAAAA4k9TLzJovoHLAAABeAAAAGBjbWFw5lFQMQAAA6gAAAGqZ2FzcP//AA
1115
+ MAACjoAAAACGdseWYmRXoPAAAGQAAAHfhoZWFkE18ayQAAAPwAAAA2aGhlYQboArEAAAE0AAAAJGh
1116
+ tdHjjERZ8AAAB2AAAAdBsb2NhuOexrgAABVQAAADqbWF4cAC7AEYAAAFYAAAAIG5hbWUr+h5lAAAk
1117
+ OAAAA6Jwb3N0D3oPTQAAJ9wAAAEKAAEAAAABGhxJDqIhXw889QALA+gAAAAA0Bqf2QAAAADhCh2h/
1118
+ 2r/LgOxAyAAAAAIAAIAAAAAAAAAAQAAA8r/GgAAA7j/av9qA7EAAQAAAAAAAAAAAAAAAAAAAHQAAQ
1119
+ AAAHQAQwAFAAAAAAACAAAAAQABAAAAQAAAAAAAAAADAfoBkAAFAAgCigJYAAAASwKKAlgAAAFeADI
1120
+ BPgAAAAAFAAAAAAAAAAAAAAcAAAAAAAAAAAAAAABVS1dOAEAAIPsCAwL/GgDIA8oA5iAAAJMAAAAA
1121
+ AhICsgAAACAAAwH0AAAAAAAAAU0AAADYAAAA8gA5AVMAVgJEAEYCRAA1AuQAKQKOAEAAsAArATsAZ
1122
+ AE7AB4CMABVAkQAUADc/+EBEgAgANwAJQEv//sCRAApAkQAggJEADwCRAAtAkQAIQJEADkCRAArAk
1123
+ QAMgJEACwCRAAxANwAJQDc/+ECRABnAkQAUAJEAEQB8wAjA1QANgJ/AB0CcwBkArsALwLFAGQCSwB
1124
+ kAjcAZALGAC8C2gBkAQgAZAIgADcCYQBkAj8AZANiAGQCzgBkAuEALwJWAGQC3QAvAmsAZAJJADQC
1125
+ ZAAiAqoAXgJuACADuAAaAnEAGQJFABMCTwAuATMAYgEv//sBJwAiAkQAUAH0ADIBLAApAhMAJAJjA
1126
+ EoCEQAeAmcAHgIlAB4BIgAVAmcAHgJRAEoA7gA+AOn/8wIKAEoA9wBGA1cASgJRAEoCSgAeAmMASg
1127
+ JnAB4BSgBKAcsAGAE5ABQCUABCAgIAAQMRAAEB4v/6AgEAAQHOABQBLwBAAPoAYAEvACECRABNA0Y
1128
+ AJAItAHgBKgAcAkQAUAEsAHQAygAgAi0AOQD3ADYA9wAWAaEANgGhABYCbAAlAYMAeAGDADkA6/9q
1129
+ AhsAFAIKABUB/QAVAAAAAwAAAAMAAAAcAAEAAAAAAKQAAwABAAAAHAAEAIgAAAAeABAAAwAOAH4Aq
1130
+ QCrALEAtAC3ALsgGSAdICYgOiBEISL7Av//AAAAIACpAKsAsAC0ALcAuyAYIBwgJiA5IEQhIvsB//
1131
+ //4/+5/7j/tP+y/7D/reBR4E/gR+A14CzfTwVxAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
1132
+ AAAAAAAEGAAABAAAAAAAAAAECAAAAAgAAAAAAAAAAAAAAAAAAAAEAAAMEBQYHCAkKCwwNDg8QERIT
1133
+ FBUWFxgZGhscHR4fICEiIyQlJicoKSorLC0uLzAxMjM0NTY3ODk6Ozw9Pj9AQUJDREVGR0hJSktMT
1134
+ U5PUFFSU1RVVldYWVpbXF1eX2BhAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGQAAA
1135
+ AAAAAAYnFmAAAAAABlAAAAAAAAAAAAAAAAAAAAAAAAAAAAY2htAAAAAAAAAABrbGlqAAAAAHAAbm9
1136
+ ycwBnAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAmACYAJgAmAD4AUgCCAMoBCgFO
1137
+ AVwBcgGIAaYBvAHKAdYB6AH2AgwCIAJKAogCpgLWAw4DIgNkA5wDugPUA+gD/AQQBEYEogS8BPoFJ
1138
+ gVSBWoFgAWwBcoF1gX6BhQGJAZMBmgGiga0BuIHGgdUB2YHkAeiB8AH3AfyCAoIHAgqCDoITghcCG
1139
+ oIogjSCPoJKglYCXwJwgnqCgIKKApACl4Klgq8CtwLDAs8C1YLjAuyC9oL7gwMDCYMSAxgDKAMrAz
1140
+ qDQoNTA1mDYQNoA2uDcAN2g3oDfYODA4iDkoOXA5sDnoOnA7EDvwAAAAFAAAAAAH0ArwAAwAGAAkA
1141
+ DAAPAAAxESERAxMhExcRASELARETAfT6qv6syKr+jgFUqsiqArz9RAGLAP/+1P8B/v3VAP8BLP4CA
1142
+ P8AAgA5//IAuQKyAAMACwAANyMDMwIyFhQGIiY0oE4MZk84JCQ4JLQB/v3AJDgkJDgAAgBWAeUBPA
1143
+ LfAAMABwAAEyMnMxcjJzOmRgpagkYKWgHl+vr6AAAAAAIARgAAAf4CsgAbAB8AAAEHMxUjByM3Iwc
1144
+ jNyM1MzcjNTM3MwczNzMHMxUrAQczAZgdZXEvOi9bLzovWmYdZXEvOi9bLzovWp9bHlsBn4w429vb
1145
+ 2ziMONvb29s4jAAAAAMANf+mAg4DDAAfACYALAAAJRQGBxUjNS4BJzMeARcRLgE0Njc1MxUeARcjJ
1146
+ icVHgEBFBYXNQ4BExU+ATU0Ag5xWDpgcgRcBz41Xl9oVTpVYwpcC1ttXP6cLTQuM5szOrVRZwlOTQ
1147
+ ZqVzZECAEAGlukZAlOTQdrUG8O7iNlAQgxNhDlCDj+8/YGOjReAAAAAAUAKf/yArsCvAAHAAsAFQA
1148
+ dACcAABIyFhQGIiY0EyMBMwQiBhUUFjI2NTQSMhYUBiImNDYiBhUUFjI2NTR5iFBQiFCVVwHAV/5c
1149
+ OiMjOiPmiFBQiFCxOiMjOiMCvFaSVlaS/ZoCsjIzMC80NC8w/uNWklZWkhozMC80NC8wAAAAAgBA/
1150
+ /ICbgLAACIALgAAARUjEQYjIiY1NDY3LgE1NDYzMhcVJiMiBhUUFhcWOwE1MxUFFBYzMjc1IyIHDg
1151
+ ECbmBcYYOOVkg7R4hsQjY4Q0RNRD4SLDxW/pJUXzksPCkUUk0BgUb+zBVUZ0BkDw5RO1huCkULQzp
1152
+ COAMBcHDHRz0J/AIHRQAAAAEAKwHlAIUC3wADAAATIycze0YKWgHl+gAAAAABAGT/sAEXAwwACQAA
1153
+ EzMGEBcjLgE0Nt06dXU6OUBAAwzG/jDGVePs4wAAAAEAHv+wANEDDAAJAAATMx4BFAYHIzYQHjo5Q
1154
+ EA5OnUDDFXj7ONVxgHQAAAAAQBVAFIB2wHbAA4AAAE3FwcXBycHJzcnNxcnMwEtmxOfcTJjYzJxnx
1155
+ ObCj4BKD07KYolmZkliik7PbMAAQBQAFUB9AIlAAsAAAEjFSM1IzUzNTMVMwH0tTq1tTq1AR/Kyjj
1156
+ OzgAAAAAB/+H/iACMAGQABAAANwcjNzOMWlFOXVrS3AAAAQAgAP8A8gE3AAMAABMjNTPy0tIA/zgA
1157
+ AQAl//IApQByAAcAADYyFhQGIiY0STgkJDgkciQ4JCQ4AAAAAf/7/+IBNALQAAMAABcjEzM5Pvs+H
1158
+ gLuAAAAAAIAKf/yAhsCwAADAAcAABIgECA2IBAgKQHy/g5gATL+zgLA/TJEAkYAAAAAAQCCAAABlg
1159
+ KyAAgAAAERIxEHNTc2MwGWVr6SIygCsv1OAldxW1sWAAEAPAAAAg4CwAAZAAA3IRUhNRM+ATU0JiM
1160
+ iDwEjNz4BMzIWFRQGB7kBUv4x+kI2QTt+EAFWAQp8aGVtSl5GRjEA/0RVLzlLmAoKa3FsUkNxXQAA
1161
+ AAEALf/yAhYCwAAqAAABHgEVFAYjIi8BMxceATMyNjU0KwE1MzI2NTQmIyIGDwEjNz4BMzIWFRQGA
1162
+ YxBSZJo2RUBVgEHV0JBUaQREUBUQzc5TQcBVgEKfGhfcEMBbxJbQl1x0AoKRkZHPn9GSD80QUVCCg
1163
+ pfbGBPOlgAAAACACEAAAIkArIACgAPAAAlIxUjNSE1ATMRMyMRBg8BAiRXVv6qAVZWV60dHLCurq4
1164
+ rAdn+QgFLMibzAAABADn/8gIZArIAHQAAATIWFRQGIyIvATMXFjMyNjU0JiMiByMTIRUhBzc2ATNv
1165
+ d5Fl1RQBVgIad0VSTkVhL1IwAYj+vh8rMAHHgGdtgcUKCoFXTU5bYgGRRvAuHQAAAAACACv/8gITA
1166
+ sAAFwAjAAABMhYVFAYjIhE0NjMyFh8BIycmIyIDNzYTMjY1NCYjIgYVFBYBLmp7imr0l3RZdAgBXA
1167
+ IYZ5wKJzU6QVNJSz5SUAHSgWltiQFGxcNlVQoKdv7sPiz+ZF1LTmJbU0lhAAAAAQAyAAACGgKyAAY
1168
+ AAAEVASMBITUCGv6oXAFL/oECsij9dgJsRgAAAAMALP/xAhgCwAAWACAALAAAAR4BFRQGIyImNTQ2
1169
+ Ny4BNTQ2MhYVFAYmIgYVFBYyNjU0AzI2NTQmIyIGFRQWAZQ5S5BmbIpPOjA7ecp5P2F8Q0J8RIVJS
1170
+ 0pLTEtOAW0TXTxpZ2ZqPF0SE1A3VWVlVTdQ/UU0N0RENzT9/ko+Ok1NOj1LAAIAMf/yAhkCwAAXAC
1171
+ MAAAEyERQGIyImLwEzFxYzMhMHBiMiJjU0NhMyNjU0JiMiBhUUFgEl9Jd0WXQIAVwCGGecCic1SWp
1172
+ 7imo+UlBAQVNJAsD+usXDZVUKCnYBFD4sgWltif5kW1NJYV1LTmIAAAACACX/8gClAiAABwAPAAAS
1173
+ MhYUBiImNBIyFhQGIiY0STgkJDgkJDgkJDgkAiAkOCQkOP52JDgkJDgAAAAC/+H/iAClAiAABwAMA
1174
+ AASMhYUBiImNBMHIzczSTgkJDgkaFpSTl4CICQ4JCQ4/mba5gAAAQBnAB4B+AH0AAYAAAENARUlNS
1175
+ UB+P6qAVb+bwGRAbCmpkbJRMkAAAIAUAC7AfQBuwADAAcAAAEhNSERITUhAfT+XAGk/lwBpAGDOP8
1176
+ AOAABAEQAHgHVAfQABgAAARUFNS0BNQHV/m8BVv6qAStEyUSmpkYAAAAAAgAj//IB1ALAABgAIAAA
1177
+ ATIWFRQHDgEHIz4BNz4BNTQmIyIGByM+ARIyFhQGIiY0AQRibmktIAJWBSEqNig+NTlHBFoDezQ4J
1178
+ CQ4JALAZ1BjaS03JS1DMD5LLDQ/SUVgcv2yJDgkJDgAAAAAAgA2/5gDFgKYADYAQgAAAQMGFRQzMj
1179
+ Y1NCYjIg4CFRQWMzI2NxcGIyImNTQ+AjMyFhUUBiMiJwcGIyImNTQ2MzIfATcHNzYmIyIGFRQzMjY
1180
+ Cej8EJjJJlnBAfGQ+oHtAhjUYg5OPx0h2k06Os3xRWQsVLjY5VHtdPBwJETcJDyUoOkZEJz8B0f74
1181
+ EQ8kZl6EkTFZjVOLlyknMVm1pmCiaTq4lX6CSCknTVRmmR8wPdYnQzxuSWVGAAIAHQAAAncCsgAHA
1182
+ AoAACUjByMTMxMjATMDAcj+UVz4dO5d/sjPZPT0ArL9TgE6ATQAAAADAGQAAAJMArIAEAAbACcAAA
1183
+ EeARUUBgcGKwERMzIXFhUUJRUzMjc2NTQnJiMTPgE1NCcmKwEVMzIBvkdHZkwiNt7LOSGq/oeFHBt
1184
+ hahIlSTM+cB8Yj5UWAW8QT0VYYgwFArIEF5Fv1eMED2NfDAL93AU+N24PBP0AAAAAAQAv//ICjwLA
1185
+ ABsAAAEyFh8BIycmIyIGFRQWMzI/ATMHDgEjIiY1NDYBdX+PCwFWAiKiaHx5ZaIiAlYBCpWBk6a0A
1186
+ sCAagoKpqN/gaOmCgplhcicn8sAAAIAZAAAAp8CsgAMABkAAAEeARUUBgcGKwERMzITPgE1NCYnJi
1187
+ sBETMyAY59lJp8IzXN0jUVWmdjWRs5d3I4Aq4QqJWUug8EArL9mQ+PeHGHDgX92gAAAAABAGQAAAI
1188
+ vArIACwAAJRUhESEVIRUhFSEVAi/+NQHB/pUBTf6zRkYCskbwRvAAAAABAGQAAAIlArIACQAAExUh
1189
+ FSERIxEhFboBQ/69VgHBAmzwRv7KArJGAAAAAAEAL//yAo8CwAAfAAABMxEjNQcGIyImNTQ2MzIWH
1190
+ wEjJyYjIgYVFBYzMjY1IwGP90wfPnWTprSSf48LAVYCIqJofHllVG+hAU3+s3hARsicn8uAagoKpq
1191
+ N/gaN1XAAAAAEAZAAAAowCsgALAAABESMRIREjETMRIRECjFb+hFZWAXwCsv1OAS7+0gKy/sQBPAA
1192
+ AAAABAGQAAAC6ArIAAwAAMyMRM7pWVgKyAAABADf/8gHoArIAEwAAAREUBw4BIyImLwEzFxYzMjc2
1193
+ NREB6AIFcGpgbQIBVgIHfXQKAQKy/lYxIltob2EpKYyEFD0BpwAAAAABAGQAAAJ0ArIACwAACQEjA
1194
+ wcVIxEzEQEzATsBJ3ntQlZWAVVlAWH+nwEnR+ACsv6RAW8AAQBkAAACLwKyAAUAACUVIREzEQIv/j
1195
+ VWRkYCsv2UAAABAGQAAAMUArIAFAAAAREjETQ3BgcDIwMmJxYVESMRMxsBAxRWAiMxemx8NxsCVo7
1196
+ MywKy/U4BY7ZLco7+nAFmoFxLtP6dArL9lwJpAAAAAAEAZAAAAoACsgANAAAhIwEWFREjETMBJjUR
1197
+ MwKAhP67A1aEAUUDVAJeeov+pwKy/aJ5jAFZAAAAAgAv//ICuwLAAAkAEwAAEiAWFRQGICY1NBIyN
1198
+ jU0JiIGFRTbATSsrP7MrNrYenrYegLAxaKhxsahov47nIeIm5uIhwACAGQAAAJHArIADgAYAAABHg
1199
+ EVFAYHBisBESMRMzITNjQnJisBETMyAZRUX2VOHzuAVtY7GlxcGDWIiDUCrgtnVlVpCgT+5gKy/rU
1200
+ V1BUF/vgAAAACAC//zAK9AsAAEgAcAAAlFhcHJiMiBwYjIiY1NDYgFhUUJRQWMjY1NCYiBgI9PUMx
1201
+ UDcfKh8omqysATSs/dR62Hp62HpICTg7NgkHxqGixcWitbWHnJyHiJubAAIAZAAAAlgCsgAXACMAA
1202
+ CUWFyMmJyYnJisBESMRMzIXHgEVFAYHFiUzMjc+ATU0JyYrAQIqDCJfGQwNWhAhglbiOx9QXEY1Tv
1203
+ 6bhDATMj1lGSyMtYgtOXR0BwH+1wKyBApbU0BSESRAAgVAOGoQBAABADT/8gIoAsAAJQAAATIWFyM
1204
+ uASMiBhUUFhceARUUBiMiJiczHgEzMjY1NCYnLgE1NDYBOmd2ClwGS0E6SUNRdW+HZnKKC1wPWkQ9
1205
+ Uk1cZGuEAsBwXUJHNjQ3OhIbZVZZbm5kREo+NT5DFRdYUFdrAAAAAAEAIgAAAmQCsgAHAAABIxEjE
1206
+ SM1IQJk9lb2AkICbP2UAmxGAAEAXv/yAmQCsgAXAAABERQHDgEiJicmNREzERQXHgEyNjc2NRECZA
1207
+ IIgfCBCAJWAgZYmlgGAgKy/k0qFFxzc1wUKgGz/lUrEkRQUEQSKwGrAAAAAAEAIAAAAnoCsgAGAAA
1208
+ hIwMzGwEzAYJ07l3N1FwCsv2PAnEAAAEAGgAAA7ECsgAMAAABAyMLASMDMxsBMxsBA7HAcZyicrZi
1209
+ kaB0nJkCsv1OAlP9rQKy/ZsCW/2kAmYAAAEAGQAAAm8CsgALAAAhCwEjEwMzGwEzAxMCCsrEY/bkY
1210
+ re+Y/D6AST+3AFcAVb+5gEa/q3+oQAAAQATAAACUQKyAAgAAAERIxEDMxsBMwFdVvRjwLphARD+8A
1211
+ EQAaL+sQFPAAABAC4AAAI5ArIACQAAJRUhNQEhNSEVAQI5/fUBof57Aen+YUZGQgIqRkX92QAAAAA
1212
+ BAGL/sAEFAwwABwAAARUjETMVIxEBBWlpowMMOP0UOANcAAAB//v/4gE0AtAAAwAABSMDMwE0Pvs+
1213
+ HgLuAAAAAQAi/7AAxQMMAAcAABcjNTMRIzUzxaNpaaNQOALsOAABAFAA1wH0AmgABgAAJQsBIxMzE
1214
+ wGwjY1GsESw1wFZ/qcBkf5vAAAAAQAy/6oBwv/iAAMAAAUhNSEBwv5wAZBWOAAAAAEAKQJEALYCsg
1215
+ ADAAATIycztjhVUAJEbgAAAAACACT/8gHQAiAAHQAlAAAhJwcGIyImNTQ2OwE1NCcmIyIHIz4BMzI
1216
+ XFh0BFBcnMjY9ASYVFAF6CR0wVUtgkJoiAgdgaQlaBm1Zrg4DCuQ9R+5MOSFQR1tbDiwUUXBUXowf
1217
+ J8c9SjRORzYSgVwAAAAAAgBK//ICRQLfABEAHgAAATIWFRQGIyImLwEVIxEzETc2EzI2NTQmIyIGH
1218
+ QEUFgFUcYCVbiNJEyNWVigySElcU01JXmECIJd4i5QTEDRJAt/+3jkq/hRuZV55ZWsdX14AAQAe//
1219
+ IB9wIgABgAAAEyFhcjJiMiBhUUFjMyNjczDgEjIiY1NDYBF152DFocbEJXU0A1Rw1aE3pbaoKQAiB
1220
+ oWH5qZm1tPDlaXYuLgZcAAAACAB7/8gIZAt8AEQAeAAABESM1BwYjIiY1NDYzMhYfAREDMjY9ATQm
1221
+ IyIGFRQWAhlWKDJacYCVbiNJEyOnSV5hQUlcUwLf/SFVOSqXeIuUExA0ARb9VWVrHV9ebmVeeQACA
1222
+ B7/8gH9AiAAFQAbAAABFAchHgEzMjY3Mw4BIyImNTQ2MzIWJyIGByEmAf0C/oAGUkA1SwlaD4FXbI
1223
+ WObmt45UBVBwEqDQEYFhNjWD84W16Oh3+akU9aU60AAAEAFQAAARoC8gAWAAATBh0BMxUjESMRIzU
1224
+ zNTQ3PgEzMhcVJqcDbW1WOTkDB0k8Hx5oAngVITRC/jQBzEIsJRs5PwVHEwAAAAIAHv8uAhkCIAAi
1225
+ AC8AAAERFAcOASMiLwEzFx4BMzI2NzY9AQcGIyImNTQ2MzIWHwE1AzI2PQE0JiMiBhUUFgIZAQSEd
1226
+ NwRAVcBBU5DTlUDASgyWnGAlW4jSRMjp0leYUFJXFMCEv5wSh1zeq8KCTI8VU0ZIQk5Kpd4i5QTED
1227
+ RJ/iJlax1fXm5lXnkAAQBKAAACCgLkABcAAAEWFREjETQnLgEHDgEdASMRMxE3NjMyFgIIAlYCBDs
1228
+ 6RVRWViE5UVViAYUbQP7WASQxGzI7AQJyf+kC5P7TPSxUAAACAD4AAACsAsAABwALAAASMhYUBiIm
1229
+ NBMjETNeLiAgLiBiVlYCwCAuICAu/WACEgAC//P/LgCnAsAABwAVAAASMhYUBiImNBcRFAcGIyInN
1230
+ RY3NjURWS4gIC4gYgMLcRwNSgYCAsAgLiAgLo79wCUbZAJGBzMOHgJEAAAAAQBKAAACCALfAAsAAC
1231
+ EnBxUjETMREzMHEwGTwTJWVvdu9/rgN6kC3/4oAQv6/ugAAQBG//wA3gLfAA8AABMRFBceATcVBiM
1232
+ iJicmNRGcAQIcIxkkKi4CAQLf/bkhERoSBD4EJC8SNAJKAAAAAQBKAAADEAIgACQAAAEWFREjETQn
1233
+ JiMiFREjETQnJiMiFREjETMVNzYzMhYXNzYzMhYDCwVWBAxedFYEDF50VlYiJko7ThAvJkpEVAGfI
1234
+ jn+vAEcQyRZ1v76ARxDJFnW/voCEk08HzYtRB9HAAAAAAEASgAAAgoCIAAWAAABFhURIxE0JyYjIg
1235
+ YdASMRMxU3NjMyFgIIAlYCCXBEVVZWITlRVWIBhRtA/tYBJDEbbHR/6QISWz0sVAAAAAACAB7/8gI
1236
+ sAiAABwARAAASIBYUBiAmNBIyNjU0JiIGFRSlAQCHh/8Ah7ieWlqeWgIgn/Cfn/D+s3ZfYHV1YF8A
1237
+ AgBK/zwCRQIgABEAHgAAATIWFRQGIyImLwERIxEzFTc2EzI2NTQmIyIGHQEUFgFUcYCVbiNJEyNWV
1238
+ igySElcU01JXmECIJd4i5QTEDT+8wLWVTkq/hRuZV55ZWsdX14AAgAe/zwCGQIgABEAHgAAAREjEQ
1239
+ cGIyImNTQ2MzIWHwE1AzI2PQE0JiMiBhUUFgIZVigyWnGAlW4jSRMjp0leYUFJXFMCEv0qARk5Kpd
1240
+ 4i5QTEDRJ/iJlax1fXm5lXnkAAQBKAAABPgIeAA0AAAEyFxUmBhURIxEzFTc2ARoWDkdXVlYwIwIe
1241
+ B0EFVlf+0gISU0cYAAEAGP/yAa0CIAAjAAATMhYXIyYjIgYVFBYXHgEVFAYjIiYnMxYzMjY1NCYnL
1242
+ gE1NDbkV2MJWhNdKy04PF1XbVhWbgxaE2ktOjlEUllkAiBaS2MrJCUoEBlPQkhOVFZoKCUmLhIWSE
1243
+ BIUwAAAAEAFP/4ARQCiQAXAAATERQXHgE3FQYjIiYnJjURIzUzNTMVMxWxAQMmMx8qMjMEAUdHVmM
1244
+ BzP7PGw4mFgY/BSwxDjQBNUJ7e0IAAAABAEL/8gICAhIAFwAAAREjNQcGIyImJyY1ETMRFBceATMy
1245
+ Nj0BAgJWITlRT2EKBVYEBkA1RFECEv3uWj4qTToiOQE+/tIlJC43c4DpAAAAAAEAAQAAAfwCEgAGA
1246
+ AABAyMDMxsBAfzJaclfop8CEv3uAhL+LQHTAAABAAEAAAMLAhIADAAAAQMjCwEjAzMbATMbAQMLqW
1247
+ Z2dmapY3t0a3Z7AhL97gG+/kICEv5AAcD+QwG9AAAB//oAAAHWAhIACwAAARMjJwcjEwMzFzczARq
1248
+ 8ZIuKY763ZoWFYwEO/vLV1QEMAQbNzQAAAQAB/y4B+wISABEAAAEDDgEjIic1FjMyNj8BAzMbAQH7
1249
+ 2iFZQB8NDRIpNhQH02GenQIS/cFVUAJGASozEwIt/i4B0gABABQAAAGxAg4ACQAAJRUhNQEhNSEVA
1250
+ QGx/mMBNP7iAYL+zkREQgGIREX+ewAAAAABAED/sAEOAwwALAAAASMiBhUUFxYVFAYHHgEVFAcGFR
1251
+ QWOwEVIyImNTQ3NjU0JzU2NTQnJjU0NjsBAQ4MKiMLDS4pKS4NCyMqDAtERAwLUlILDERECwLUGBk
1252
+ WTlsgKzUFBTcrIFtOFhkYOC87GFVMIkUIOAhFIkxVGDsvAAAAAAEAYP84AJoDIAADAAAXIxEzmjo6
1253
+ yAPoAAEAIf+wAO8DDAAsAAATFQYVFBcWFRQGKwE1MzI2NTQnJjU0NjcuATU0NzY1NCYrATUzMhYVF
1254
+ AcGFRTvUgsMREQLDCojCw0uKSkuDQsjKgwLREQMCwF6OAhFIkxVGDsvOBgZFk5bICs1BQU3KyBbTh
1255
+ YZGDgvOxhVTCJFAAABAE0A3wH2AWQAEwAAATMUIyImJyYjIhUjNDMyFhcWMzIBvjhuGywtQR0xOG4
1256
+ bLC1BHTEBZIURGCNMhREYIwAAAwAk/94DIgLoAAcAEQApAAAAIBYQBiAmECQgBhUUFiA2NTQlMhYX
1257
+ IyYjIgYUFjMyNjczDgEjIiY1NDYBAQFE3d3+vN0CB/7wubkBELn+xVBnD1wSWDo+QTcqOQZcEmZWX
1258
+ HN2Aujg/rbg4AFKpr+Mjb6+jYxbWEldV5ZZNShLVn5na34AAgB4AFIB9AGeAAUACwAAAQcXIyc3Mw
1259
+ cXIyc3AUqJiUmJifOJiUmJiQGepqampqampqYAAAIAHAHSAQ4CwAAHAA8AABIyFhQGIiY0NiIGFBY
1260
+ yNjRgakREakSTNCEhNCECwEJqQkJqCiM4IyM4AAAAAAIAUAAAAfQCCwALAA8AAAEzFSMVIzUjNTM1
1261
+ MxMhNSEBP7W1OrW1OrX+XAGkAVs4tLQ4sP31OAAAAQB0AkQBAQKyAAMAABMjNzOsOD1QAkRuAAAAA
1262
+ AEAIADsAKoBdgAHAAASMhYUBiImNEg6KCg6KAF2KDooKDoAAAIAOQBSAbUBngAFAAsAACUHIzcnMw
1263
+ UHIzcnMwELiUmJiUkBM4lJiYlJ+KampqampqYAAAABADYB5QDhAt8ABAAAEzczByM2Xk1OXQHv8Po
1264
+ AAQAWAeUAwQLfAAQAABMHIzczwV5NTl0C1fD6AAIANgHlAYsC3wAEAAkAABM3MwcjPwEzByM2Xk1O
1265
+ XapeTU5dAe/w+grw+gAAAgAWAeUBawLfAAQACQAAEwcjNzMXByM3M8FeTU5dql5NTl0C1fD6CvD6A
1266
+ AADACX/8gI1AHIABwAPABcAADYyFhQGIiY0NjIWFAYiJjQ2MhYUBiImNEk4JCQ4JOw4JCQ4JOw4JC
1267
+ Q4JHIkOCQkOCQkOCQkOCQkOCQkOAAAAAEAeABSAUoBngAFAAABBxcjJzcBSomJSYmJAZ6mpqamAAA
1268
+ AAAEAOQBSAQsBngAFAAAlByM3JzMBC4lJiYlJ+KampgAAAf9qAAABgQKyAAMAACsBATM/VwHAVwKy
1269
+ AAAAAAIAFAHIAdwClAAHABQAABMVIxUjNSM1BRUjNwcjJxcjNTMXN9pKMkoByDICKzQqATJLKysCl
1270
+ CmjoykBy46KiY3Lm5sAAQAVAAABvALyABgAAAERIxEjESMRIzUzNTQ3NjMyFxUmBgcGHQEBvFbCVj
1271
+ k5AxHHHx5iVgcDAg798gHM/jQBzEIOJRuWBUcIJDAVIRYAAAABABX//AHkAvIAJQAAJR4BNxUGIyI
1272
+ mJyY1ESYjIgcGHQEzFSMRIxEjNTM1NDc2MzIXERQBowIcIxkkKi4CAR4nXgwDbW1WLy8DEbNdOmYa
1273
+ EQQ/BCQvEjQCFQZWFSEWQv40AcxCDiUblhP9uSEAAAAAAAAWAQ4AAQAAAAAAAAATACgAAQAAAAAAA
1274
+ QAHAEwAAQAAAAAAAgAHAGQAAQAAAAAAAwAaAKIAAQAAAAAABAAHAM0AAQAAAAAABQA8AU8AAQAAAA
1275
+ AABgAPAawAAQAAAAAACAALAdQAAQAAAAAACQALAfgAAQAAAAAACwAXAjQAAQAAAAAADAAXAnwAAwA
1276
+ BBAkAAAAmAAAAAwABBAkAAQAOADwAAwABBAkAAgAOAFQAAwABBAkAAwA0AGwAAwABBAkABAAOAL0A
1277
+ AwABBAkABQB4ANUAAwABBAkABgAeAYwAAwABBAkACAAWAbwAAwABBAkACQAWAeAAAwABBAkACwAuA
1278
+ gQAAwABBAkADAAuAkwATgBvACAAUgBpAGcAaAB0AHMAIABSAGUAcwBlAHIAdgBlAGQALgAATm8gUm
1279
+ lnaHRzIFJlc2VydmVkLgAAQQBpAGwAZQByAG8AbgAAQWlsZXJvbgAAUgBlAGcAdQBsAGEAcgAAUmV
1280
+ ndWxhcgAAMQAuADEAMAAyADsAVQBLAFcATgA7AEEAaQBsAGUAcgBvAG4ALQBSAGUAZwB1AGwAYQBy
1281
+ AAAxLjEwMjtVS1dOO0FpbGVyb24tUmVndWxhcgAAQQBpAGwAZQByAG8AbgAAQWlsZXJvbgAAVgBlA
1282
+ HIAcwBpAG8AbgAgADEALgAxADAAMgA7AFAAUwAgADAAMAAxAC4AMQAwADIAOwBoAG8AdABjAG8Abg
1283
+ B2ACAAMQAuADAALgA3ADAAOwBtAGEAawBlAG8AdABmAC4AbABpAGIAMgAuADUALgA1ADgAMwAyADk
1284
+ AAFZlcnNpb24gMS4xMDI7UFMgMDAxLjEwMjtob3Rjb252IDEuMC43MDttYWtlb3RmLmxpYjIuNS41
1285
+ ODMyOQAAQQBpAGwAZQByAG8AbgAtAFIAZQBnAHUAbABhAHIAAEFpbGVyb24tUmVndWxhcgAAUwBvA
1286
+ HIAYQAgAFMAYQBnAGEAbgBvAABTb3JhIFNhZ2FubwAAUwBvAHIAYQAgAFMAYQBnAGEAbgBvAABTb3
1287
+ JhIFNhZ2FubwAAaAB0AHQAcAA6AC8ALwB3AHcAdwAuAGQAbwB0AGMAbwBsAG8AbgAuAG4AZQB0AAB
1288
+ odHRwOi8vd3d3LmRvdGNvbG9uLm5ldAAAaAB0AHQAcAA6AC8ALwB3AHcAdwAuAGQAbwB0AGMAbwBs
1289
+ AG8AbgAuAG4AZQB0AABodHRwOi8vd3d3LmRvdGNvbG9uLm5ldAAAAAACAAAAAAAA/4MAMgAAAAAAA
1290
+ AAAAAAAAAAAAAAAAAAAAHQAAAABAAIAAwAEAAUABgAHAAgACQAKAAsADAANAA4ADwAQABEAEgATAB
1291
+ QAFQAWABcAGAAZABoAGwAcAB0AHgAfACAAIQAiACMAJAAlACYAJwAoACkAKgArACwALQAuAC8AMAA
1292
+ xADIAMwA0ADUANgA3ADgAOQA6ADsAPAA9AD4APwBAAEEAQgBDAEQARQBGAEcASABJAEoASwBMAE0A
1293
+ TgBPAFAAUQBSAFMAVABVAFYAVwBYAFkAWgBbAFwAXQBeAF8AYABhAIsAqQCDAJMAjQDDAKoAtgC3A
1294
+ LQAtQCrAL4AvwC8AIwAwADBAAAAAAAB//8AAgABAAAADAAAABwAAAACAAIAAwBxAAEAcgBzAAIABA
1295
+ AAAAIAAAABAAAACgBMAGYAAkRGTFQADmxhdG4AGgAEAAAAAP//AAEAAAAWAANDQVQgAB5NT0wgABZ
1296
+ ST00gABYAAP//AAEAAAAA//8AAgAAAAEAAmxpZ2EADmxvY2wAFAAAAAEAAQAAAAEAAAACAAYAEAAG
1297
+ AAAAAgASADQABAAAAAEATAADAAAAAgAQABYAAQAcAAAAAQABAE8AAQABAGcAAQABAE8AAwAAAAIAE
1298
+ AAWAAEAHAAAAAEAAQAvAAEAAQBnAAEAAQAvAAEAGgABAAgAAgAGAAwAcwACAE8AcgACAEwAAQABAE
1299
+ kAAAABAAAACgBGAGAAAkRGTFQADmxhdG4AHAAEAAAAAP//AAIAAAABABYAA0NBVCAAFk1PTCAAFlJ
1300
+ PTSAAFgAA//8AAgAAAAEAAmNwc3AADmtlcm4AFAAAAAEAAAAAAAEAAQACAAYADgABAAAAAQASAAIA
1301
+ AAACAB4ANgABAAoABQAFAAoAAgABACQAPQAAAAEAEgAEAAAAAQAMAAEAOP/nAAEAAQAkAAIGigAEA
1302
+ AAFJAXKABoAGQAA//gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
1303
+ AAAAD/sv+4/+z/7v/MAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
1304
+ AAAAAAAD/xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/9T/6AAAAAD/8QAA
1305
+ ABD/vQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/7gAAAAAAAAAAAAAAAAAA//MAA
1306
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABIAAAAAAAAAAP/5AAAAAAAAAA
1307
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP/gAAD/4AAAAAAAAAAAAAAAAAA
1308
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//L/9AAAAAAAAAAAAAAAAAAAAAAA
1309
+ AAAAAAAAAAAA/+gAAAAAAAkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
1310
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP/zAAAAAA
1311
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP/mAAAAAAAAAAAAAAAAAAD
1312
+ /4gAA//AAAAAA//YAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/+AAAAAAAAP/OAAAAAAAAAAAAAAAA
1313
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/zv/qAAAAAP/0AAAACAAAAAAAAAAAAAAAAAAAAAAAA
1314
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP/ZAAD/egAA/1kAAAAA/5D/rgAAAAAAAAAAAA
1315
+ AAAAAAAAAAAAAAAAD/9AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
1316
+ AAAAAAAAAAAAAAAAAAAD/8AAA/7b/8P+wAAD/8P/E/98AAAAA/8P/+P/0//oAAAAAAAAAAAAA//gA
1317
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/+AAAAAAAAAAAAAAA
1318
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/w//C/9MAAP/SAAD/9wAAAAAAAA
1319
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAD/yAAA/+kAAAAA//QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
1320
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/9wAAAAD//QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
1321
+ AAAAAAAAAAAAAAAAAAAAAP/2AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
1322
+ AAAAAAAAP/cAAAAAAAAAAAAAAAA/7YAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
1323
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAP/8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/6AAAAAAAAAA
1324
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAkAFAAEAAAAAQACwAAABcA
1325
+ BgAAAAAAAAAIAA4AAAAAAAsAEgAAAAAAAAATABkAAwANAAAAAQAJAAAAAAAAAAAAAAAAAAAAGAAAA
1326
+ AAABwAAAAAAAAAAAAAAFQAFAAAAAAAYABgAAAAUAAAACgAAAAwAAgAPABEAFgAAAAAAAAAAAAAAAA
1327
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAEAEQBdAAYAAAAAAAAAAAAAAAAAAAAAAAA
1328
+ AAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAcAAAAAAAAABwAAAAAACAAAAAAAAAAAAAcAAAAHAAAAEwAJ
1329
+ ABUADgAPAAAACwAQAAAAAAAAAAAAAAAAAAUAGAACAAIAAgAAAAIAGAAXAAAAGAAAABYAFgACABYAA
1330
+ gAWAAAAEQADAAoAFAAMAA0ABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASAAAAEgAGAAEAHgAkAC
1331
+ YAJwApACoALQAuAC8AMgAzADcAOAA5ADoAPAA9AEUASABOAE8AUgBTAFUAVwBZAFoAWwBcAF0AcwA
1332
+ AAAAAAQAAAADa3tfFAAAAANAan9kAAAAA4QodoQ==
1333
+ """
1334
+ )
1335
+ ),
1336
+ 10 if size is None else size,
1337
+ layout_engine=Layout.BASIC,
1338
+ )
1339
+ return load_default_imagefont()
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/ImageGrab.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library
3
+ # $Id$
4
+ #
5
+ # screen grabber
6
+ #
7
+ # History:
8
+ # 2001-04-26 fl created
9
+ # 2001-09-17 fl use builtin driver, if present
10
+ # 2002-11-19 fl added grabclipboard support
11
+ #
12
+ # Copyright (c) 2001-2002 by Secret Labs AB
13
+ # Copyright (c) 2001-2002 by Fredrik Lundh
14
+ #
15
+ # See the README file for information on usage and redistribution.
16
+ #
17
+ from __future__ import annotations
18
+
19
+ import io
20
+ import os
21
+ import shutil
22
+ import subprocess
23
+ import sys
24
+ import tempfile
25
+
26
+ from . import Image
27
+
28
+ TYPE_CHECKING = False
29
+ if TYPE_CHECKING:
30
+ from . import ImageWin
31
+
32
+
33
+ def grab(
34
+ bbox: tuple[int, int, int, int] | None = None,
35
+ include_layered_windows: bool = False,
36
+ all_screens: bool = False,
37
+ xdisplay: str | None = None,
38
+ window: int | ImageWin.HWND | None = None,
39
+ ) -> Image.Image:
40
+ im: Image.Image
41
+ if xdisplay is None:
42
+ if sys.platform == "darwin":
43
+ fh, filepath = tempfile.mkstemp(".png")
44
+ os.close(fh)
45
+ args = ["screencapture"]
46
+ if bbox:
47
+ left, top, right, bottom = bbox
48
+ args += ["-R", f"{left},{top},{right-left},{bottom-top}"]
49
+ subprocess.call(args + ["-x", filepath])
50
+ im = Image.open(filepath)
51
+ im.load()
52
+ os.unlink(filepath)
53
+ if bbox:
54
+ im_resized = im.resize((right - left, bottom - top))
55
+ im.close()
56
+ return im_resized
57
+ return im
58
+ elif sys.platform == "win32":
59
+ if window is not None:
60
+ all_screens = -1
61
+ offset, size, data = Image.core.grabscreen_win32(
62
+ include_layered_windows,
63
+ all_screens,
64
+ int(window) if window is not None else 0,
65
+ )
66
+ im = Image.frombytes(
67
+ "RGB",
68
+ size,
69
+ data,
70
+ # RGB, 32-bit line padding, origin lower left corner
71
+ "raw",
72
+ "BGR",
73
+ (size[0] * 3 + 3) & -4,
74
+ -1,
75
+ )
76
+ if bbox:
77
+ x0, y0 = offset
78
+ left, top, right, bottom = bbox
79
+ im = im.crop((left - x0, top - y0, right - x0, bottom - y0))
80
+ return im
81
+ # Cast to Optional[str] needed for Windows and macOS.
82
+ display_name: str | None = xdisplay
83
+ try:
84
+ if not Image.core.HAVE_XCB:
85
+ msg = "Pillow was built without XCB support"
86
+ raise OSError(msg)
87
+ size, data = Image.core.grabscreen_x11(display_name)
88
+ except OSError:
89
+ if display_name is None and sys.platform not in ("darwin", "win32"):
90
+ if shutil.which("gnome-screenshot"):
91
+ args = ["gnome-screenshot", "-f"]
92
+ elif shutil.which("grim"):
93
+ args = ["grim"]
94
+ elif shutil.which("spectacle"):
95
+ args = ["spectacle", "-n", "-b", "-f", "-o"]
96
+ else:
97
+ raise
98
+ fh, filepath = tempfile.mkstemp(".png")
99
+ os.close(fh)
100
+ subprocess.call(args + [filepath])
101
+ im = Image.open(filepath)
102
+ im.load()
103
+ os.unlink(filepath)
104
+ if bbox:
105
+ im_cropped = im.crop(bbox)
106
+ im.close()
107
+ return im_cropped
108
+ return im
109
+ else:
110
+ raise
111
+ else:
112
+ im = Image.frombytes("RGB", size, data, "raw", "BGRX", size[0] * 4, 1)
113
+ if bbox:
114
+ im = im.crop(bbox)
115
+ return im
116
+
117
+
118
+ def grabclipboard() -> Image.Image | list[str] | None:
119
+ if sys.platform == "darwin":
120
+ p = subprocess.run(
121
+ ["osascript", "-e", "get the clipboard as «class PNGf»"],
122
+ capture_output=True,
123
+ )
124
+ if p.returncode != 0:
125
+ return None
126
+
127
+ import binascii
128
+
129
+ data = io.BytesIO(binascii.unhexlify(p.stdout[11:-3]))
130
+ return Image.open(data)
131
+ elif sys.platform == "win32":
132
+ fmt, data = Image.core.grabclipboard_win32()
133
+ if fmt == "file": # CF_HDROP
134
+ import struct
135
+
136
+ o = struct.unpack_from("I", data)[0]
137
+ if data[16] == 0:
138
+ files = data[o:].decode("mbcs").split("\0")
139
+ else:
140
+ files = data[o:].decode("utf-16le").split("\0")
141
+ return files[: files.index("")]
142
+ if isinstance(data, bytes):
143
+ data = io.BytesIO(data)
144
+ if fmt == "png":
145
+ from . import PngImagePlugin
146
+
147
+ return PngImagePlugin.PngImageFile(data)
148
+ elif fmt == "DIB":
149
+ from . import BmpImagePlugin
150
+
151
+ return BmpImagePlugin.DibImageFile(data)
152
+ return None
153
+ else:
154
+ if os.getenv("WAYLAND_DISPLAY"):
155
+ session_type = "wayland"
156
+ elif os.getenv("DISPLAY"):
157
+ session_type = "x11"
158
+ else: # Session type check failed
159
+ session_type = None
160
+
161
+ if shutil.which("wl-paste") and session_type in ("wayland", None):
162
+ args = ["wl-paste", "-t", "image"]
163
+ elif shutil.which("xclip") and session_type in ("x11", None):
164
+ args = ["xclip", "-selection", "clipboard", "-t", "image/png", "-o"]
165
+ else:
166
+ msg = "wl-paste or xclip is required for ImageGrab.grabclipboard() on Linux"
167
+ raise NotImplementedError(msg)
168
+
169
+ p = subprocess.run(args, capture_output=True)
170
+ if p.returncode != 0:
171
+ err = p.stderr
172
+ for silent_error in [
173
+ # wl-paste, when the clipboard is empty
174
+ b"Nothing is copied",
175
+ # Ubuntu/Debian wl-paste, when the clipboard is empty
176
+ b"No selection",
177
+ # Ubuntu/Debian wl-paste, when an image isn't available
178
+ b"No suitable type of content copied",
179
+ # wl-paste or Ubuntu/Debian xclip, when an image isn't available
180
+ b" not available",
181
+ # xclip, when an image isn't available
182
+ b"cannot convert ",
183
+ # xclip, when the clipboard isn't initialized
184
+ b"xclip: Error: There is no owner for the ",
185
+ ]:
186
+ if silent_error in err:
187
+ return None
188
+ msg = f"{args[0]} error"
189
+ if err:
190
+ msg += f": {err.strip().decode()}"
191
+ raise ChildProcessError(msg)
192
+
193
+ data = io.BytesIO(p.stdout)
194
+ im = Image.open(data)
195
+ im.load()
196
+ return im
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/ImageMath.py ADDED
@@ -0,0 +1,368 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library
3
+ # $Id$
4
+ #
5
+ # a simple math add-on for the Python Imaging Library
6
+ #
7
+ # History:
8
+ # 1999-02-15 fl Original PIL Plus release
9
+ # 2005-05-05 fl Simplified and cleaned up for PIL 1.1.6
10
+ # 2005-09-12 fl Fixed int() and float() for Python 2.4.1
11
+ #
12
+ # Copyright (c) 1999-2005 by Secret Labs AB
13
+ # Copyright (c) 2005 by Fredrik Lundh
14
+ #
15
+ # See the README file for information on usage and redistribution.
16
+ #
17
+ from __future__ import annotations
18
+
19
+ import builtins
20
+ from types import CodeType
21
+ from typing import Any, Callable
22
+
23
+ from . import Image, _imagingmath
24
+ from ._deprecate import deprecate
25
+
26
+
27
+ class _Operand:
28
+ """Wraps an image operand, providing standard operators"""
29
+
30
+ def __init__(self, im: Image.Image):
31
+ self.im = im
32
+
33
+ def __fixup(self, im1: _Operand | float) -> Image.Image:
34
+ # convert image to suitable mode
35
+ if isinstance(im1, _Operand):
36
+ # argument was an image.
37
+ if im1.im.mode in ("1", "L"):
38
+ return im1.im.convert("I")
39
+ elif im1.im.mode in ("I", "F"):
40
+ return im1.im
41
+ else:
42
+ msg = f"unsupported mode: {im1.im.mode}"
43
+ raise ValueError(msg)
44
+ else:
45
+ # argument was a constant
46
+ if isinstance(im1, (int, float)) and self.im.mode in ("1", "L", "I"):
47
+ return Image.new("I", self.im.size, im1)
48
+ else:
49
+ return Image.new("F", self.im.size, im1)
50
+
51
+ def apply(
52
+ self,
53
+ op: str,
54
+ im1: _Operand | float,
55
+ im2: _Operand | float | None = None,
56
+ mode: str | None = None,
57
+ ) -> _Operand:
58
+ im_1 = self.__fixup(im1)
59
+ if im2 is None:
60
+ # unary operation
61
+ out = Image.new(mode or im_1.mode, im_1.size, None)
62
+ try:
63
+ op = getattr(_imagingmath, f"{op}_{im_1.mode}")
64
+ except AttributeError as e:
65
+ msg = f"bad operand type for '{op}'"
66
+ raise TypeError(msg) from e
67
+ _imagingmath.unop(op, out.getim(), im_1.getim())
68
+ else:
69
+ # binary operation
70
+ im_2 = self.__fixup(im2)
71
+ if im_1.mode != im_2.mode:
72
+ # convert both arguments to floating point
73
+ if im_1.mode != "F":
74
+ im_1 = im_1.convert("F")
75
+ if im_2.mode != "F":
76
+ im_2 = im_2.convert("F")
77
+ if im_1.size != im_2.size:
78
+ # crop both arguments to a common size
79
+ size = (
80
+ min(im_1.size[0], im_2.size[0]),
81
+ min(im_1.size[1], im_2.size[1]),
82
+ )
83
+ if im_1.size != size:
84
+ im_1 = im_1.crop((0, 0) + size)
85
+ if im_2.size != size:
86
+ im_2 = im_2.crop((0, 0) + size)
87
+ out = Image.new(mode or im_1.mode, im_1.size, None)
88
+ try:
89
+ op = getattr(_imagingmath, f"{op}_{im_1.mode}")
90
+ except AttributeError as e:
91
+ msg = f"bad operand type for '{op}'"
92
+ raise TypeError(msg) from e
93
+ _imagingmath.binop(op, out.getim(), im_1.getim(), im_2.getim())
94
+ return _Operand(out)
95
+
96
+ # unary operators
97
+ def __bool__(self) -> bool:
98
+ # an image is "true" if it contains at least one non-zero pixel
99
+ return self.im.getbbox() is not None
100
+
101
+ def __abs__(self) -> _Operand:
102
+ return self.apply("abs", self)
103
+
104
+ def __pos__(self) -> _Operand:
105
+ return self
106
+
107
+ def __neg__(self) -> _Operand:
108
+ return self.apply("neg", self)
109
+
110
+ # binary operators
111
+ def __add__(self, other: _Operand | float) -> _Operand:
112
+ return self.apply("add", self, other)
113
+
114
+ def __radd__(self, other: _Operand | float) -> _Operand:
115
+ return self.apply("add", other, self)
116
+
117
+ def __sub__(self, other: _Operand | float) -> _Operand:
118
+ return self.apply("sub", self, other)
119
+
120
+ def __rsub__(self, other: _Operand | float) -> _Operand:
121
+ return self.apply("sub", other, self)
122
+
123
+ def __mul__(self, other: _Operand | float) -> _Operand:
124
+ return self.apply("mul", self, other)
125
+
126
+ def __rmul__(self, other: _Operand | float) -> _Operand:
127
+ return self.apply("mul", other, self)
128
+
129
+ def __truediv__(self, other: _Operand | float) -> _Operand:
130
+ return self.apply("div", self, other)
131
+
132
+ def __rtruediv__(self, other: _Operand | float) -> _Operand:
133
+ return self.apply("div", other, self)
134
+
135
+ def __mod__(self, other: _Operand | float) -> _Operand:
136
+ return self.apply("mod", self, other)
137
+
138
+ def __rmod__(self, other: _Operand | float) -> _Operand:
139
+ return self.apply("mod", other, self)
140
+
141
+ def __pow__(self, other: _Operand | float) -> _Operand:
142
+ return self.apply("pow", self, other)
143
+
144
+ def __rpow__(self, other: _Operand | float) -> _Operand:
145
+ return self.apply("pow", other, self)
146
+
147
+ # bitwise
148
+ def __invert__(self) -> _Operand:
149
+ return self.apply("invert", self)
150
+
151
+ def __and__(self, other: _Operand | float) -> _Operand:
152
+ return self.apply("and", self, other)
153
+
154
+ def __rand__(self, other: _Operand | float) -> _Operand:
155
+ return self.apply("and", other, self)
156
+
157
+ def __or__(self, other: _Operand | float) -> _Operand:
158
+ return self.apply("or", self, other)
159
+
160
+ def __ror__(self, other: _Operand | float) -> _Operand:
161
+ return self.apply("or", other, self)
162
+
163
+ def __xor__(self, other: _Operand | float) -> _Operand:
164
+ return self.apply("xor", self, other)
165
+
166
+ def __rxor__(self, other: _Operand | float) -> _Operand:
167
+ return self.apply("xor", other, self)
168
+
169
+ def __lshift__(self, other: _Operand | float) -> _Operand:
170
+ return self.apply("lshift", self, other)
171
+
172
+ def __rshift__(self, other: _Operand | float) -> _Operand:
173
+ return self.apply("rshift", self, other)
174
+
175
+ # logical
176
+ def __eq__(self, other: _Operand | float) -> _Operand: # type: ignore[override]
177
+ return self.apply("eq", self, other)
178
+
179
+ def __ne__(self, other: _Operand | float) -> _Operand: # type: ignore[override]
180
+ return self.apply("ne", self, other)
181
+
182
+ def __lt__(self, other: _Operand | float) -> _Operand:
183
+ return self.apply("lt", self, other)
184
+
185
+ def __le__(self, other: _Operand | float) -> _Operand:
186
+ return self.apply("le", self, other)
187
+
188
+ def __gt__(self, other: _Operand | float) -> _Operand:
189
+ return self.apply("gt", self, other)
190
+
191
+ def __ge__(self, other: _Operand | float) -> _Operand:
192
+ return self.apply("ge", self, other)
193
+
194
+
195
+ # conversions
196
+ def imagemath_int(self: _Operand) -> _Operand:
197
+ return _Operand(self.im.convert("I"))
198
+
199
+
200
+ def imagemath_float(self: _Operand) -> _Operand:
201
+ return _Operand(self.im.convert("F"))
202
+
203
+
204
+ # logical
205
+ def imagemath_equal(self: _Operand, other: _Operand | float | None) -> _Operand:
206
+ return self.apply("eq", self, other, mode="I")
207
+
208
+
209
+ def imagemath_notequal(self: _Operand, other: _Operand | float | None) -> _Operand:
210
+ return self.apply("ne", self, other, mode="I")
211
+
212
+
213
+ def imagemath_min(self: _Operand, other: _Operand | float | None) -> _Operand:
214
+ return self.apply("min", self, other)
215
+
216
+
217
+ def imagemath_max(self: _Operand, other: _Operand | float | None) -> _Operand:
218
+ return self.apply("max", self, other)
219
+
220
+
221
+ def imagemath_convert(self: _Operand, mode: str) -> _Operand:
222
+ return _Operand(self.im.convert(mode))
223
+
224
+
225
+ ops = {
226
+ "int": imagemath_int,
227
+ "float": imagemath_float,
228
+ "equal": imagemath_equal,
229
+ "notequal": imagemath_notequal,
230
+ "min": imagemath_min,
231
+ "max": imagemath_max,
232
+ "convert": imagemath_convert,
233
+ }
234
+
235
+
236
+ def lambda_eval(
237
+ expression: Callable[[dict[str, Any]], Any],
238
+ options: dict[str, Any] = {},
239
+ **kw: Any,
240
+ ) -> Any:
241
+ """
242
+ Returns the result of an image function.
243
+
244
+ :py:mod:`~PIL.ImageMath` only supports single-layer images. To process multi-band
245
+ images, use the :py:meth:`~PIL.Image.Image.split` method or
246
+ :py:func:`~PIL.Image.merge` function.
247
+
248
+ :param expression: A function that receives a dictionary.
249
+ :param options: Values to add to the function's dictionary. Deprecated.
250
+ You can instead use one or more keyword arguments.
251
+ :param **kw: Values to add to the function's dictionary.
252
+ :return: The expression result. This is usually an image object, but can
253
+ also be an integer, a floating point value, or a pixel tuple,
254
+ depending on the expression.
255
+ """
256
+
257
+ if options:
258
+ deprecate(
259
+ "ImageMath.lambda_eval options",
260
+ 12,
261
+ "ImageMath.lambda_eval keyword arguments",
262
+ )
263
+
264
+ args: dict[str, Any] = ops.copy()
265
+ args.update(options)
266
+ args.update(kw)
267
+ for k, v in args.items():
268
+ if isinstance(v, Image.Image):
269
+ args[k] = _Operand(v)
270
+
271
+ out = expression(args)
272
+ try:
273
+ return out.im
274
+ except AttributeError:
275
+ return out
276
+
277
+
278
+ def unsafe_eval(
279
+ expression: str,
280
+ options: dict[str, Any] = {},
281
+ **kw: Any,
282
+ ) -> Any:
283
+ """
284
+ Evaluates an image expression. This uses Python's ``eval()`` function to process
285
+ the expression string, and carries the security risks of doing so. It is not
286
+ recommended to process expressions without considering this.
287
+ :py:meth:`~lambda_eval` is a more secure alternative.
288
+
289
+ :py:mod:`~PIL.ImageMath` only supports single-layer images. To process multi-band
290
+ images, use the :py:meth:`~PIL.Image.Image.split` method or
291
+ :py:func:`~PIL.Image.merge` function.
292
+
293
+ :param expression: A string containing a Python-style expression.
294
+ :param options: Values to add to the evaluation context. Deprecated.
295
+ You can instead use one or more keyword arguments.
296
+ :param **kw: Values to add to the evaluation context.
297
+ :return: The evaluated expression. This is usually an image object, but can
298
+ also be an integer, a floating point value, or a pixel tuple,
299
+ depending on the expression.
300
+ """
301
+
302
+ if options:
303
+ deprecate(
304
+ "ImageMath.unsafe_eval options",
305
+ 12,
306
+ "ImageMath.unsafe_eval keyword arguments",
307
+ )
308
+
309
+ # build execution namespace
310
+ args: dict[str, Any] = ops.copy()
311
+ for k in [*options, *kw]:
312
+ if "__" in k or hasattr(builtins, k):
313
+ msg = f"'{k}' not allowed"
314
+ raise ValueError(msg)
315
+
316
+ args.update(options)
317
+ args.update(kw)
318
+ for k, v in args.items():
319
+ if isinstance(v, Image.Image):
320
+ args[k] = _Operand(v)
321
+
322
+ compiled_code = compile(expression, "<string>", "eval")
323
+
324
+ def scan(code: CodeType) -> None:
325
+ for const in code.co_consts:
326
+ if type(const) is type(compiled_code):
327
+ scan(const)
328
+
329
+ for name in code.co_names:
330
+ if name not in args and name != "abs":
331
+ msg = f"'{name}' not allowed"
332
+ raise ValueError(msg)
333
+
334
+ scan(compiled_code)
335
+ out = builtins.eval(expression, {"__builtins": {"abs": abs}}, args)
336
+ try:
337
+ return out.im
338
+ except AttributeError:
339
+ return out
340
+
341
+
342
+ def eval(
343
+ expression: str,
344
+ _dict: dict[str, Any] = {},
345
+ **kw: Any,
346
+ ) -> Any:
347
+ """
348
+ Evaluates an image expression.
349
+
350
+ Deprecated. Use lambda_eval() or unsafe_eval() instead.
351
+
352
+ :param expression: A string containing a Python-style expression.
353
+ :param _dict: Values to add to the evaluation context. You
354
+ can either use a dictionary, or one or more keyword
355
+ arguments.
356
+ :return: The evaluated expression. This is usually an image object, but can
357
+ also be an integer, a floating point value, or a pixel tuple,
358
+ depending on the expression.
359
+
360
+ .. deprecated:: 10.3.0
361
+ """
362
+
363
+ deprecate(
364
+ "ImageMath.eval",
365
+ 12,
366
+ "ImageMath.lambda_eval or ImageMath.unsafe_eval",
367
+ )
368
+ return unsafe_eval(expression, _dict, **kw)
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/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)
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/ImageMorph.py ADDED
@@ -0,0 +1,265 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # A binary morphology add-on for the Python Imaging Library
2
+ #
3
+ # History:
4
+ # 2014-06-04 Initial version.
5
+ #
6
+ # Copyright (c) 2014 Dov Grobgeld <dov.grobgeld@gmail.com>
7
+ from __future__ import annotations
8
+
9
+ import re
10
+
11
+ from . import Image, _imagingmorph
12
+
13
+ LUT_SIZE = 1 << 9
14
+
15
+ # fmt: off
16
+ ROTATION_MATRIX = [
17
+ 6, 3, 0,
18
+ 7, 4, 1,
19
+ 8, 5, 2,
20
+ ]
21
+ MIRROR_MATRIX = [
22
+ 2, 1, 0,
23
+ 5, 4, 3,
24
+ 8, 7, 6,
25
+ ]
26
+ # fmt: on
27
+
28
+
29
+ class LutBuilder:
30
+ """A class for building a MorphLut from a descriptive language
31
+
32
+ The input patterns is a list of a strings sequences like these::
33
+
34
+ 4:(...
35
+ .1.
36
+ 111)->1
37
+
38
+ (whitespaces including linebreaks are ignored). The option 4
39
+ describes a series of symmetry operations (in this case a
40
+ 4-rotation), the pattern is described by:
41
+
42
+ - . or X - Ignore
43
+ - 1 - Pixel is on
44
+ - 0 - Pixel is off
45
+
46
+ The result of the operation is described after "->" string.
47
+
48
+ The default is to return the current pixel value, which is
49
+ returned if no other match is found.
50
+
51
+ Operations:
52
+
53
+ - 4 - 4 way rotation
54
+ - N - Negate
55
+ - 1 - Dummy op for no other operation (an op must always be given)
56
+ - M - Mirroring
57
+
58
+ Example::
59
+
60
+ lb = LutBuilder(patterns = ["4:(... .1. 111)->1"])
61
+ lut = lb.build_lut()
62
+
63
+ """
64
+
65
+ def __init__(
66
+ self, patterns: list[str] | None = None, op_name: str | None = None
67
+ ) -> None:
68
+ if patterns is not None:
69
+ self.patterns = patterns
70
+ else:
71
+ self.patterns = []
72
+ self.lut: bytearray | None = None
73
+ if op_name is not None:
74
+ known_patterns = {
75
+ "corner": ["1:(... ... ...)->0", "4:(00. 01. ...)->1"],
76
+ "dilation4": ["4:(... .0. .1.)->1"],
77
+ "dilation8": ["4:(... .0. .1.)->1", "4:(... .0. ..1)->1"],
78
+ "erosion4": ["4:(... .1. .0.)->0"],
79
+ "erosion8": ["4:(... .1. .0.)->0", "4:(... .1. ..0)->0"],
80
+ "edge": [
81
+ "1:(... ... ...)->0",
82
+ "4:(.0. .1. ...)->1",
83
+ "4:(01. .1. ...)->1",
84
+ ],
85
+ }
86
+ if op_name not in known_patterns:
87
+ msg = f"Unknown pattern {op_name}!"
88
+ raise Exception(msg)
89
+
90
+ self.patterns = known_patterns[op_name]
91
+
92
+ def add_patterns(self, patterns: list[str]) -> None:
93
+ self.patterns += patterns
94
+
95
+ def build_default_lut(self) -> None:
96
+ symbols = [0, 1]
97
+ m = 1 << 4 # pos of current pixel
98
+ self.lut = bytearray(symbols[(i & m) > 0] for i in range(LUT_SIZE))
99
+
100
+ def get_lut(self) -> bytearray | None:
101
+ return self.lut
102
+
103
+ def _string_permute(self, pattern: str, permutation: list[int]) -> str:
104
+ """string_permute takes a pattern and a permutation and returns the
105
+ string permuted according to the permutation list.
106
+ """
107
+ assert len(permutation) == 9
108
+ return "".join(pattern[p] for p in permutation)
109
+
110
+ def _pattern_permute(
111
+ self, basic_pattern: str, options: str, basic_result: int
112
+ ) -> list[tuple[str, int]]:
113
+ """pattern_permute takes a basic pattern and its result and clones
114
+ the pattern according to the modifications described in the $options
115
+ parameter. It returns a list of all cloned patterns."""
116
+ patterns = [(basic_pattern, basic_result)]
117
+
118
+ # rotations
119
+ if "4" in options:
120
+ res = patterns[-1][1]
121
+ for i in range(4):
122
+ patterns.append(
123
+ (self._string_permute(patterns[-1][0], ROTATION_MATRIX), res)
124
+ )
125
+ # mirror
126
+ if "M" in options:
127
+ n = len(patterns)
128
+ for pattern, res in patterns[:n]:
129
+ patterns.append((self._string_permute(pattern, MIRROR_MATRIX), res))
130
+
131
+ # negate
132
+ if "N" in options:
133
+ n = len(patterns)
134
+ for pattern, res in patterns[:n]:
135
+ # Swap 0 and 1
136
+ pattern = pattern.replace("0", "Z").replace("1", "0").replace("Z", "1")
137
+ res = 1 - int(res)
138
+ patterns.append((pattern, res))
139
+
140
+ return patterns
141
+
142
+ def build_lut(self) -> bytearray:
143
+ """Compile all patterns into a morphology lut.
144
+
145
+ TBD :Build based on (file) morphlut:modify_lut
146
+ """
147
+ self.build_default_lut()
148
+ assert self.lut is not None
149
+ patterns = []
150
+
151
+ # Parse and create symmetries of the patterns strings
152
+ for p in self.patterns:
153
+ m = re.search(r"(\w*):?\s*\((.+?)\)\s*->\s*(\d)", p.replace("\n", ""))
154
+ if not m:
155
+ msg = 'Syntax error in pattern "' + p + '"'
156
+ raise Exception(msg)
157
+ options = m.group(1)
158
+ pattern = m.group(2)
159
+ result = int(m.group(3))
160
+
161
+ # Get rid of spaces
162
+ pattern = pattern.replace(" ", "").replace("\n", "")
163
+
164
+ patterns += self._pattern_permute(pattern, options, result)
165
+
166
+ # compile the patterns into regular expressions for speed
167
+ compiled_patterns = []
168
+ for pattern in patterns:
169
+ p = pattern[0].replace(".", "X").replace("X", "[01]")
170
+ compiled_patterns.append((re.compile(p), pattern[1]))
171
+
172
+ # Step through table and find patterns that match.
173
+ # Note that all the patterns are searched. The last one
174
+ # caught overrides
175
+ for i in range(LUT_SIZE):
176
+ # Build the bit pattern
177
+ bitpattern = bin(i)[2:]
178
+ bitpattern = ("0" * (9 - len(bitpattern)) + bitpattern)[::-1]
179
+
180
+ for pattern, r in compiled_patterns:
181
+ if pattern.match(bitpattern):
182
+ self.lut[i] = [0, 1][r]
183
+
184
+ return self.lut
185
+
186
+
187
+ class MorphOp:
188
+ """A class for binary morphological operators"""
189
+
190
+ def __init__(
191
+ self,
192
+ lut: bytearray | None = None,
193
+ op_name: str | None = None,
194
+ patterns: list[str] | None = None,
195
+ ) -> None:
196
+ """Create a binary morphological operator"""
197
+ self.lut = lut
198
+ if op_name is not None:
199
+ self.lut = LutBuilder(op_name=op_name).build_lut()
200
+ elif patterns is not None:
201
+ self.lut = LutBuilder(patterns=patterns).build_lut()
202
+
203
+ def apply(self, image: Image.Image) -> tuple[int, Image.Image]:
204
+ """Run a single morphological operation on an image
205
+
206
+ Returns a tuple of the number of changed pixels and the
207
+ morphed image"""
208
+ if self.lut is None:
209
+ msg = "No operator loaded"
210
+ raise Exception(msg)
211
+
212
+ if image.mode != "L":
213
+ msg = "Image mode must be L"
214
+ raise ValueError(msg)
215
+ outimage = Image.new(image.mode, image.size, None)
216
+ count = _imagingmorph.apply(bytes(self.lut), image.getim(), outimage.getim())
217
+ return count, outimage
218
+
219
+ def match(self, image: Image.Image) -> list[tuple[int, int]]:
220
+ """Get a list of coordinates matching the morphological operation on
221
+ an image.
222
+
223
+ Returns a list of tuples of (x,y) coordinates
224
+ of all matching pixels. See :ref:`coordinate-system`."""
225
+ if self.lut is None:
226
+ msg = "No operator loaded"
227
+ raise Exception(msg)
228
+
229
+ if image.mode != "L":
230
+ msg = "Image mode must be L"
231
+ raise ValueError(msg)
232
+ return _imagingmorph.match(bytes(self.lut), image.getim())
233
+
234
+ def get_on_pixels(self, image: Image.Image) -> list[tuple[int, int]]:
235
+ """Get a list of all turned on pixels in a binary image
236
+
237
+ Returns a list of tuples of (x,y) coordinates
238
+ of all matching pixels. See :ref:`coordinate-system`."""
239
+
240
+ if image.mode != "L":
241
+ msg = "Image mode must be L"
242
+ raise ValueError(msg)
243
+ return _imagingmorph.get_on_pixels(image.getim())
244
+
245
+ def load_lut(self, filename: str) -> None:
246
+ """Load an operator from an mrl file"""
247
+ with open(filename, "rb") as f:
248
+ self.lut = bytearray(f.read())
249
+
250
+ if len(self.lut) != LUT_SIZE:
251
+ self.lut = None
252
+ msg = "Wrong size operator file!"
253
+ raise Exception(msg)
254
+
255
+ def save_lut(self, filename: str) -> None:
256
+ """Save an operator to an mrl file"""
257
+ if self.lut is None:
258
+ msg = "No operator loaded"
259
+ raise Exception(msg)
260
+ with open(filename, "wb") as f:
261
+ f.write(self.lut)
262
+
263
+ def set_lut(self, lut: bytearray | None) -> None:
264
+ """Set the lut from an external source"""
265
+ self.lut = lut
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/ImageOps.py ADDED
@@ -0,0 +1,745 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # standard image operations
6
+ #
7
+ # History:
8
+ # 2001-10-20 fl Created
9
+ # 2001-10-23 fl Added autocontrast operator
10
+ # 2001-12-18 fl Added Kevin's fit operator
11
+ # 2004-03-14 fl Fixed potential division by zero in equalize
12
+ # 2005-05-05 fl Fixed equalize for low number of values
13
+ #
14
+ # Copyright (c) 2001-2004 by Secret Labs AB
15
+ # Copyright (c) 2001-2004 by Fredrik Lundh
16
+ #
17
+ # See the README file for information on usage and redistribution.
18
+ #
19
+ from __future__ import annotations
20
+
21
+ import functools
22
+ import operator
23
+ import re
24
+ from collections.abc import Sequence
25
+ from typing import Literal, Protocol, cast, overload
26
+
27
+ from . import ExifTags, Image, ImagePalette
28
+
29
+ #
30
+ # helpers
31
+
32
+
33
+ def _border(border: int | tuple[int, ...]) -> tuple[int, int, int, int]:
34
+ if isinstance(border, tuple):
35
+ if len(border) == 2:
36
+ left, top = right, bottom = border
37
+ elif len(border) == 4:
38
+ left, top, right, bottom = border
39
+ else:
40
+ left = top = right = bottom = border
41
+ return left, top, right, bottom
42
+
43
+
44
+ def _color(color: str | int | tuple[int, ...], mode: str) -> int | tuple[int, ...]:
45
+ if isinstance(color, str):
46
+ from . import ImageColor
47
+
48
+ color = ImageColor.getcolor(color, mode)
49
+ return color
50
+
51
+
52
+ def _lut(image: Image.Image, lut: list[int]) -> Image.Image:
53
+ if image.mode == "P":
54
+ # FIXME: apply to lookup table, not image data
55
+ msg = "mode P support coming soon"
56
+ raise NotImplementedError(msg)
57
+ elif image.mode in ("L", "RGB"):
58
+ if image.mode == "RGB" and len(lut) == 256:
59
+ lut = lut + lut + lut
60
+ return image.point(lut)
61
+ else:
62
+ msg = f"not supported for mode {image.mode}"
63
+ raise OSError(msg)
64
+
65
+
66
+ #
67
+ # actions
68
+
69
+
70
+ def autocontrast(
71
+ image: Image.Image,
72
+ cutoff: float | tuple[float, float] = 0,
73
+ ignore: int | Sequence[int] | None = None,
74
+ mask: Image.Image | None = None,
75
+ preserve_tone: bool = False,
76
+ ) -> Image.Image:
77
+ """
78
+ Maximize (normalize) image contrast. This function calculates a
79
+ histogram of the input image (or mask region), removes ``cutoff`` percent of the
80
+ lightest and darkest pixels from the histogram, and remaps the image
81
+ so that the darkest pixel becomes black (0), and the lightest
82
+ becomes white (255).
83
+
84
+ :param image: The image to process.
85
+ :param cutoff: The percent to cut off from the histogram on the low and
86
+ high ends. Either a tuple of (low, high), or a single
87
+ number for both.
88
+ :param ignore: The background pixel value (use None for no background).
89
+ :param mask: Histogram used in contrast operation is computed using pixels
90
+ within the mask. If no mask is given the entire image is used
91
+ for histogram computation.
92
+ :param preserve_tone: Preserve image tone in Photoshop-like style autocontrast.
93
+
94
+ .. versionadded:: 8.2.0
95
+
96
+ :return: An image.
97
+ """
98
+ if preserve_tone:
99
+ histogram = image.convert("L").histogram(mask)
100
+ else:
101
+ histogram = image.histogram(mask)
102
+
103
+ lut = []
104
+ for layer in range(0, len(histogram), 256):
105
+ h = histogram[layer : layer + 256]
106
+ if ignore is not None:
107
+ # get rid of outliers
108
+ if isinstance(ignore, int):
109
+ h[ignore] = 0
110
+ else:
111
+ for ix in ignore:
112
+ h[ix] = 0
113
+ if cutoff:
114
+ # cut off pixels from both ends of the histogram
115
+ if not isinstance(cutoff, tuple):
116
+ cutoff = (cutoff, cutoff)
117
+ # get number of pixels
118
+ n = 0
119
+ for ix in range(256):
120
+ n = n + h[ix]
121
+ # remove cutoff% pixels from the low end
122
+ cut = int(n * cutoff[0] // 100)
123
+ for lo in range(256):
124
+ if cut > h[lo]:
125
+ cut = cut - h[lo]
126
+ h[lo] = 0
127
+ else:
128
+ h[lo] -= cut
129
+ cut = 0
130
+ if cut <= 0:
131
+ break
132
+ # remove cutoff% samples from the high end
133
+ cut = int(n * cutoff[1] // 100)
134
+ for hi in range(255, -1, -1):
135
+ if cut > h[hi]:
136
+ cut = cut - h[hi]
137
+ h[hi] = 0
138
+ else:
139
+ h[hi] -= cut
140
+ cut = 0
141
+ if cut <= 0:
142
+ break
143
+ # find lowest/highest samples after preprocessing
144
+ for lo in range(256):
145
+ if h[lo]:
146
+ break
147
+ for hi in range(255, -1, -1):
148
+ if h[hi]:
149
+ break
150
+ if hi <= lo:
151
+ # don't bother
152
+ lut.extend(list(range(256)))
153
+ else:
154
+ scale = 255.0 / (hi - lo)
155
+ offset = -lo * scale
156
+ for ix in range(256):
157
+ ix = int(ix * scale + offset)
158
+ if ix < 0:
159
+ ix = 0
160
+ elif ix > 255:
161
+ ix = 255
162
+ lut.append(ix)
163
+ return _lut(image, lut)
164
+
165
+
166
+ def colorize(
167
+ image: Image.Image,
168
+ black: str | tuple[int, ...],
169
+ white: str | tuple[int, ...],
170
+ mid: str | int | tuple[int, ...] | None = None,
171
+ blackpoint: int = 0,
172
+ whitepoint: int = 255,
173
+ midpoint: int = 127,
174
+ ) -> Image.Image:
175
+ """
176
+ Colorize grayscale image.
177
+ This function calculates a color wedge which maps all black pixels in
178
+ the source image to the first color and all white pixels to the
179
+ second color. If ``mid`` is specified, it uses three-color mapping.
180
+ The ``black`` and ``white`` arguments should be RGB tuples or color names;
181
+ optionally you can use three-color mapping by also specifying ``mid``.
182
+ Mapping positions for any of the colors can be specified
183
+ (e.g. ``blackpoint``), where these parameters are the integer
184
+ value corresponding to where the corresponding color should be mapped.
185
+ These parameters must have logical order, such that
186
+ ``blackpoint <= midpoint <= whitepoint`` (if ``mid`` is specified).
187
+
188
+ :param image: The image to colorize.
189
+ :param black: The color to use for black input pixels.
190
+ :param white: The color to use for white input pixels.
191
+ :param mid: The color to use for midtone input pixels.
192
+ :param blackpoint: an int value [0, 255] for the black mapping.
193
+ :param whitepoint: an int value [0, 255] for the white mapping.
194
+ :param midpoint: an int value [0, 255] for the midtone mapping.
195
+ :return: An image.
196
+ """
197
+
198
+ # Initial asserts
199
+ assert image.mode == "L"
200
+ if mid is None:
201
+ assert 0 <= blackpoint <= whitepoint <= 255
202
+ else:
203
+ assert 0 <= blackpoint <= midpoint <= whitepoint <= 255
204
+
205
+ # Define colors from arguments
206
+ rgb_black = cast(Sequence[int], _color(black, "RGB"))
207
+ rgb_white = cast(Sequence[int], _color(white, "RGB"))
208
+ rgb_mid = cast(Sequence[int], _color(mid, "RGB")) if mid is not None else None
209
+
210
+ # Empty lists for the mapping
211
+ red = []
212
+ green = []
213
+ blue = []
214
+
215
+ # Create the low-end values
216
+ for i in range(blackpoint):
217
+ red.append(rgb_black[0])
218
+ green.append(rgb_black[1])
219
+ blue.append(rgb_black[2])
220
+
221
+ # Create the mapping (2-color)
222
+ if rgb_mid is None:
223
+ range_map = range(whitepoint - blackpoint)
224
+
225
+ for i in range_map:
226
+ red.append(
227
+ rgb_black[0] + i * (rgb_white[0] - rgb_black[0]) // len(range_map)
228
+ )
229
+ green.append(
230
+ rgb_black[1] + i * (rgb_white[1] - rgb_black[1]) // len(range_map)
231
+ )
232
+ blue.append(
233
+ rgb_black[2] + i * (rgb_white[2] - rgb_black[2]) // len(range_map)
234
+ )
235
+
236
+ # Create the mapping (3-color)
237
+ else:
238
+ range_map1 = range(midpoint - blackpoint)
239
+ range_map2 = range(whitepoint - midpoint)
240
+
241
+ for i in range_map1:
242
+ red.append(
243
+ rgb_black[0] + i * (rgb_mid[0] - rgb_black[0]) // len(range_map1)
244
+ )
245
+ green.append(
246
+ rgb_black[1] + i * (rgb_mid[1] - rgb_black[1]) // len(range_map1)
247
+ )
248
+ blue.append(
249
+ rgb_black[2] + i * (rgb_mid[2] - rgb_black[2]) // len(range_map1)
250
+ )
251
+ for i in range_map2:
252
+ red.append(rgb_mid[0] + i * (rgb_white[0] - rgb_mid[0]) // len(range_map2))
253
+ green.append(
254
+ rgb_mid[1] + i * (rgb_white[1] - rgb_mid[1]) // len(range_map2)
255
+ )
256
+ blue.append(rgb_mid[2] + i * (rgb_white[2] - rgb_mid[2]) // len(range_map2))
257
+
258
+ # Create the high-end values
259
+ for i in range(256 - whitepoint):
260
+ red.append(rgb_white[0])
261
+ green.append(rgb_white[1])
262
+ blue.append(rgb_white[2])
263
+
264
+ # Return converted image
265
+ image = image.convert("RGB")
266
+ return _lut(image, red + green + blue)
267
+
268
+
269
+ def contain(
270
+ image: Image.Image, size: tuple[int, int], method: int = Image.Resampling.BICUBIC
271
+ ) -> Image.Image:
272
+ """
273
+ Returns a resized version of the image, set to the maximum width and height
274
+ within the requested size, while maintaining the original aspect ratio.
275
+
276
+ :param image: The image to resize.
277
+ :param size: The requested output size in pixels, given as a
278
+ (width, height) tuple.
279
+ :param method: Resampling method to use. Default is
280
+ :py:attr:`~PIL.Image.Resampling.BICUBIC`.
281
+ See :ref:`concept-filters`.
282
+ :return: An image.
283
+ """
284
+
285
+ im_ratio = image.width / image.height
286
+ dest_ratio = size[0] / size[1]
287
+
288
+ if im_ratio != dest_ratio:
289
+ if im_ratio > dest_ratio:
290
+ new_height = round(image.height / image.width * size[0])
291
+ if new_height != size[1]:
292
+ size = (size[0], new_height)
293
+ else:
294
+ new_width = round(image.width / image.height * size[1])
295
+ if new_width != size[0]:
296
+ size = (new_width, size[1])
297
+ return image.resize(size, resample=method)
298
+
299
+
300
+ def cover(
301
+ image: Image.Image, size: tuple[int, int], method: int = Image.Resampling.BICUBIC
302
+ ) -> Image.Image:
303
+ """
304
+ Returns a resized version of the image, so that the requested size is
305
+ covered, while maintaining the original aspect ratio.
306
+
307
+ :param image: The image to resize.
308
+ :param size: The requested output size in pixels, given as a
309
+ (width, height) tuple.
310
+ :param method: Resampling method to use. Default is
311
+ :py:attr:`~PIL.Image.Resampling.BICUBIC`.
312
+ See :ref:`concept-filters`.
313
+ :return: An image.
314
+ """
315
+
316
+ im_ratio = image.width / image.height
317
+ dest_ratio = size[0] / size[1]
318
+
319
+ if im_ratio != dest_ratio:
320
+ if im_ratio < dest_ratio:
321
+ new_height = round(image.height / image.width * size[0])
322
+ if new_height != size[1]:
323
+ size = (size[0], new_height)
324
+ else:
325
+ new_width = round(image.width / image.height * size[1])
326
+ if new_width != size[0]:
327
+ size = (new_width, size[1])
328
+ return image.resize(size, resample=method)
329
+
330
+
331
+ def pad(
332
+ image: Image.Image,
333
+ size: tuple[int, int],
334
+ method: int = Image.Resampling.BICUBIC,
335
+ color: str | int | tuple[int, ...] | None = None,
336
+ centering: tuple[float, float] = (0.5, 0.5),
337
+ ) -> Image.Image:
338
+ """
339
+ Returns a resized and padded version of the image, expanded to fill the
340
+ requested aspect ratio and size.
341
+
342
+ :param image: The image to resize and crop.
343
+ :param size: The requested output size in pixels, given as a
344
+ (width, height) tuple.
345
+ :param method: Resampling method to use. Default is
346
+ :py:attr:`~PIL.Image.Resampling.BICUBIC`.
347
+ See :ref:`concept-filters`.
348
+ :param color: The background color of the padded image.
349
+ :param centering: Control the position of the original image within the
350
+ padded version.
351
+
352
+ (0.5, 0.5) will keep the image centered
353
+ (0, 0) will keep the image aligned to the top left
354
+ (1, 1) will keep the image aligned to the bottom
355
+ right
356
+ :return: An image.
357
+ """
358
+
359
+ resized = contain(image, size, method)
360
+ if resized.size == size:
361
+ out = resized
362
+ else:
363
+ out = Image.new(image.mode, size, color)
364
+ if resized.palette:
365
+ palette = resized.getpalette()
366
+ if palette is not None:
367
+ out.putpalette(palette)
368
+ if resized.width != size[0]:
369
+ x = round((size[0] - resized.width) * max(0, min(centering[0], 1)))
370
+ out.paste(resized, (x, 0))
371
+ else:
372
+ y = round((size[1] - resized.height) * max(0, min(centering[1], 1)))
373
+ out.paste(resized, (0, y))
374
+ return out
375
+
376
+
377
+ def crop(image: Image.Image, border: int = 0) -> Image.Image:
378
+ """
379
+ Remove border from image. The same amount of pixels are removed
380
+ from all four sides. This function works on all image modes.
381
+
382
+ .. seealso:: :py:meth:`~PIL.Image.Image.crop`
383
+
384
+ :param image: The image to crop.
385
+ :param border: The number of pixels to remove.
386
+ :return: An image.
387
+ """
388
+ left, top, right, bottom = _border(border)
389
+ return image.crop((left, top, image.size[0] - right, image.size[1] - bottom))
390
+
391
+
392
+ def scale(
393
+ image: Image.Image, factor: float, resample: int = Image.Resampling.BICUBIC
394
+ ) -> Image.Image:
395
+ """
396
+ Returns a rescaled image by a specific factor given in parameter.
397
+ A factor greater than 1 expands the image, between 0 and 1 contracts the
398
+ image.
399
+
400
+ :param image: The image to rescale.
401
+ :param factor: The expansion factor, as a float.
402
+ :param resample: Resampling method to use. Default is
403
+ :py:attr:`~PIL.Image.Resampling.BICUBIC`.
404
+ See :ref:`concept-filters`.
405
+ :returns: An :py:class:`~PIL.Image.Image` object.
406
+ """
407
+ if factor == 1:
408
+ return image.copy()
409
+ elif factor <= 0:
410
+ msg = "the factor must be greater than 0"
411
+ raise ValueError(msg)
412
+ else:
413
+ size = (round(factor * image.width), round(factor * image.height))
414
+ return image.resize(size, resample)
415
+
416
+
417
+ class SupportsGetMesh(Protocol):
418
+ """
419
+ An object that supports the ``getmesh`` method, taking an image as an
420
+ argument, and returning a list of tuples. Each tuple contains two tuples,
421
+ the source box as a tuple of 4 integers, and a tuple of 8 integers for the
422
+ final quadrilateral, in order of top left, bottom left, bottom right, top
423
+ right.
424
+ """
425
+
426
+ def getmesh(
427
+ self, image: Image.Image
428
+ ) -> list[
429
+ tuple[tuple[int, int, int, int], tuple[int, int, int, int, int, int, int, int]]
430
+ ]: ...
431
+
432
+
433
+ def deform(
434
+ image: Image.Image,
435
+ deformer: SupportsGetMesh,
436
+ resample: int = Image.Resampling.BILINEAR,
437
+ ) -> Image.Image:
438
+ """
439
+ Deform the image.
440
+
441
+ :param image: The image to deform.
442
+ :param deformer: A deformer object. Any object that implements a
443
+ ``getmesh`` method can be used.
444
+ :param resample: An optional resampling filter. Same values possible as
445
+ in the PIL.Image.transform function.
446
+ :return: An image.
447
+ """
448
+ return image.transform(
449
+ image.size, Image.Transform.MESH, deformer.getmesh(image), resample
450
+ )
451
+
452
+
453
+ def equalize(image: Image.Image, mask: Image.Image | None = None) -> Image.Image:
454
+ """
455
+ Equalize the image histogram. This function applies a non-linear
456
+ mapping to the input image, in order to create a uniform
457
+ distribution of grayscale values in the output image.
458
+
459
+ :param image: The image to equalize.
460
+ :param mask: An optional mask. If given, only the pixels selected by
461
+ the mask are included in the analysis.
462
+ :return: An image.
463
+ """
464
+ if image.mode == "P":
465
+ image = image.convert("RGB")
466
+ h = image.histogram(mask)
467
+ lut = []
468
+ for b in range(0, len(h), 256):
469
+ histo = [_f for _f in h[b : b + 256] if _f]
470
+ if len(histo) <= 1:
471
+ lut.extend(list(range(256)))
472
+ else:
473
+ step = (functools.reduce(operator.add, histo) - histo[-1]) // 255
474
+ if not step:
475
+ lut.extend(list(range(256)))
476
+ else:
477
+ n = step // 2
478
+ for i in range(256):
479
+ lut.append(n // step)
480
+ n = n + h[i + b]
481
+ return _lut(image, lut)
482
+
483
+
484
+ def expand(
485
+ image: Image.Image,
486
+ border: int | tuple[int, ...] = 0,
487
+ fill: str | int | tuple[int, ...] = 0,
488
+ ) -> Image.Image:
489
+ """
490
+ Add border to the image
491
+
492
+ :param image: The image to expand.
493
+ :param border: Border width, in pixels.
494
+ :param fill: Pixel fill value (a color value). Default is 0 (black).
495
+ :return: An image.
496
+ """
497
+ left, top, right, bottom = _border(border)
498
+ width = left + image.size[0] + right
499
+ height = top + image.size[1] + bottom
500
+ color = _color(fill, image.mode)
501
+ if image.palette:
502
+ palette = ImagePalette.ImagePalette(palette=image.getpalette())
503
+ if isinstance(color, tuple) and (len(color) == 3 or len(color) == 4):
504
+ color = palette.getcolor(color)
505
+ else:
506
+ palette = None
507
+ out = Image.new(image.mode, (width, height), color)
508
+ if palette:
509
+ out.putpalette(palette.palette)
510
+ out.paste(image, (left, top))
511
+ return out
512
+
513
+
514
+ def fit(
515
+ image: Image.Image,
516
+ size: tuple[int, int],
517
+ method: int = Image.Resampling.BICUBIC,
518
+ bleed: float = 0.0,
519
+ centering: tuple[float, float] = (0.5, 0.5),
520
+ ) -> Image.Image:
521
+ """
522
+ Returns a resized and cropped version of the image, cropped to the
523
+ requested aspect ratio and size.
524
+
525
+ This function was contributed by Kevin Cazabon.
526
+
527
+ :param image: The image to resize and crop.
528
+ :param size: The requested output size in pixels, given as a
529
+ (width, height) tuple.
530
+ :param method: Resampling method to use. Default is
531
+ :py:attr:`~PIL.Image.Resampling.BICUBIC`.
532
+ See :ref:`concept-filters`.
533
+ :param bleed: Remove a border around the outside of the image from all
534
+ four edges. The value is a decimal percentage (use 0.01 for
535
+ one percent). The default value is 0 (no border).
536
+ Cannot be greater than or equal to 0.5.
537
+ :param centering: Control the cropping position. Use (0.5, 0.5) for
538
+ center cropping (e.g. if cropping the width, take 50% off
539
+ of the left side, and therefore 50% off the right side).
540
+ (0.0, 0.0) will crop from the top left corner (i.e. if
541
+ cropping the width, take all of the crop off of the right
542
+ side, and if cropping the height, take all of it off the
543
+ bottom). (1.0, 0.0) will crop from the bottom left
544
+ corner, etc. (i.e. if cropping the width, take all of the
545
+ crop off the left side, and if cropping the height take
546
+ none from the top, and therefore all off the bottom).
547
+ :return: An image.
548
+ """
549
+
550
+ # by Kevin Cazabon, Feb 17/2000
551
+ # kevin@cazabon.com
552
+ # https://www.cazabon.com
553
+
554
+ centering_x, centering_y = centering
555
+
556
+ if not 0.0 <= centering_x <= 1.0:
557
+ centering_x = 0.5
558
+ if not 0.0 <= centering_y <= 1.0:
559
+ centering_y = 0.5
560
+
561
+ if not 0.0 <= bleed < 0.5:
562
+ bleed = 0.0
563
+
564
+ # calculate the area to use for resizing and cropping, subtracting
565
+ # the 'bleed' around the edges
566
+
567
+ # number of pixels to trim off on Top and Bottom, Left and Right
568
+ bleed_pixels = (bleed * image.size[0], bleed * image.size[1])
569
+
570
+ live_size = (
571
+ image.size[0] - bleed_pixels[0] * 2,
572
+ image.size[1] - bleed_pixels[1] * 2,
573
+ )
574
+
575
+ # calculate the aspect ratio of the live_size
576
+ live_size_ratio = live_size[0] / live_size[1]
577
+
578
+ # calculate the aspect ratio of the output image
579
+ output_ratio = size[0] / size[1]
580
+
581
+ # figure out if the sides or top/bottom will be cropped off
582
+ if live_size_ratio == output_ratio:
583
+ # live_size is already the needed ratio
584
+ crop_width = live_size[0]
585
+ crop_height = live_size[1]
586
+ elif live_size_ratio >= output_ratio:
587
+ # live_size is wider than what's needed, crop the sides
588
+ crop_width = output_ratio * live_size[1]
589
+ crop_height = live_size[1]
590
+ else:
591
+ # live_size is taller than what's needed, crop the top and bottom
592
+ crop_width = live_size[0]
593
+ crop_height = live_size[0] / output_ratio
594
+
595
+ # make the crop
596
+ crop_left = bleed_pixels[0] + (live_size[0] - crop_width) * centering_x
597
+ crop_top = bleed_pixels[1] + (live_size[1] - crop_height) * centering_y
598
+
599
+ crop = (crop_left, crop_top, crop_left + crop_width, crop_top + crop_height)
600
+
601
+ # resize the image and return it
602
+ return image.resize(size, method, box=crop)
603
+
604
+
605
+ def flip(image: Image.Image) -> Image.Image:
606
+ """
607
+ Flip the image vertically (top to bottom).
608
+
609
+ :param image: The image to flip.
610
+ :return: An image.
611
+ """
612
+ return image.transpose(Image.Transpose.FLIP_TOP_BOTTOM)
613
+
614
+
615
+ def grayscale(image: Image.Image) -> Image.Image:
616
+ """
617
+ Convert the image to grayscale.
618
+
619
+ :param image: The image to convert.
620
+ :return: An image.
621
+ """
622
+ return image.convert("L")
623
+
624
+
625
+ def invert(image: Image.Image) -> Image.Image:
626
+ """
627
+ Invert (negate) the image.
628
+
629
+ :param image: The image to invert.
630
+ :return: An image.
631
+ """
632
+ lut = list(range(255, -1, -1))
633
+ return image.point(lut) if image.mode == "1" else _lut(image, lut)
634
+
635
+
636
+ def mirror(image: Image.Image) -> Image.Image:
637
+ """
638
+ Flip image horizontally (left to right).
639
+
640
+ :param image: The image to mirror.
641
+ :return: An image.
642
+ """
643
+ return image.transpose(Image.Transpose.FLIP_LEFT_RIGHT)
644
+
645
+
646
+ def posterize(image: Image.Image, bits: int) -> Image.Image:
647
+ """
648
+ Reduce the number of bits for each color channel.
649
+
650
+ :param image: The image to posterize.
651
+ :param bits: The number of bits to keep for each channel (1-8).
652
+ :return: An image.
653
+ """
654
+ mask = ~(2 ** (8 - bits) - 1)
655
+ lut = [i & mask for i in range(256)]
656
+ return _lut(image, lut)
657
+
658
+
659
+ def solarize(image: Image.Image, threshold: int = 128) -> Image.Image:
660
+ """
661
+ Invert all pixel values above a threshold.
662
+
663
+ :param image: The image to solarize.
664
+ :param threshold: All pixels above this grayscale level are inverted.
665
+ :return: An image.
666
+ """
667
+ lut = []
668
+ for i in range(256):
669
+ if i < threshold:
670
+ lut.append(i)
671
+ else:
672
+ lut.append(255 - i)
673
+ return _lut(image, lut)
674
+
675
+
676
+ @overload
677
+ def exif_transpose(image: Image.Image, *, in_place: Literal[True]) -> None: ...
678
+
679
+
680
+ @overload
681
+ def exif_transpose(
682
+ image: Image.Image, *, in_place: Literal[False] = False
683
+ ) -> Image.Image: ...
684
+
685
+
686
+ def exif_transpose(image: Image.Image, *, in_place: bool = False) -> Image.Image | None:
687
+ """
688
+ If an image has an EXIF Orientation tag, other than 1, transpose the image
689
+ accordingly, and remove the orientation data.
690
+
691
+ :param image: The image to transpose.
692
+ :param in_place: Boolean. Keyword-only argument.
693
+ If ``True``, the original image is modified in-place, and ``None`` is returned.
694
+ If ``False`` (default), a new :py:class:`~PIL.Image.Image` object is returned
695
+ with the transposition applied. If there is no transposition, a copy of the
696
+ image will be returned.
697
+ """
698
+ image.load()
699
+ image_exif = image.getexif()
700
+ orientation = image_exif.get(ExifTags.Base.Orientation, 1)
701
+ method = {
702
+ 2: Image.Transpose.FLIP_LEFT_RIGHT,
703
+ 3: Image.Transpose.ROTATE_180,
704
+ 4: Image.Transpose.FLIP_TOP_BOTTOM,
705
+ 5: Image.Transpose.TRANSPOSE,
706
+ 6: Image.Transpose.ROTATE_270,
707
+ 7: Image.Transpose.TRANSVERSE,
708
+ 8: Image.Transpose.ROTATE_90,
709
+ }.get(orientation)
710
+ if method is not None:
711
+ if in_place:
712
+ image.im = image.im.transpose(method)
713
+ image._size = image.im.size
714
+ else:
715
+ transposed_image = image.transpose(method)
716
+ exif_image = image if in_place else transposed_image
717
+
718
+ exif = exif_image.getexif()
719
+ if ExifTags.Base.Orientation in exif:
720
+ del exif[ExifTags.Base.Orientation]
721
+ if "exif" in exif_image.info:
722
+ exif_image.info["exif"] = exif.tobytes()
723
+ elif "Raw profile type exif" in exif_image.info:
724
+ exif_image.info["Raw profile type exif"] = exif.tobytes().hex()
725
+ for key in ("XML:com.adobe.xmp", "xmp"):
726
+ if key in exif_image.info:
727
+ for pattern in (
728
+ r'tiff:Orientation="([0-9])"',
729
+ r"<tiff:Orientation>([0-9])</tiff:Orientation>",
730
+ ):
731
+ value = exif_image.info[key]
732
+ if isinstance(value, str):
733
+ value = re.sub(pattern, "", value)
734
+ elif isinstance(value, tuple):
735
+ value = tuple(
736
+ re.sub(pattern.encode(), b"", v) for v in value
737
+ )
738
+ else:
739
+ value = re.sub(pattern.encode(), b"", value)
740
+ exif_image.info[key] = value
741
+ if not in_place:
742
+ return transposed_image
743
+ elif not in_place:
744
+ return image.copy()
745
+ return None
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/ImagePalette.py ADDED
@@ -0,0 +1,286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # image palette object
6
+ #
7
+ # History:
8
+ # 1996-03-11 fl Rewritten.
9
+ # 1997-01-03 fl Up and running.
10
+ # 1997-08-23 fl Added load hack
11
+ # 2001-04-16 fl Fixed randint shadow bug in random()
12
+ #
13
+ # Copyright (c) 1997-2001 by Secret Labs AB
14
+ # Copyright (c) 1996-1997 by Fredrik Lundh
15
+ #
16
+ # See the README file for information on usage and redistribution.
17
+ #
18
+ from __future__ import annotations
19
+
20
+ import array
21
+ from collections.abc import Sequence
22
+ from typing import IO
23
+
24
+ from . import GimpGradientFile, GimpPaletteFile, ImageColor, PaletteFile
25
+
26
+ TYPE_CHECKING = False
27
+ if TYPE_CHECKING:
28
+ from . import Image
29
+
30
+
31
+ class ImagePalette:
32
+ """
33
+ Color palette for palette mapped images
34
+
35
+ :param mode: The mode to use for the palette. See:
36
+ :ref:`concept-modes`. Defaults to "RGB"
37
+ :param palette: An optional palette. If given, it must be a bytearray,
38
+ an array or a list of ints between 0-255. The list must consist of
39
+ all channels for one color followed by the next color (e.g. RGBRGBRGB).
40
+ Defaults to an empty palette.
41
+ """
42
+
43
+ def __init__(
44
+ self,
45
+ mode: str = "RGB",
46
+ palette: Sequence[int] | bytes | bytearray | None = None,
47
+ ) -> None:
48
+ self.mode = mode
49
+ self.rawmode: str | None = None # if set, palette contains raw data
50
+ self.palette = palette or bytearray()
51
+ self.dirty: int | None = None
52
+
53
+ @property
54
+ def palette(self) -> Sequence[int] | bytes | bytearray:
55
+ return self._palette
56
+
57
+ @palette.setter
58
+ def palette(self, palette: Sequence[int] | bytes | bytearray) -> None:
59
+ self._colors: dict[tuple[int, ...], int] | None = None
60
+ self._palette = palette
61
+
62
+ @property
63
+ def colors(self) -> dict[tuple[int, ...], int]:
64
+ if self._colors is None:
65
+ mode_len = len(self.mode)
66
+ self._colors = {}
67
+ for i in range(0, len(self.palette), mode_len):
68
+ color = tuple(self.palette[i : i + mode_len])
69
+ if color in self._colors:
70
+ continue
71
+ self._colors[color] = i // mode_len
72
+ return self._colors
73
+
74
+ @colors.setter
75
+ def colors(self, colors: dict[tuple[int, ...], int]) -> None:
76
+ self._colors = colors
77
+
78
+ def copy(self) -> ImagePalette:
79
+ new = ImagePalette()
80
+
81
+ new.mode = self.mode
82
+ new.rawmode = self.rawmode
83
+ if self.palette is not None:
84
+ new.palette = self.palette[:]
85
+ new.dirty = self.dirty
86
+
87
+ return new
88
+
89
+ def getdata(self) -> tuple[str, Sequence[int] | bytes | bytearray]:
90
+ """
91
+ Get palette contents in format suitable for the low-level
92
+ ``im.putpalette`` primitive.
93
+
94
+ .. warning:: This method is experimental.
95
+ """
96
+ if self.rawmode:
97
+ return self.rawmode, self.palette
98
+ return self.mode, self.tobytes()
99
+
100
+ def tobytes(self) -> bytes:
101
+ """Convert palette to bytes.
102
+
103
+ .. warning:: This method is experimental.
104
+ """
105
+ if self.rawmode:
106
+ msg = "palette contains raw palette data"
107
+ raise ValueError(msg)
108
+ if isinstance(self.palette, bytes):
109
+ return self.palette
110
+ arr = array.array("B", self.palette)
111
+ return arr.tobytes()
112
+
113
+ # Declare tostring as an alias for tobytes
114
+ tostring = tobytes
115
+
116
+ def _new_color_index(
117
+ self, image: Image.Image | None = None, e: Exception | None = None
118
+ ) -> int:
119
+ if not isinstance(self.palette, bytearray):
120
+ self._palette = bytearray(self.palette)
121
+ index = len(self.palette) // 3
122
+ special_colors: tuple[int | tuple[int, ...] | None, ...] = ()
123
+ if image:
124
+ special_colors = (
125
+ image.info.get("background"),
126
+ image.info.get("transparency"),
127
+ )
128
+ while index in special_colors:
129
+ index += 1
130
+ if index >= 256:
131
+ if image:
132
+ # Search for an unused index
133
+ for i, count in reversed(list(enumerate(image.histogram()))):
134
+ if count == 0 and i not in special_colors:
135
+ index = i
136
+ break
137
+ if index >= 256:
138
+ msg = "cannot allocate more than 256 colors"
139
+ raise ValueError(msg) from e
140
+ return index
141
+
142
+ def getcolor(
143
+ self,
144
+ color: tuple[int, ...],
145
+ image: Image.Image | None = None,
146
+ ) -> int:
147
+ """Given an rgb tuple, allocate palette entry.
148
+
149
+ .. warning:: This method is experimental.
150
+ """
151
+ if self.rawmode:
152
+ msg = "palette contains raw palette data"
153
+ raise ValueError(msg)
154
+ if isinstance(color, tuple):
155
+ if self.mode == "RGB":
156
+ if len(color) == 4:
157
+ if color[3] != 255:
158
+ msg = "cannot add non-opaque RGBA color to RGB palette"
159
+ raise ValueError(msg)
160
+ color = color[:3]
161
+ elif self.mode == "RGBA":
162
+ if len(color) == 3:
163
+ color += (255,)
164
+ try:
165
+ return self.colors[color]
166
+ except KeyError as e:
167
+ # allocate new color slot
168
+ index = self._new_color_index(image, e)
169
+ assert isinstance(self._palette, bytearray)
170
+ self.colors[color] = index
171
+ if index * 3 < len(self.palette):
172
+ self._palette = (
173
+ self._palette[: index * 3]
174
+ + bytes(color)
175
+ + self._palette[index * 3 + 3 :]
176
+ )
177
+ else:
178
+ self._palette += bytes(color)
179
+ self.dirty = 1
180
+ return index
181
+ else:
182
+ msg = f"unknown color specifier: {repr(color)}" # type: ignore[unreachable]
183
+ raise ValueError(msg)
184
+
185
+ def save(self, fp: str | IO[str]) -> None:
186
+ """Save palette to text file.
187
+
188
+ .. warning:: This method is experimental.
189
+ """
190
+ if self.rawmode:
191
+ msg = "palette contains raw palette data"
192
+ raise ValueError(msg)
193
+ if isinstance(fp, str):
194
+ fp = open(fp, "w")
195
+ fp.write("# Palette\n")
196
+ fp.write(f"# Mode: {self.mode}\n")
197
+ for i in range(256):
198
+ fp.write(f"{i}")
199
+ for j in range(i * len(self.mode), (i + 1) * len(self.mode)):
200
+ try:
201
+ fp.write(f" {self.palette[j]}")
202
+ except IndexError:
203
+ fp.write(" 0")
204
+ fp.write("\n")
205
+ fp.close()
206
+
207
+
208
+ # --------------------------------------------------------------------
209
+ # Internal
210
+
211
+
212
+ def raw(rawmode: str, data: Sequence[int] | bytes | bytearray) -> ImagePalette:
213
+ palette = ImagePalette()
214
+ palette.rawmode = rawmode
215
+ palette.palette = data
216
+ palette.dirty = 1
217
+ return palette
218
+
219
+
220
+ # --------------------------------------------------------------------
221
+ # Factories
222
+
223
+
224
+ def make_linear_lut(black: int, white: float) -> list[int]:
225
+ if black == 0:
226
+ return [int(white * i // 255) for i in range(256)]
227
+
228
+ msg = "unavailable when black is non-zero"
229
+ raise NotImplementedError(msg) # FIXME
230
+
231
+
232
+ def make_gamma_lut(exp: float) -> list[int]:
233
+ return [int(((i / 255.0) ** exp) * 255.0 + 0.5) for i in range(256)]
234
+
235
+
236
+ def negative(mode: str = "RGB") -> ImagePalette:
237
+ palette = list(range(256 * len(mode)))
238
+ palette.reverse()
239
+ return ImagePalette(mode, [i // len(mode) for i in palette])
240
+
241
+
242
+ def random(mode: str = "RGB") -> ImagePalette:
243
+ from random import randint
244
+
245
+ palette = [randint(0, 255) for _ in range(256 * len(mode))]
246
+ return ImagePalette(mode, palette)
247
+
248
+
249
+ def sepia(white: str = "#fff0c0") -> ImagePalette:
250
+ bands = [make_linear_lut(0, band) for band in ImageColor.getrgb(white)]
251
+ return ImagePalette("RGB", [bands[i % 3][i // 3] for i in range(256 * 3)])
252
+
253
+
254
+ def wedge(mode: str = "RGB") -> ImagePalette:
255
+ palette = list(range(256 * len(mode)))
256
+ return ImagePalette(mode, [i // len(mode) for i in palette])
257
+
258
+
259
+ def load(filename: str) -> tuple[bytes, str]:
260
+ # FIXME: supports GIMP gradients only
261
+
262
+ with open(filename, "rb") as fp:
263
+ paletteHandlers: list[
264
+ type[
265
+ GimpPaletteFile.GimpPaletteFile
266
+ | GimpGradientFile.GimpGradientFile
267
+ | PaletteFile.PaletteFile
268
+ ]
269
+ ] = [
270
+ GimpPaletteFile.GimpPaletteFile,
271
+ GimpGradientFile.GimpGradientFile,
272
+ PaletteFile.PaletteFile,
273
+ ]
274
+ for paletteHandler in paletteHandlers:
275
+ try:
276
+ fp.seek(0)
277
+ lut = paletteHandler(fp).getpalette()
278
+ if lut:
279
+ break
280
+ except (SyntaxError, ValueError):
281
+ pass
282
+ else:
283
+ msg = "cannot load palette"
284
+ raise OSError(msg)
285
+
286
+ return lut # data, rawmode
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/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
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/ImageQt.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # a simple Qt image interface.
6
+ #
7
+ # history:
8
+ # 2006-06-03 fl: created
9
+ # 2006-06-04 fl: inherit from QImage instead of wrapping it
10
+ # 2006-06-05 fl: removed toimage helper; move string support to ImageQt
11
+ # 2013-11-13 fl: add support for Qt5 (aurelien.ballier@cyclonit.com)
12
+ #
13
+ # Copyright (c) 2006 by Secret Labs AB
14
+ # Copyright (c) 2006 by Fredrik Lundh
15
+ #
16
+ # See the README file for information on usage and redistribution.
17
+ #
18
+ from __future__ import annotations
19
+
20
+ import sys
21
+ from io import BytesIO
22
+ from typing import Any, Callable, Union
23
+
24
+ from . import Image
25
+ from ._util import is_path
26
+
27
+ TYPE_CHECKING = False
28
+ if TYPE_CHECKING:
29
+ import PyQt6
30
+ import PySide6
31
+
32
+ from . import ImageFile
33
+
34
+ QBuffer: type
35
+ QByteArray = Union[PyQt6.QtCore.QByteArray, PySide6.QtCore.QByteArray]
36
+ QIODevice = Union[PyQt6.QtCore.QIODevice, PySide6.QtCore.QIODevice]
37
+ QImage = Union[PyQt6.QtGui.QImage, PySide6.QtGui.QImage]
38
+ QPixmap = Union[PyQt6.QtGui.QPixmap, PySide6.QtGui.QPixmap]
39
+
40
+ qt_version: str | None
41
+ qt_versions = [
42
+ ["6", "PyQt6"],
43
+ ["side6", "PySide6"],
44
+ ]
45
+
46
+ # If a version has already been imported, attempt it first
47
+ qt_versions.sort(key=lambda version: version[1] in sys.modules, reverse=True)
48
+ for version, qt_module in qt_versions:
49
+ try:
50
+ qRgba: Callable[[int, int, int, int], int]
51
+ if qt_module == "PyQt6":
52
+ from PyQt6.QtCore import QBuffer, QIODevice
53
+ from PyQt6.QtGui import QImage, QPixmap, qRgba
54
+ elif qt_module == "PySide6":
55
+ from PySide6.QtCore import QBuffer, QIODevice
56
+ from PySide6.QtGui import QImage, QPixmap, qRgba
57
+ except (ImportError, RuntimeError):
58
+ continue
59
+ qt_is_installed = True
60
+ qt_version = version
61
+ break
62
+ else:
63
+ qt_is_installed = False
64
+ qt_version = None
65
+
66
+
67
+ def rgb(r: int, g: int, b: int, a: int = 255) -> int:
68
+ """(Internal) Turns an RGB color into a Qt compatible color integer."""
69
+ # use qRgb to pack the colors, and then turn the resulting long
70
+ # into a negative integer with the same bitpattern.
71
+ return qRgba(r, g, b, a) & 0xFFFFFFFF
72
+
73
+
74
+ def fromqimage(im: QImage | QPixmap) -> ImageFile.ImageFile:
75
+ """
76
+ :param im: QImage or PIL ImageQt object
77
+ """
78
+ buffer = QBuffer()
79
+ qt_openmode: object
80
+ if qt_version == "6":
81
+ try:
82
+ qt_openmode = getattr(QIODevice, "OpenModeFlag")
83
+ except AttributeError:
84
+ qt_openmode = getattr(QIODevice, "OpenMode")
85
+ else:
86
+ qt_openmode = QIODevice
87
+ buffer.open(getattr(qt_openmode, "ReadWrite"))
88
+ # preserve alpha channel with png
89
+ # otherwise ppm is more friendly with Image.open
90
+ if im.hasAlphaChannel():
91
+ im.save(buffer, "png")
92
+ else:
93
+ im.save(buffer, "ppm")
94
+
95
+ b = BytesIO()
96
+ b.write(buffer.data())
97
+ buffer.close()
98
+ b.seek(0)
99
+
100
+ return Image.open(b)
101
+
102
+
103
+ def fromqpixmap(im: QPixmap) -> ImageFile.ImageFile:
104
+ return fromqimage(im)
105
+
106
+
107
+ def align8to32(bytes: bytes, width: int, mode: str) -> bytes:
108
+ """
109
+ converts each scanline of data from 8 bit to 32 bit aligned
110
+ """
111
+
112
+ bits_per_pixel = {"1": 1, "L": 8, "P": 8, "I;16": 16}[mode]
113
+
114
+ # calculate bytes per line and the extra padding if needed
115
+ bits_per_line = bits_per_pixel * width
116
+ full_bytes_per_line, remaining_bits_per_line = divmod(bits_per_line, 8)
117
+ bytes_per_line = full_bytes_per_line + (1 if remaining_bits_per_line else 0)
118
+
119
+ extra_padding = -bytes_per_line % 4
120
+
121
+ # already 32 bit aligned by luck
122
+ if not extra_padding:
123
+ return bytes
124
+
125
+ new_data = [
126
+ bytes[i * bytes_per_line : (i + 1) * bytes_per_line] + b"\x00" * extra_padding
127
+ for i in range(len(bytes) // bytes_per_line)
128
+ ]
129
+
130
+ return b"".join(new_data)
131
+
132
+
133
+ def _toqclass_helper(im: Image.Image | str | QByteArray) -> dict[str, Any]:
134
+ data = None
135
+ colortable = None
136
+ exclusive_fp = False
137
+
138
+ # handle filename, if given instead of image name
139
+ if hasattr(im, "toUtf8"):
140
+ # FIXME - is this really the best way to do this?
141
+ im = str(im.toUtf8(), "utf-8")
142
+ if is_path(im):
143
+ im = Image.open(im)
144
+ exclusive_fp = True
145
+ assert isinstance(im, Image.Image)
146
+
147
+ qt_format = getattr(QImage, "Format") if qt_version == "6" else QImage
148
+ if im.mode == "1":
149
+ format = getattr(qt_format, "Format_Mono")
150
+ elif im.mode == "L":
151
+ format = getattr(qt_format, "Format_Indexed8")
152
+ colortable = [rgb(i, i, i) for i in range(256)]
153
+ elif im.mode == "P":
154
+ format = getattr(qt_format, "Format_Indexed8")
155
+ palette = im.getpalette()
156
+ assert palette is not None
157
+ colortable = [rgb(*palette[i : i + 3]) for i in range(0, len(palette), 3)]
158
+ elif im.mode == "RGB":
159
+ # Populate the 4th channel with 255
160
+ im = im.convert("RGBA")
161
+
162
+ data = im.tobytes("raw", "BGRA")
163
+ format = getattr(qt_format, "Format_RGB32")
164
+ elif im.mode == "RGBA":
165
+ data = im.tobytes("raw", "BGRA")
166
+ format = getattr(qt_format, "Format_ARGB32")
167
+ elif im.mode == "I;16":
168
+ im = im.point(lambda i: i * 256)
169
+
170
+ format = getattr(qt_format, "Format_Grayscale16")
171
+ else:
172
+ if exclusive_fp:
173
+ im.close()
174
+ msg = f"unsupported image mode {repr(im.mode)}"
175
+ raise ValueError(msg)
176
+
177
+ size = im.size
178
+ __data = data or align8to32(im.tobytes(), size[0], im.mode)
179
+ if exclusive_fp:
180
+ im.close()
181
+ return {"data": __data, "size": size, "format": format, "colortable": colortable}
182
+
183
+
184
+ if qt_is_installed:
185
+
186
+ class ImageQt(QImage): # type: ignore[misc]
187
+ def __init__(self, im: Image.Image | str | QByteArray) -> None:
188
+ """
189
+ An PIL image wrapper for Qt. This is a subclass of PyQt's QImage
190
+ class.
191
+
192
+ :param im: A PIL Image object, or a file name (given either as
193
+ Python string or a PyQt string object).
194
+ """
195
+ im_data = _toqclass_helper(im)
196
+ # must keep a reference, or Qt will crash!
197
+ # All QImage constructors that take data operate on an existing
198
+ # buffer, so this buffer has to hang on for the life of the image.
199
+ # Fixes https://github.com/python-pillow/Pillow/issues/1370
200
+ self.__data = im_data["data"]
201
+ super().__init__(
202
+ self.__data,
203
+ im_data["size"][0],
204
+ im_data["size"][1],
205
+ im_data["format"],
206
+ )
207
+ if im_data["colortable"]:
208
+ self.setColorTable(im_data["colortable"])
209
+
210
+
211
+ def toqimage(im: Image.Image | str | QByteArray) -> ImageQt:
212
+ return ImageQt(im)
213
+
214
+
215
+ def toqpixmap(im: Image.Image | str | QByteArray) -> QPixmap:
216
+ qimage = toqimage(im)
217
+ pixmap = getattr(QPixmap, "fromImage")(qimage)
218
+ if qt_version == "6":
219
+ pixmap.detach()
220
+ return pixmap
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/ImageSequence.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # sequence support classes
6
+ #
7
+ # history:
8
+ # 1997-02-20 fl Created
9
+ #
10
+ # Copyright (c) 1997 by Secret Labs AB.
11
+ # Copyright (c) 1997 by Fredrik Lundh.
12
+ #
13
+ # See the README file for information on usage and redistribution.
14
+ #
15
+
16
+ ##
17
+ from __future__ import annotations
18
+
19
+ from typing import Callable
20
+
21
+ from . import Image
22
+
23
+
24
+ class Iterator:
25
+ """
26
+ This class implements an iterator object that can be used to loop
27
+ over an image sequence.
28
+
29
+ You can use the ``[]`` operator to access elements by index. This operator
30
+ will raise an :py:exc:`IndexError` if you try to access a nonexistent
31
+ frame.
32
+
33
+ :param im: An image object.
34
+ """
35
+
36
+ def __init__(self, im: Image.Image) -> None:
37
+ if not hasattr(im, "seek"):
38
+ msg = "im must have seek method"
39
+ raise AttributeError(msg)
40
+ self.im = im
41
+ self.position = getattr(self.im, "_min_frame", 0)
42
+
43
+ def __getitem__(self, ix: int) -> Image.Image:
44
+ try:
45
+ self.im.seek(ix)
46
+ return self.im
47
+ except EOFError as e:
48
+ msg = "end of sequence"
49
+ raise IndexError(msg) from e
50
+
51
+ def __iter__(self) -> Iterator:
52
+ return self
53
+
54
+ def __next__(self) -> Image.Image:
55
+ try:
56
+ self.im.seek(self.position)
57
+ self.position += 1
58
+ return self.im
59
+ except EOFError as e:
60
+ msg = "end of sequence"
61
+ raise StopIteration(msg) from e
62
+
63
+
64
+ def all_frames(
65
+ im: Image.Image | list[Image.Image],
66
+ func: Callable[[Image.Image], Image.Image] | None = None,
67
+ ) -> list[Image.Image]:
68
+ """
69
+ Applies a given function to all frames in an image or a list of images.
70
+ The frames are returned as a list of separate images.
71
+
72
+ :param im: An image, or a list of images.
73
+ :param func: The function to apply to all of the image frames.
74
+ :returns: A list of images.
75
+ """
76
+ if not isinstance(im, list):
77
+ im = [im]
78
+
79
+ ims = []
80
+ for imSequence in im:
81
+ current = imSequence.tell()
82
+
83
+ ims += [im_frame.copy() for im_frame in Iterator(imSequence)]
84
+
85
+ imSequence.seek(current)
86
+ return [func(im) for im in ims] if func else ims
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/ImageShow.py ADDED
@@ -0,0 +1,362 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
179
+ pyinstaller = getattr(sys, "frozen", False) and hasattr(sys, "_MEIPASS")
180
+ executable = (not pyinstaller and sys.executable) or shutil.which("python3")
181
+ if executable:
182
+ subprocess.Popen(
183
+ [
184
+ executable,
185
+ "-c",
186
+ "import os, sys, time; time.sleep(20); os.remove(sys.argv[1])",
187
+ path,
188
+ ]
189
+ )
190
+ return 1
191
+
192
+
193
+ if sys.platform == "darwin":
194
+ register(MacViewer)
195
+
196
+
197
+ class UnixViewer(abc.ABC, Viewer):
198
+ format = "PNG"
199
+ options = {"compress_level": 1, "save_all": True}
200
+
201
+ @abc.abstractmethod
202
+ def get_command_ex(self, file: str, **options: Any) -> tuple[str, str]:
203
+ pass
204
+
205
+ def get_command(self, file: str, **options: Any) -> str:
206
+ command = self.get_command_ex(file, **options)[0]
207
+ return f"{command} {quote(file)}"
208
+
209
+
210
+ class XDGViewer(UnixViewer):
211
+ """
212
+ The freedesktop.org ``xdg-open`` command.
213
+ """
214
+
215
+ def get_command_ex(self, file: str, **options: Any) -> tuple[str, str]:
216
+ command = executable = "xdg-open"
217
+ return command, executable
218
+
219
+ def show_file(self, path: str, **options: Any) -> int:
220
+ """
221
+ Display given file.
222
+ """
223
+ if not os.path.exists(path):
224
+ raise FileNotFoundError
225
+ subprocess.Popen(["xdg-open", path])
226
+ return 1
227
+
228
+
229
+ class DisplayViewer(UnixViewer):
230
+ """
231
+ The ImageMagick ``display`` command.
232
+ This viewer supports the ``title`` parameter.
233
+ """
234
+
235
+ def get_command_ex(
236
+ self, file: str, title: str | None = None, **options: Any
237
+ ) -> tuple[str, str]:
238
+ command = executable = "display"
239
+ if title:
240
+ command += f" -title {quote(title)}"
241
+ return command, executable
242
+
243
+ def show_file(self, path: str, **options: Any) -> int:
244
+ """
245
+ Display given file.
246
+ """
247
+ if not os.path.exists(path):
248
+ raise FileNotFoundError
249
+ args = ["display"]
250
+ title = options.get("title")
251
+ if title:
252
+ args += ["-title", title]
253
+ args.append(path)
254
+
255
+ subprocess.Popen(args)
256
+ return 1
257
+
258
+
259
+ class GmDisplayViewer(UnixViewer):
260
+ """The GraphicsMagick ``gm display`` command."""
261
+
262
+ def get_command_ex(self, file: str, **options: Any) -> tuple[str, str]:
263
+ executable = "gm"
264
+ command = "gm display"
265
+ return command, executable
266
+
267
+ def show_file(self, path: str, **options: Any) -> int:
268
+ """
269
+ Display given file.
270
+ """
271
+ if not os.path.exists(path):
272
+ raise FileNotFoundError
273
+ subprocess.Popen(["gm", "display", path])
274
+ return 1
275
+
276
+
277
+ class EogViewer(UnixViewer):
278
+ """The GNOME Image Viewer ``eog`` command."""
279
+
280
+ def get_command_ex(self, file: str, **options: Any) -> tuple[str, str]:
281
+ executable = "eog"
282
+ command = "eog -n"
283
+ return command, executable
284
+
285
+ def show_file(self, path: str, **options: Any) -> int:
286
+ """
287
+ Display given file.
288
+ """
289
+ if not os.path.exists(path):
290
+ raise FileNotFoundError
291
+ subprocess.Popen(["eog", "-n", path])
292
+ return 1
293
+
294
+
295
+ class XVViewer(UnixViewer):
296
+ """
297
+ The X Viewer ``xv`` command.
298
+ This viewer supports the ``title`` parameter.
299
+ """
300
+
301
+ def get_command_ex(
302
+ self, file: str, title: str | None = None, **options: Any
303
+ ) -> tuple[str, str]:
304
+ # note: xv is pretty outdated. most modern systems have
305
+ # imagemagick's display command instead.
306
+ command = executable = "xv"
307
+ if title:
308
+ command += f" -name {quote(title)}"
309
+ return command, executable
310
+
311
+ def show_file(self, path: str, **options: Any) -> int:
312
+ """
313
+ Display given file.
314
+ """
315
+ if not os.path.exists(path):
316
+ raise FileNotFoundError
317
+ args = ["xv"]
318
+ title = options.get("title")
319
+ if title:
320
+ args += ["-name", title]
321
+ args.append(path)
322
+
323
+ subprocess.Popen(args)
324
+ return 1
325
+
326
+
327
+ if sys.platform not in ("win32", "darwin"): # unixoids
328
+ if shutil.which("xdg-open"):
329
+ register(XDGViewer)
330
+ if shutil.which("display"):
331
+ register(DisplayViewer)
332
+ if shutil.which("gm"):
333
+ register(GmDisplayViewer)
334
+ if shutil.which("eog"):
335
+ register(EogViewer)
336
+ if shutil.which("xv"):
337
+ register(XVViewer)
338
+
339
+
340
+ class IPythonViewer(Viewer):
341
+ """The viewer for IPython frontends."""
342
+
343
+ def show_image(self, image: Image.Image, **options: Any) -> int:
344
+ ipython_display(image)
345
+ return 1
346
+
347
+
348
+ try:
349
+ from IPython.display import display as ipython_display
350
+ except ImportError:
351
+ pass
352
+ else:
353
+ register(IPythonViewer)
354
+
355
+
356
+ if __name__ == "__main__":
357
+ if len(sys.argv) < 2:
358
+ print("Syntax: python3 ImageShow.py imagefile [title]")
359
+ sys.exit()
360
+
361
+ with Image.open(sys.argv[1]) as im:
362
+ print(show(im, *sys.argv[2:]))
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/ImageStat.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # global image statistics
6
+ #
7
+ # History:
8
+ # 1996-04-05 fl Created
9
+ # 1997-05-21 fl Added mask; added rms, var, stddev attributes
10
+ # 1997-08-05 fl Added median
11
+ # 1998-07-05 hk Fixed integer overflow error
12
+ #
13
+ # Notes:
14
+ # This class shows how to implement delayed evaluation of attributes.
15
+ # To get a certain value, simply access the corresponding attribute.
16
+ # The __getattr__ dispatcher takes care of the rest.
17
+ #
18
+ # Copyright (c) Secret Labs AB 1997.
19
+ # Copyright (c) Fredrik Lundh 1996-97.
20
+ #
21
+ # See the README file for information on usage and redistribution.
22
+ #
23
+ from __future__ import annotations
24
+
25
+ import math
26
+ from functools import cached_property
27
+
28
+ from . import Image
29
+
30
+
31
+ class Stat:
32
+ def __init__(
33
+ self, image_or_list: Image.Image | list[int], mask: Image.Image | None = None
34
+ ) -> None:
35
+ """
36
+ Calculate statistics for the given image. If a mask is included,
37
+ only the regions covered by that mask are included in the
38
+ statistics. You can also pass in a previously calculated histogram.
39
+
40
+ :param image: A PIL image, or a precalculated histogram.
41
+
42
+ .. note::
43
+
44
+ For a PIL image, calculations rely on the
45
+ :py:meth:`~PIL.Image.Image.histogram` method. The pixel counts are
46
+ grouped into 256 bins, even if the image has more than 8 bits per
47
+ channel. So ``I`` and ``F`` mode images have a maximum ``mean``,
48
+ ``median`` and ``rms`` of 255, and cannot have an ``extrema`` maximum
49
+ of more than 255.
50
+
51
+ :param mask: An optional mask.
52
+ """
53
+ if isinstance(image_or_list, Image.Image):
54
+ self.h = image_or_list.histogram(mask)
55
+ elif isinstance(image_or_list, list):
56
+ self.h = image_or_list
57
+ else:
58
+ msg = "first argument must be image or list" # type: ignore[unreachable]
59
+ raise TypeError(msg)
60
+ self.bands = list(range(len(self.h) // 256))
61
+
62
+ @cached_property
63
+ def extrema(self) -> list[tuple[int, int]]:
64
+ """
65
+ Min/max values for each band in the image.
66
+
67
+ .. note::
68
+ This relies on the :py:meth:`~PIL.Image.Image.histogram` method, and
69
+ simply returns the low and high bins used. This is correct for
70
+ images with 8 bits per channel, but fails for other modes such as
71
+ ``I`` or ``F``. Instead, use :py:meth:`~PIL.Image.Image.getextrema` to
72
+ return per-band extrema for the image. This is more correct and
73
+ efficient because, for non-8-bit modes, the histogram method uses
74
+ :py:meth:`~PIL.Image.Image.getextrema` to determine the bins used.
75
+ """
76
+
77
+ def minmax(histogram: list[int]) -> tuple[int, int]:
78
+ res_min, res_max = 255, 0
79
+ for i in range(256):
80
+ if histogram[i]:
81
+ res_min = i
82
+ break
83
+ for i in range(255, -1, -1):
84
+ if histogram[i]:
85
+ res_max = i
86
+ break
87
+ return res_min, res_max
88
+
89
+ return [minmax(self.h[i:]) for i in range(0, len(self.h), 256)]
90
+
91
+ @cached_property
92
+ def count(self) -> list[int]:
93
+ """Total number of pixels for each band in the image."""
94
+ return [sum(self.h[i : i + 256]) for i in range(0, len(self.h), 256)]
95
+
96
+ @cached_property
97
+ def sum(self) -> list[float]:
98
+ """Sum of all pixels for each band in the image."""
99
+
100
+ v = []
101
+ for i in range(0, len(self.h), 256):
102
+ layer_sum = 0.0
103
+ for j in range(256):
104
+ layer_sum += j * self.h[i + j]
105
+ v.append(layer_sum)
106
+ return v
107
+
108
+ @cached_property
109
+ def sum2(self) -> list[float]:
110
+ """Squared sum of all pixels for each band in the image."""
111
+
112
+ v = []
113
+ for i in range(0, len(self.h), 256):
114
+ sum2 = 0.0
115
+ for j in range(256):
116
+ sum2 += (j**2) * float(self.h[i + j])
117
+ v.append(sum2)
118
+ return v
119
+
120
+ @cached_property
121
+ def mean(self) -> list[float]:
122
+ """Average (arithmetic mean) pixel level for each band in the image."""
123
+ return [self.sum[i] / self.count[i] for i in self.bands]
124
+
125
+ @cached_property
126
+ def median(self) -> list[int]:
127
+ """Median pixel level for each band in the image."""
128
+
129
+ v = []
130
+ for i in self.bands:
131
+ s = 0
132
+ half = self.count[i] // 2
133
+ b = i * 256
134
+ for j in range(256):
135
+ s = s + self.h[b + j]
136
+ if s > half:
137
+ break
138
+ v.append(j)
139
+ return v
140
+
141
+ @cached_property
142
+ def rms(self) -> list[float]:
143
+ """RMS (root-mean-square) for each band in the image."""
144
+ return [math.sqrt(self.sum2[i] / self.count[i]) for i in self.bands]
145
+
146
+ @cached_property
147
+ def var(self) -> list[float]:
148
+ """Variance for each band in the image."""
149
+ return [
150
+ (self.sum2[i] - (self.sum[i] ** 2.0) / self.count[i]) / self.count[i]
151
+ for i in self.bands
152
+ ]
153
+
154
+ @cached_property
155
+ def stddev(self) -> list[float]:
156
+ """Standard deviation for each band in the image."""
157
+ return [math.sqrt(self.var[i]) for i in self.bands]
158
+
159
+
160
+ Global = Stat # compatibility
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/PIL/ImageTk.py ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 Any
32
+
33
+ from . import Image, ImageFile
34
+
35
+ TYPE_CHECKING = False
36
+ if TYPE_CHECKING:
37
+ from ._typing import CapsuleType
38
+
39
+ # --------------------------------------------------------------------
40
+ # Check for Tkinter interface hooks
41
+
42
+
43
+ def _get_image_from_kw(kw: dict[str, Any]) -> ImageFile.ImageFile | None:
44
+ source = None
45
+ if "file" in kw:
46
+ source = kw.pop("file")
47
+ elif "data" in kw:
48
+ source = BytesIO(kw.pop("data"))
49
+ if not source:
50
+ return None
51
+ return Image.open(source)
52
+
53
+
54
+ def _pyimagingtkcall(
55
+ command: str, photo: PhotoImage | tkinter.PhotoImage, ptr: CapsuleType
56
+ ) -> None:
57
+ tk = photo.tk
58
+ try:
59
+ tk.call(command, photo, repr(ptr))
60
+ except tkinter.TclError:
61
+ # activate Tkinter hook
62
+ # may raise an error if it cannot attach to Tkinter
63
+ from . import _imagingtk
64
+
65
+ _imagingtk.tkinit(tk.interpaddr())
66
+ tk.call(command, photo, repr(ptr))
67
+
68
+
69
+ # --------------------------------------------------------------------
70
+ # PhotoImage
71
+
72
+
73
+ class PhotoImage:
74
+ """
75
+ A Tkinter-compatible photo image. This can be used
76
+ everywhere Tkinter expects an image object. If the image is an RGBA
77
+ image, pixels having alpha 0 are treated as transparent.
78
+
79
+ The constructor takes either a PIL image, or a mode and a size.
80
+ Alternatively, you can use the ``file`` or ``data`` options to initialize
81
+ the photo image object.
82
+
83
+ :param image: Either a PIL image, or a mode string. If a mode string is
84
+ used, a size must also be given.
85
+ :param size: If the first argument is a mode string, this defines the size
86
+ of the image.
87
+ :keyword file: A filename to load the image from (using
88
+ ``Image.open(file)``).
89
+ :keyword data: An 8-bit string containing image data (as loaded from an
90
+ image file).
91
+ """
92
+
93
+ def __init__(
94
+ self,
95
+ image: Image.Image | str | None = None,
96
+ size: tuple[int, int] | None = None,
97
+ **kw: Any,
98
+ ) -> None:
99
+ # Tk compatibility: file or data
100
+ if image is None:
101
+ image = _get_image_from_kw(kw)
102
+
103
+ if image is None:
104
+ msg = "Image is required"
105
+ raise ValueError(msg)
106
+ elif isinstance(image, str):
107
+ mode = image
108
+ image = None
109
+
110
+ if size is None:
111
+ msg = "If first argument is mode, size is required"
112
+ raise ValueError(msg)
113
+ else:
114
+ # got an image instead of a mode
115
+ mode = image.mode
116
+ if mode == "P":
117
+ # palette mapped data
118
+ image.apply_transparency()
119
+ image.load()
120
+ mode = image.palette.mode if image.palette else "RGB"
121
+ size = image.size
122
+ kw["width"], kw["height"] = size
123
+
124
+ if mode not in ["1", "L", "RGB", "RGBA"]:
125
+ mode = Image.getmodebase(mode)
126
+
127
+ self.__mode = mode
128
+ self.__size = size
129
+ self.__photo = tkinter.PhotoImage(**kw)
130
+ self.tk = self.__photo.tk
131
+ if image:
132
+ self.paste(image)
133
+
134
+ def __del__(self) -> None:
135
+ try:
136
+ name = self.__photo.name
137
+ except AttributeError:
138
+ return
139
+ self.__photo.name = None
140
+ try:
141
+ self.__photo.tk.call("image", "delete", name)
142
+ except Exception:
143
+ pass # ignore internal errors
144
+
145
+ def __str__(self) -> str:
146
+ """
147
+ Get the Tkinter photo image identifier. This method is automatically
148
+ called by Tkinter whenever a PhotoImage object is passed to a Tkinter
149
+ method.
150
+
151
+ :return: A Tkinter photo image identifier (a string).
152
+ """
153
+ return str(self.__photo)
154
+
155
+ def width(self) -> int:
156
+ """
157
+ Get the width of the image.
158
+
159
+ :return: The width, in pixels.
160
+ """
161
+ return self.__size[0]
162
+
163
+ def height(self) -> int:
164
+ """
165
+ Get the height of the image.
166
+
167
+ :return: The height, in pixels.
168
+ """
169
+ return self.__size[1]
170
+
171
+ def paste(self, im: Image.Image) -> None:
172
+ """
173
+ Paste a PIL image into the photo image. Note that this can
174
+ be very slow if the photo image is displayed.
175
+
176
+ :param im: A PIL image. The size must match the target region. If the
177
+ mode does not match, the image is converted to the mode of
178
+ the bitmap image.
179
+ """
180
+ # convert to blittable
181
+ ptr = im.getim()
182
+ image = im.im
183
+ if not image.isblock() or im.mode != self.__mode:
184
+ block = Image.core.new_block(self.__mode, im.size)
185
+ image.convert2(block, image) # convert directly between buffers
186
+ ptr = block.ptr
187
+
188
+ _pyimagingtkcall("PyImagingPhoto", self.__photo, ptr)
189
+
190
+
191
+ # --------------------------------------------------------------------
192
+ # BitmapImage
193
+
194
+
195
+ class BitmapImage:
196
+ """
197
+ A Tkinter-compatible bitmap image. This can be used everywhere Tkinter
198
+ expects an image object.
199
+
200
+ The given image must have mode "1". Pixels having value 0 are treated as
201
+ transparent. Options, if any, are passed on to Tkinter. The most commonly
202
+ used option is ``foreground``, which is used to specify the color for the
203
+ non-transparent parts. See the Tkinter documentation for information on
204
+ how to specify colours.
205
+
206
+ :param image: A PIL image.
207
+ """
208
+
209
+ def __init__(self, image: Image.Image | None = None, **kw: Any) -> None:
210
+ # Tk compatibility: file or data
211
+ if image is None:
212
+ image = _get_image_from_kw(kw)
213
+
214
+ if image is None:
215
+ msg = "Image is required"
216
+ raise ValueError(msg)
217
+ self.__mode = image.mode
218
+ self.__size = image.size
219
+
220
+ self.__photo = tkinter.BitmapImage(data=image.tobitmap(), **kw)
221
+
222
+ def __del__(self) -> None:
223
+ try:
224
+ name = self.__photo.name
225
+ except AttributeError:
226
+ return
227
+ self.__photo.name = None
228
+ try:
229
+ self.__photo.tk.call("image", "delete", name)
230
+ except Exception:
231
+ pass # ignore internal errors
232
+
233
+ def width(self) -> int:
234
+ """
235
+ Get the width of the image.
236
+
237
+ :return: The width, in pixels.
238
+ """
239
+ return self.__size[0]
240
+
241
+ def height(self) -> int:
242
+ """
243
+ Get the height of the image.
244
+
245
+ :return: The height, in pixels.
246
+ """
247
+ return self.__size[1]
248
+
249
+ def __str__(self) -> str:
250
+ """
251
+ Get the Tkinter bitmap image identifier. This method is automatically
252
+ called by Tkinter whenever a BitmapImage object is passed to a Tkinter
253
+ method.
254
+
255
+ :return: A Tkinter bitmap image identifier (a string).
256
+ """
257
+ return str(self.__photo)
258
+
259
+
260
+ def getimage(photo: PhotoImage) -> Image.Image:
261
+ """Copies the contents of a PhotoImage to a PIL image memory."""
262
+ im = Image.new("RGBA", (photo.width(), photo.height()))
263
+
264
+ _pyimagingtkcall("PyImagingPhotoGet", photo, im.getim())
265
+
266
+ return im
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/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 the inverse of an affine transform matrix. For each pixel
52
+ (x, y) in the output image, the new value is taken from a position (a x +
53
+ b y + c, 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 the inverse of 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
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/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))