FusionCow commited on
Commit
e0251cb
·
verified ·
1 Parent(s): 2b6c6b1

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. .venv/bin/Activate.ps1 +247 -0
  2. .venv/bin/accelerate +6 -0
  3. .venv/bin/accelerate-config +6 -0
  4. .venv/bin/accelerate-estimate-memory +6 -0
  5. .venv/bin/accelerate-launch +6 -0
  6. .venv/bin/accelerate-merge-weights +6 -0
  7. .venv/bin/activate +76 -0
  8. .venv/bin/diffusers-cli +6 -0
  9. .venv/bin/f2py +6 -0
  10. .venv/bin/fonttools +6 -0
  11. .venv/bin/ftfy +6 -0
  12. .venv/bin/hf +6 -0
  13. .venv/bin/huggingface-cli +6 -0
  14. .venv/bin/isympy +6 -0
  15. .venv/bin/markdown_py +6 -0
  16. .venv/bin/normalizer +6 -0
  17. .venv/bin/numpy-config +6 -0
  18. .venv/bin/pip3.12 +8 -0
  19. .venv/bin/proton +6 -0
  20. .venv/bin/proton-viewer +6 -0
  21. .venv/bin/pyav +6 -0
  22. .venv/bin/pyftmerge +6 -0
  23. .venv/bin/pyftsubset +6 -0
  24. .venv/bin/tensorboard +6 -0
  25. .venv/bin/tiny-agents +6 -0
  26. .venv/bin/torchfrtrace +6 -0
  27. .venv/bin/torchrun +6 -0
  28. .venv/bin/tqdm +6 -0
  29. .venv/bin/transformers +6 -0
  30. .venv/bin/transformers-cli +6 -0
  31. .venv/bin/ttx +6 -0
  32. .venv/lib/python3.12/site-packages/MarkupSafe-3.0.2.dist-info/LICENSE.txt +28 -0
  33. .venv/lib/python3.12/site-packages/MarkupSafe-3.0.2.dist-info/METADATA +92 -0
  34. .venv/lib/python3.12/site-packages/PIL/CurImagePlugin.py +75 -0
  35. .venv/lib/python3.12/site-packages/PIL/DdsImagePlugin.py +624 -0
  36. .venv/lib/python3.12/site-packages/PIL/FtexImagePlugin.py +114 -0
  37. .venv/lib/python3.12/site-packages/PIL/GdImageFile.py +102 -0
  38. .venv/lib/python3.12/site-packages/PIL/GimpGradientFile.py +153 -0
  39. .venv/lib/python3.12/site-packages/PIL/Hdf5StubImagePlugin.py +75 -0
  40. .venv/lib/python3.12/site-packages/PIL/IcoImagePlugin.py +381 -0
  41. .venv/lib/python3.12/site-packages/PIL/ImageChops.py +311 -0
  42. .venv/lib/python3.12/site-packages/PIL/ImageColor.py +320 -0
  43. .venv/lib/python3.12/site-packages/PIL/ImageFile.py +926 -0
  44. .venv/lib/python3.12/site-packages/PIL/ImageFont.py +1312 -0
  45. .venv/lib/python3.12/site-packages/PIL/ImageMode.py +85 -0
  46. .venv/lib/python3.12/site-packages/PIL/ImageMorph.py +265 -0
  47. .venv/lib/python3.12/site-packages/PIL/ImageOps.py +746 -0
  48. .venv/lib/python3.12/site-packages/PIL/ImageQt.py +219 -0
  49. .venv/lib/python3.12/site-packages/PIL/ImageSequence.py +88 -0
  50. .venv/lib/python3.12/site-packages/PIL/ImageShow.py +362 -0
.venv/bin/Activate.ps1 ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <#
2
+ .Synopsis
3
+ Activate a Python virtual environment for the current PowerShell session.
4
+
5
+ .Description
6
+ Pushes the python executable for a virtual environment to the front of the
7
+ $Env:PATH environment variable and sets the prompt to signify that you are
8
+ in a Python virtual environment. Makes use of the command line switches as
9
+ well as the `pyvenv.cfg` file values present in the virtual environment.
10
+
11
+ .Parameter VenvDir
12
+ Path to the directory that contains the virtual environment to activate. The
13
+ default value for this is the parent of the directory that the Activate.ps1
14
+ script is located within.
15
+
16
+ .Parameter Prompt
17
+ The prompt prefix to display when this virtual environment is activated. By
18
+ default, this prompt is the name of the virtual environment folder (VenvDir)
19
+ surrounded by parentheses and followed by a single space (ie. '(.venv) ').
20
+
21
+ .Example
22
+ Activate.ps1
23
+ Activates the Python virtual environment that contains the Activate.ps1 script.
24
+
25
+ .Example
26
+ Activate.ps1 -Verbose
27
+ Activates the Python virtual environment that contains the Activate.ps1 script,
28
+ and shows extra information about the activation as it executes.
29
+
30
+ .Example
31
+ Activate.ps1 -VenvDir C:\Users\MyUser\Common\.venv
32
+ Activates the Python virtual environment located in the specified location.
33
+
34
+ .Example
35
+ Activate.ps1 -Prompt "MyPython"
36
+ Activates the Python virtual environment that contains the Activate.ps1 script,
37
+ and prefixes the current prompt with the specified string (surrounded in
38
+ parentheses) while the virtual environment is active.
39
+
40
+ .Notes
41
+ On Windows, it may be required to enable this Activate.ps1 script by setting the
42
+ execution policy for the user. You can do this by issuing the following PowerShell
43
+ command:
44
+
45
+ PS C:\> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
46
+
47
+ For more information on Execution Policies:
48
+ https://go.microsoft.com/fwlink/?LinkID=135170
49
+
50
+ #>
51
+ Param(
52
+ [Parameter(Mandatory = $false)]
53
+ [String]
54
+ $VenvDir,
55
+ [Parameter(Mandatory = $false)]
56
+ [String]
57
+ $Prompt
58
+ )
59
+
60
+ <# Function declarations --------------------------------------------------- #>
61
+
62
+ <#
63
+ .Synopsis
64
+ Remove all shell session elements added by the Activate script, including the
65
+ addition of the virtual environment's Python executable from the beginning of
66
+ the PATH variable.
67
+
68
+ .Parameter NonDestructive
69
+ If present, do not remove this function from the global namespace for the
70
+ session.
71
+
72
+ #>
73
+ function global:deactivate ([switch]$NonDestructive) {
74
+ # Revert to original values
75
+
76
+ # The prior prompt:
77
+ if (Test-Path -Path Function:_OLD_VIRTUAL_PROMPT) {
78
+ Copy-Item -Path Function:_OLD_VIRTUAL_PROMPT -Destination Function:prompt
79
+ Remove-Item -Path Function:_OLD_VIRTUAL_PROMPT
80
+ }
81
+
82
+ # The prior PYTHONHOME:
83
+ if (Test-Path -Path Env:_OLD_VIRTUAL_PYTHONHOME) {
84
+ Copy-Item -Path Env:_OLD_VIRTUAL_PYTHONHOME -Destination Env:PYTHONHOME
85
+ Remove-Item -Path Env:_OLD_VIRTUAL_PYTHONHOME
86
+ }
87
+
88
+ # The prior PATH:
89
+ if (Test-Path -Path Env:_OLD_VIRTUAL_PATH) {
90
+ Copy-Item -Path Env:_OLD_VIRTUAL_PATH -Destination Env:PATH
91
+ Remove-Item -Path Env:_OLD_VIRTUAL_PATH
92
+ }
93
+
94
+ # Just remove the VIRTUAL_ENV altogether:
95
+ if (Test-Path -Path Env:VIRTUAL_ENV) {
96
+ Remove-Item -Path env:VIRTUAL_ENV
97
+ }
98
+
99
+ # Just remove VIRTUAL_ENV_PROMPT altogether.
100
+ if (Test-Path -Path Env:VIRTUAL_ENV_PROMPT) {
101
+ Remove-Item -Path env:VIRTUAL_ENV_PROMPT
102
+ }
103
+
104
+ # Just remove the _PYTHON_VENV_PROMPT_PREFIX altogether:
105
+ if (Get-Variable -Name "_PYTHON_VENV_PROMPT_PREFIX" -ErrorAction SilentlyContinue) {
106
+ Remove-Variable -Name _PYTHON_VENV_PROMPT_PREFIX -Scope Global -Force
107
+ }
108
+
109
+ # Leave deactivate function in the global namespace if requested:
110
+ if (-not $NonDestructive) {
111
+ Remove-Item -Path function:deactivate
112
+ }
113
+ }
114
+
115
+ <#
116
+ .Description
117
+ Get-PyVenvConfig parses the values from the pyvenv.cfg file located in the
118
+ given folder, and returns them in a map.
119
+
120
+ For each line in the pyvenv.cfg file, if that line can be parsed into exactly
121
+ two strings separated by `=` (with any amount of whitespace surrounding the =)
122
+ then it is considered a `key = value` line. The left hand string is the key,
123
+ the right hand is the value.
124
+
125
+ If the value starts with a `'` or a `"` then the first and last character is
126
+ stripped from the value before being captured.
127
+
128
+ .Parameter ConfigDir
129
+ Path to the directory that contains the `pyvenv.cfg` file.
130
+ #>
131
+ function Get-PyVenvConfig(
132
+ [String]
133
+ $ConfigDir
134
+ ) {
135
+ Write-Verbose "Given ConfigDir=$ConfigDir, obtain values in pyvenv.cfg"
136
+
137
+ # Ensure the file exists, and issue a warning if it doesn't (but still allow the function to continue).
138
+ $pyvenvConfigPath = Join-Path -Resolve -Path $ConfigDir -ChildPath 'pyvenv.cfg' -ErrorAction Continue
139
+
140
+ # An empty map will be returned if no config file is found.
141
+ $pyvenvConfig = @{ }
142
+
143
+ if ($pyvenvConfigPath) {
144
+
145
+ Write-Verbose "File exists, parse `key = value` lines"
146
+ $pyvenvConfigContent = Get-Content -Path $pyvenvConfigPath
147
+
148
+ $pyvenvConfigContent | ForEach-Object {
149
+ $keyval = $PSItem -split "\s*=\s*", 2
150
+ if ($keyval[0] -and $keyval[1]) {
151
+ $val = $keyval[1]
152
+
153
+ # Remove extraneous quotations around a string value.
154
+ if ("'""".Contains($val.Substring(0, 1))) {
155
+ $val = $val.Substring(1, $val.Length - 2)
156
+ }
157
+
158
+ $pyvenvConfig[$keyval[0]] = $val
159
+ Write-Verbose "Adding Key: '$($keyval[0])'='$val'"
160
+ }
161
+ }
162
+ }
163
+ return $pyvenvConfig
164
+ }
165
+
166
+
167
+ <# Begin Activate script --------------------------------------------------- #>
168
+
169
+ # Determine the containing directory of this script
170
+ $VenvExecPath = Split-Path -Parent $MyInvocation.MyCommand.Definition
171
+ $VenvExecDir = Get-Item -Path $VenvExecPath
172
+
173
+ Write-Verbose "Activation script is located in path: '$VenvExecPath'"
174
+ Write-Verbose "VenvExecDir Fullname: '$($VenvExecDir.FullName)"
175
+ Write-Verbose "VenvExecDir Name: '$($VenvExecDir.Name)"
176
+
177
+ # Set values required in priority: CmdLine, ConfigFile, Default
178
+ # First, get the location of the virtual environment, it might not be
179
+ # VenvExecDir if specified on the command line.
180
+ if ($VenvDir) {
181
+ Write-Verbose "VenvDir given as parameter, using '$VenvDir' to determine values"
182
+ }
183
+ else {
184
+ Write-Verbose "VenvDir not given as a parameter, using parent directory name as VenvDir."
185
+ $VenvDir = $VenvExecDir.Parent.FullName.TrimEnd("\\/")
186
+ Write-Verbose "VenvDir=$VenvDir"
187
+ }
188
+
189
+ # Next, read the `pyvenv.cfg` file to determine any required value such
190
+ # as `prompt`.
191
+ $pyvenvCfg = Get-PyVenvConfig -ConfigDir $VenvDir
192
+
193
+ # Next, set the prompt from the command line, or the config file, or
194
+ # just use the name of the virtual environment folder.
195
+ if ($Prompt) {
196
+ Write-Verbose "Prompt specified as argument, using '$Prompt'"
197
+ }
198
+ else {
199
+ Write-Verbose "Prompt not specified as argument to script, checking pyvenv.cfg value"
200
+ if ($pyvenvCfg -and $pyvenvCfg['prompt']) {
201
+ Write-Verbose " Setting based on value in pyvenv.cfg='$($pyvenvCfg['prompt'])'"
202
+ $Prompt = $pyvenvCfg['prompt'];
203
+ }
204
+ else {
205
+ Write-Verbose " Setting prompt based on parent's directory's name. (Is the directory name passed to venv module when creating the virtual environment)"
206
+ Write-Verbose " Got leaf-name of $VenvDir='$(Split-Path -Path $venvDir -Leaf)'"
207
+ $Prompt = Split-Path -Path $venvDir -Leaf
208
+ }
209
+ }
210
+
211
+ Write-Verbose "Prompt = '$Prompt'"
212
+ Write-Verbose "VenvDir='$VenvDir'"
213
+
214
+ # Deactivate any currently active virtual environment, but leave the
215
+ # deactivate function in place.
216
+ deactivate -nondestructive
217
+
218
+ # Now set the environment variable VIRTUAL_ENV, used by many tools to determine
219
+ # that there is an activated venv.
220
+ $env:VIRTUAL_ENV = $VenvDir
221
+
222
+ if (-not $Env:VIRTUAL_ENV_DISABLE_PROMPT) {
223
+
224
+ Write-Verbose "Setting prompt to '$Prompt'"
225
+
226
+ # Set the prompt to include the env name
227
+ # Make sure _OLD_VIRTUAL_PROMPT is global
228
+ function global:_OLD_VIRTUAL_PROMPT { "" }
229
+ Copy-Item -Path function:prompt -Destination function:_OLD_VIRTUAL_PROMPT
230
+ New-Variable -Name _PYTHON_VENV_PROMPT_PREFIX -Description "Python virtual environment prompt prefix" -Scope Global -Option ReadOnly -Visibility Public -Value $Prompt
231
+
232
+ function global:prompt {
233
+ Write-Host -NoNewline -ForegroundColor Green "($_PYTHON_VENV_PROMPT_PREFIX) "
234
+ _OLD_VIRTUAL_PROMPT
235
+ }
236
+ $env:VIRTUAL_ENV_PROMPT = $Prompt
237
+ }
238
+
239
+ # Clear PYTHONHOME
240
+ if (Test-Path -Path Env:PYTHONHOME) {
241
+ Copy-Item -Path Env:PYTHONHOME -Destination Env:_OLD_VIRTUAL_PYTHONHOME
242
+ Remove-Item -Path Env:PYTHONHOME
243
+ }
244
+
245
+ # Add the venv to the PATH
246
+ Copy-Item -Path Env:PATH -Destination Env:_OLD_VIRTUAL_PATH
247
+ $Env:PATH = "$VenvExecDir$([System.IO.Path]::PathSeparator)$Env:PATH"
.venv/bin/accelerate ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/workspace/musubi-tuner/.venv/bin/python
2
+ import sys
3
+ from accelerate.commands.accelerate_cli import main
4
+ if __name__ == '__main__':
5
+ sys.argv[0] = sys.argv[0].removesuffix('.exe')
6
+ sys.exit(main())
.venv/bin/accelerate-config ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/workspace/musubi-tuner/.venv/bin/python
2
+ import sys
3
+ from accelerate.commands.config import main
4
+ if __name__ == '__main__':
5
+ sys.argv[0] = sys.argv[0].removesuffix('.exe')
6
+ sys.exit(main())
.venv/bin/accelerate-estimate-memory ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/workspace/musubi-tuner/.venv/bin/python
2
+ import sys
3
+ from accelerate.commands.estimate import main
4
+ if __name__ == '__main__':
5
+ sys.argv[0] = sys.argv[0].removesuffix('.exe')
6
+ sys.exit(main())
.venv/bin/accelerate-launch ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/workspace/musubi-tuner/.venv/bin/python
2
+ import sys
3
+ from accelerate.commands.launch import main
4
+ if __name__ == '__main__':
5
+ sys.argv[0] = sys.argv[0].removesuffix('.exe')
6
+ sys.exit(main())
.venv/bin/accelerate-merge-weights ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/workspace/musubi-tuner/.venv/bin/python
2
+ import sys
3
+ from accelerate.commands.merge import main
4
+ if __name__ == '__main__':
5
+ sys.argv[0] = sys.argv[0].removesuffix('.exe')
6
+ sys.exit(main())
.venv/bin/activate ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file must be used with "source bin/activate" *from bash*
2
+ # You cannot run it directly
3
+
4
+ deactivate () {
5
+ # reset old environment variables
6
+ if [ -n "${_OLD_VIRTUAL_PATH:-}" ] ; then
7
+ PATH="${_OLD_VIRTUAL_PATH:-}"
8
+ export PATH
9
+ unset _OLD_VIRTUAL_PATH
10
+ fi
11
+ if [ -n "${_OLD_VIRTUAL_PYTHONHOME:-}" ] ; then
12
+ PYTHONHOME="${_OLD_VIRTUAL_PYTHONHOME:-}"
13
+ export PYTHONHOME
14
+ unset _OLD_VIRTUAL_PYTHONHOME
15
+ fi
16
+
17
+ # Call hash to forget past locations. Without forgetting
18
+ # past locations the $PATH changes we made may not be respected.
19
+ # See "man bash" for more details. hash is usually a builtin of your shell
20
+ hash -r 2> /dev/null
21
+
22
+ if [ -n "${_OLD_VIRTUAL_PS1:-}" ] ; then
23
+ PS1="${_OLD_VIRTUAL_PS1:-}"
24
+ export PS1
25
+ unset _OLD_VIRTUAL_PS1
26
+ fi
27
+
28
+ unset VIRTUAL_ENV
29
+ unset VIRTUAL_ENV_PROMPT
30
+ if [ ! "${1:-}" = "nondestructive" ] ; then
31
+ # Self destruct!
32
+ unset -f deactivate
33
+ fi
34
+ }
35
+
36
+ # unset irrelevant variables
37
+ deactivate nondestructive
38
+
39
+ # on Windows, a path can contain colons and backslashes and has to be converted:
40
+ case "$(uname)" in
41
+ CYGWIN*|MSYS*|MINGW*)
42
+ # transform D:\path\to\venv to /d/path/to/venv on MSYS and MINGW
43
+ # and to /cygdrive/d/path/to/venv on Cygwin
44
+ VIRTUAL_ENV=$(cygpath /workspace/musubi-tuner/.venv)
45
+ export VIRTUAL_ENV
46
+ ;;
47
+ *)
48
+ # use the path as-is
49
+ export VIRTUAL_ENV=/workspace/musubi-tuner/.venv
50
+ ;;
51
+ esac
52
+
53
+ _OLD_VIRTUAL_PATH="$PATH"
54
+ PATH="$VIRTUAL_ENV/"bin":$PATH"
55
+ export PATH
56
+
57
+ VIRTUAL_ENV_PROMPT='(.venv) '
58
+ export VIRTUAL_ENV_PROMPT
59
+
60
+ # unset PYTHONHOME if set
61
+ # this will fail if PYTHONHOME is set to the empty string (which is bad anyway)
62
+ # could use `if (set -u; : $PYTHONHOME) ;` in bash
63
+ if [ -n "${PYTHONHOME:-}" ] ; then
64
+ _OLD_VIRTUAL_PYTHONHOME="${PYTHONHOME:-}"
65
+ unset PYTHONHOME
66
+ fi
67
+
68
+ if [ -z "${VIRTUAL_ENV_DISABLE_PROMPT:-}" ] ; then
69
+ _OLD_VIRTUAL_PS1="${PS1:-}"
70
+ PS1="("'(.venv) '") ${PS1:-}"
71
+ export PS1
72
+ fi
73
+
74
+ # Call hash to forget past commands. Without forgetting
75
+ # past commands the $PATH changes we made may not be respected
76
+ hash -r 2> /dev/null
.venv/bin/diffusers-cli ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/workspace/musubi-tuner/.venv/bin/python
2
+ import sys
3
+ from diffusers.commands.diffusers_cli import main
4
+ if __name__ == '__main__':
5
+ sys.argv[0] = sys.argv[0].removesuffix('.exe')
6
+ sys.exit(main())
.venv/bin/f2py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/workspace/musubi-tuner/.venv/bin/python
2
+ import sys
3
+ from numpy.f2py.f2py2e import main
4
+ if __name__ == '__main__':
5
+ sys.argv[0] = sys.argv[0].removesuffix('.exe')
6
+ sys.exit(main())
.venv/bin/fonttools ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/workspace/musubi-tuner/.venv/bin/python
2
+ import sys
3
+ from fontTools.__main__ import main
4
+ if __name__ == '__main__':
5
+ sys.argv[0] = sys.argv[0].removesuffix('.exe')
6
+ sys.exit(main())
.venv/bin/ftfy ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/workspace/musubi-tuner/.venv/bin/python
2
+ import sys
3
+ from ftfy.cli import main
4
+ if __name__ == '__main__':
5
+ sys.argv[0] = sys.argv[0].removesuffix('.exe')
6
+ sys.exit(main())
.venv/bin/hf ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/workspace/musubi-tuner/.venv/bin/python
2
+ import sys
3
+ from huggingface_hub.cli.hf import main
4
+ if __name__ == '__main__':
5
+ sys.argv[0] = sys.argv[0].removesuffix('.exe')
6
+ sys.exit(main())
.venv/bin/huggingface-cli ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/workspace/musubi-tuner/.venv/bin/python
2
+ import sys
3
+ from huggingface_hub.commands.huggingface_cli import main
4
+ if __name__ == '__main__':
5
+ sys.argv[0] = sys.argv[0].removesuffix('.exe')
6
+ sys.exit(main())
.venv/bin/isympy ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/workspace/musubi-tuner/.venv/bin/python
2
+ import sys
3
+ from isympy import main
4
+ if __name__ == '__main__':
5
+ sys.argv[0] = sys.argv[0].removesuffix('.exe')
6
+ sys.exit(main())
.venv/bin/markdown_py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/workspace/musubi-tuner/.venv/bin/python
2
+ import sys
3
+ from markdown.__main__ import run
4
+ if __name__ == '__main__':
5
+ sys.argv[0] = sys.argv[0].removesuffix('.exe')
6
+ sys.exit(run())
.venv/bin/normalizer ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/workspace/musubi-tuner/.venv/bin/python
2
+ import sys
3
+ from charset_normalizer.cli import cli_detect
4
+ if __name__ == '__main__':
5
+ sys.argv[0] = sys.argv[0].removesuffix('.exe')
6
+ sys.exit(cli_detect())
.venv/bin/numpy-config ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/workspace/musubi-tuner/.venv/bin/python
2
+ import sys
3
+ from numpy._configtool import main
4
+ if __name__ == '__main__':
5
+ sys.argv[0] = sys.argv[0].removesuffix('.exe')
6
+ sys.exit(main())
.venv/bin/pip3.12 ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ #!/workspace/musubi-tuner/.venv/bin/python
2
+ # -*- coding: utf-8 -*-
3
+ import re
4
+ import sys
5
+ from pip._internal.cli.main import main
6
+ if __name__ == '__main__':
7
+ sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
8
+ sys.exit(main())
.venv/bin/proton ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/workspace/musubi-tuner/.venv/bin/python
2
+ import sys
3
+ from triton.profiler.proton import main
4
+ if __name__ == '__main__':
5
+ sys.argv[0] = sys.argv[0].removesuffix('.exe')
6
+ sys.exit(main())
.venv/bin/proton-viewer ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/workspace/musubi-tuner/.venv/bin/python
2
+ import sys
3
+ from triton.profiler.viewer import main
4
+ if __name__ == '__main__':
5
+ sys.argv[0] = sys.argv[0].removesuffix('.exe')
6
+ sys.exit(main())
.venv/bin/pyav ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/workspace/musubi-tuner/.venv/bin/python
2
+ import sys
3
+ from av.__main__ import main
4
+ if __name__ == '__main__':
5
+ sys.argv[0] = sys.argv[0].removesuffix('.exe')
6
+ sys.exit(main())
.venv/bin/pyftmerge ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/workspace/musubi-tuner/.venv/bin/python
2
+ import sys
3
+ from fontTools.merge import main
4
+ if __name__ == '__main__':
5
+ sys.argv[0] = sys.argv[0].removesuffix('.exe')
6
+ sys.exit(main())
.venv/bin/pyftsubset ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/workspace/musubi-tuner/.venv/bin/python
2
+ import sys
3
+ from fontTools.subset import main
4
+ if __name__ == '__main__':
5
+ sys.argv[0] = sys.argv[0].removesuffix('.exe')
6
+ sys.exit(main())
.venv/bin/tensorboard ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/workspace/musubi-tuner/.venv/bin/python
2
+ import sys
3
+ from tensorboard.main import run_main
4
+ if __name__ == '__main__':
5
+ sys.argv[0] = sys.argv[0].removesuffix('.exe')
6
+ sys.exit(run_main())
.venv/bin/tiny-agents ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/workspace/musubi-tuner/.venv/bin/python
2
+ import sys
3
+ from huggingface_hub.inference._mcp.cli import app
4
+ if __name__ == '__main__':
5
+ sys.argv[0] = sys.argv[0].removesuffix('.exe')
6
+ sys.exit(app())
.venv/bin/torchfrtrace ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/workspace/musubi-tuner/.venv/bin/python
2
+ import sys
3
+ from tools.flight_recorder.fr_trace import main
4
+ if __name__ == '__main__':
5
+ sys.argv[0] = sys.argv[0].removesuffix('.exe')
6
+ sys.exit(main())
.venv/bin/torchrun ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/workspace/musubi-tuner/.venv/bin/python
2
+ import sys
3
+ from torch.distributed.run import main
4
+ if __name__ == '__main__':
5
+ sys.argv[0] = sys.argv[0].removesuffix('.exe')
6
+ sys.exit(main())
.venv/bin/tqdm ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/workspace/musubi-tuner/.venv/bin/python
2
+ import sys
3
+ from tqdm.cli import main
4
+ if __name__ == '__main__':
5
+ sys.argv[0] = sys.argv[0].removesuffix('.exe')
6
+ sys.exit(main())
.venv/bin/transformers ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/workspace/musubi-tuner/.venv/bin/python
2
+ import sys
3
+ from transformers.commands.transformers_cli import main
4
+ if __name__ == '__main__':
5
+ sys.argv[0] = sys.argv[0].removesuffix('.exe')
6
+ sys.exit(main())
.venv/bin/transformers-cli ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/workspace/musubi-tuner/.venv/bin/python
2
+ import sys
3
+ from transformers.commands.transformers_cli import main_cli
4
+ if __name__ == '__main__':
5
+ sys.argv[0] = sys.argv[0].removesuffix('.exe')
6
+ sys.exit(main_cli())
.venv/bin/ttx ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/workspace/musubi-tuner/.venv/bin/python
2
+ import sys
3
+ from fontTools.ttx import main
4
+ if __name__ == '__main__':
5
+ sys.argv[0] = sys.argv[0].removesuffix('.exe')
6
+ sys.exit(main())
.venv/lib/python3.12/site-packages/MarkupSafe-3.0.2.dist-info/LICENSE.txt ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright 2010 Pallets
2
+
3
+ Redistribution and use in source and binary forms, with or without
4
+ modification, are permitted provided that the following conditions are
5
+ met:
6
+
7
+ 1. Redistributions of source code must retain the above copyright
8
+ notice, this list of conditions and the following disclaimer.
9
+
10
+ 2. Redistributions in binary form must reproduce the above copyright
11
+ notice, this list of conditions and the following disclaimer in the
12
+ documentation and/or other materials provided with the distribution.
13
+
14
+ 3. Neither the name of the copyright holder nor the names of its
15
+ contributors may be used to endorse or promote products derived from
16
+ this software without specific prior written permission.
17
+
18
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
21
+ PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22
+ HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
24
+ TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
25
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
26
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
27
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
28
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
.venv/lib/python3.12/site-packages/MarkupSafe-3.0.2.dist-info/METADATA ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.1
2
+ Name: MarkupSafe
3
+ Version: 3.0.2
4
+ Summary: Safely add untrusted strings to HTML/XML markup.
5
+ Maintainer-email: Pallets <contact@palletsprojects.com>
6
+ License: Copyright 2010 Pallets
7
+
8
+ Redistribution and use in source and binary forms, with or without
9
+ modification, are permitted provided that the following conditions are
10
+ met:
11
+
12
+ 1. Redistributions of source code must retain the above copyright
13
+ notice, this list of conditions and the following disclaimer.
14
+
15
+ 2. Redistributions in binary form must reproduce the above copyright
16
+ notice, this list of conditions and the following disclaimer in the
17
+ documentation and/or other materials provided with the distribution.
18
+
19
+ 3. Neither the name of the copyright holder nor the names of its
20
+ contributors may be used to endorse or promote products derived from
21
+ this software without specific prior written permission.
22
+
23
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
26
+ PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27
+ HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
29
+ TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
30
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
31
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
32
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
33
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34
+
35
+ Project-URL: Donate, https://palletsprojects.com/donate
36
+ Project-URL: Documentation, https://markupsafe.palletsprojects.com/
37
+ Project-URL: Changes, https://markupsafe.palletsprojects.com/changes/
38
+ Project-URL: Source, https://github.com/pallets/markupsafe/
39
+ Project-URL: Chat, https://discord.gg/pallets
40
+ Classifier: Development Status :: 5 - Production/Stable
41
+ Classifier: Environment :: Web Environment
42
+ Classifier: Intended Audience :: Developers
43
+ Classifier: License :: OSI Approved :: BSD License
44
+ Classifier: Operating System :: OS Independent
45
+ Classifier: Programming Language :: Python
46
+ Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
47
+ Classifier: Topic :: Text Processing :: Markup :: HTML
48
+ Classifier: Typing :: Typed
49
+ Requires-Python: >=3.9
50
+ Description-Content-Type: text/markdown
51
+ License-File: LICENSE.txt
52
+
53
+ # MarkupSafe
54
+
55
+ MarkupSafe implements a text object that escapes characters so it is
56
+ safe to use in HTML and XML. Characters that have special meanings are
57
+ replaced so that they display as the actual characters. This mitigates
58
+ injection attacks, meaning untrusted user input can safely be displayed
59
+ on a page.
60
+
61
+
62
+ ## Examples
63
+
64
+ ```pycon
65
+ >>> from markupsafe import Markup, escape
66
+
67
+ >>> # escape replaces special characters and wraps in Markup
68
+ >>> escape("<script>alert(document.cookie);</script>")
69
+ Markup('&lt;script&gt;alert(document.cookie);&lt;/script&gt;')
70
+
71
+ >>> # wrap in Markup to mark text "safe" and prevent escaping
72
+ >>> Markup("<strong>Hello</strong>")
73
+ Markup('<strong>hello</strong>')
74
+
75
+ >>> escape(Markup("<strong>Hello</strong>"))
76
+ Markup('<strong>hello</strong>')
77
+
78
+ >>> # Markup is a str subclass
79
+ >>> # methods and operators escape their arguments
80
+ >>> template = Markup("Hello <em>{name}</em>")
81
+ >>> template.format(name='"World"')
82
+ Markup('Hello <em>&#34;World&#34;</em>')
83
+ ```
84
+
85
+ ## Donate
86
+
87
+ The Pallets organization develops and supports MarkupSafe and other
88
+ popular packages. In order to grow the community of contributors and
89
+ users, and allow the maintainers to devote more time to the projects,
90
+ [please donate today][].
91
+
92
+ [please donate today]: https://palletsprojects.com/donate
.venv/lib/python3.12/site-packages/PIL/CurImagePlugin.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # Windows Cursor support for PIL
6
+ #
7
+ # notes:
8
+ # uses BmpImagePlugin.py to read the bitmap data.
9
+ #
10
+ # history:
11
+ # 96-05-27 fl Created
12
+ #
13
+ # Copyright (c) Secret Labs AB 1997.
14
+ # Copyright (c) Fredrik Lundh 1996.
15
+ #
16
+ # See the README file for information on usage and redistribution.
17
+ #
18
+ from __future__ import annotations
19
+
20
+ from . import BmpImagePlugin, Image
21
+ from ._binary import i16le as i16
22
+ from ._binary import i32le as i32
23
+
24
+ #
25
+ # --------------------------------------------------------------------
26
+
27
+
28
+ def _accept(prefix: bytes) -> bool:
29
+ return prefix.startswith(b"\0\0\2\0")
30
+
31
+
32
+ ##
33
+ # Image plugin for Windows Cursor files.
34
+
35
+
36
+ class CurImageFile(BmpImagePlugin.BmpImageFile):
37
+ format = "CUR"
38
+ format_description = "Windows Cursor"
39
+
40
+ def _open(self) -> None:
41
+ assert self.fp is not None
42
+ offset = self.fp.tell()
43
+
44
+ # check magic
45
+ s = self.fp.read(6)
46
+ if not _accept(s):
47
+ msg = "not a CUR file"
48
+ raise SyntaxError(msg)
49
+
50
+ # pick the largest cursor in the file
51
+ m = b""
52
+ for i in range(i16(s, 4)):
53
+ s = self.fp.read(16)
54
+ if not m:
55
+ m = s
56
+ elif s[0] > m[0] and s[1] > m[1]:
57
+ m = s
58
+ if not m:
59
+ msg = "No cursors were found"
60
+ raise TypeError(msg)
61
+
62
+ # load as bitmap
63
+ self._bitmap(i32(m, 12) + offset)
64
+
65
+ # patch up the bitmap height
66
+ self._size = self.size[0], self.size[1] // 2
67
+ self.tile = [self.tile[0]._replace(extents=(0, 0) + self.size)]
68
+
69
+
70
+ #
71
+ # --------------------------------------------------------------------
72
+
73
+ Image.register_open(CurImageFile.format, CurImageFile, _accept)
74
+
75
+ Image.register_extension(CurImageFile.format, ".cur")
.venv/lib/python3.12/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")
.venv/lib/python3.12/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"])
.venv/lib/python3.12/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
.venv/lib/python3.12/site-packages/PIL/GimpGradientFile.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Python Imaging Library
3
+ # $Id$
4
+ #
5
+ # stuff to read (and render) GIMP gradient files
6
+ #
7
+ # History:
8
+ # 97-08-23 fl Created
9
+ #
10
+ # Copyright (c) Secret Labs AB 1997.
11
+ # Copyright (c) Fredrik Lundh 1997.
12
+ #
13
+ # See the README file for information on usage and redistribution.
14
+ #
15
+
16
+ """
17
+ Stuff to translate curve segments to palette values (derived from
18
+ the corresponding code in GIMP, written by Federico Mena Quintero.
19
+ See the GIMP distribution for more information.)
20
+ """
21
+ from __future__ import annotations
22
+
23
+ from math import log, pi, sin, sqrt
24
+
25
+ from ._binary import o8
26
+
27
+ TYPE_CHECKING = False
28
+ if TYPE_CHECKING:
29
+ from collections.abc import Callable
30
+ from typing import IO
31
+
32
+ EPSILON = 1e-10
33
+ """""" # Enable auto-doc for data member
34
+
35
+
36
+ def linear(middle: float, pos: float) -> float:
37
+ if pos <= middle:
38
+ if middle < EPSILON:
39
+ return 0.0
40
+ else:
41
+ return 0.5 * pos / middle
42
+ else:
43
+ pos = pos - middle
44
+ middle = 1.0 - middle
45
+ if middle < EPSILON:
46
+ return 1.0
47
+ else:
48
+ return 0.5 + 0.5 * pos / middle
49
+
50
+
51
+ def curved(middle: float, pos: float) -> float:
52
+ return pos ** (log(0.5) / log(max(middle, EPSILON)))
53
+
54
+
55
+ def sine(middle: float, pos: float) -> float:
56
+ return (sin((-pi / 2.0) + pi * linear(middle, pos)) + 1.0) / 2.0
57
+
58
+
59
+ def sphere_increasing(middle: float, pos: float) -> float:
60
+ return sqrt(1.0 - (linear(middle, pos) - 1.0) ** 2)
61
+
62
+
63
+ def sphere_decreasing(middle: float, pos: float) -> float:
64
+ return 1.0 - sqrt(1.0 - linear(middle, pos) ** 2)
65
+
66
+
67
+ SEGMENTS = [linear, curved, sine, sphere_increasing, sphere_decreasing]
68
+ """""" # Enable auto-doc for data member
69
+
70
+
71
+ class GradientFile:
72
+ gradient: (
73
+ list[
74
+ tuple[
75
+ float,
76
+ float,
77
+ float,
78
+ list[float],
79
+ list[float],
80
+ Callable[[float, float], float],
81
+ ]
82
+ ]
83
+ | None
84
+ ) = None
85
+
86
+ def getpalette(self, entries: int = 256) -> tuple[bytes, str]:
87
+ assert self.gradient is not None
88
+ palette = []
89
+
90
+ ix = 0
91
+ x0, x1, xm, rgb0, rgb1, segment = self.gradient[ix]
92
+
93
+ for i in range(entries):
94
+ x = i / (entries - 1)
95
+
96
+ while x1 < x:
97
+ ix += 1
98
+ x0, x1, xm, rgb0, rgb1, segment = self.gradient[ix]
99
+
100
+ w = x1 - x0
101
+
102
+ if w < EPSILON:
103
+ scale = segment(0.5, 0.5)
104
+ else:
105
+ scale = segment((xm - x0) / w, (x - x0) / w)
106
+
107
+ # expand to RGBA
108
+ r = o8(int(255 * ((rgb1[0] - rgb0[0]) * scale + rgb0[0]) + 0.5))
109
+ g = o8(int(255 * ((rgb1[1] - rgb0[1]) * scale + rgb0[1]) + 0.5))
110
+ b = o8(int(255 * ((rgb1[2] - rgb0[2]) * scale + rgb0[2]) + 0.5))
111
+ a = o8(int(255 * ((rgb1[3] - rgb0[3]) * scale + rgb0[3]) + 0.5))
112
+
113
+ # add to palette
114
+ palette.append(r + g + b + a)
115
+
116
+ return b"".join(palette), "RGBA"
117
+
118
+
119
+ class GimpGradientFile(GradientFile):
120
+ """File handler for GIMP's gradient format."""
121
+
122
+ def __init__(self, fp: IO[bytes]) -> None:
123
+ if not fp.readline().startswith(b"GIMP Gradient"):
124
+ msg = "not a GIMP gradient file"
125
+ raise SyntaxError(msg)
126
+
127
+ line = fp.readline()
128
+
129
+ # GIMP 1.2 gradient files don't contain a name, but GIMP 1.3 files do
130
+ if line.startswith(b"Name: "):
131
+ line = fp.readline().strip()
132
+
133
+ count = int(line)
134
+
135
+ self.gradient = []
136
+
137
+ for i in range(count):
138
+ s = fp.readline().split()
139
+ w = [float(x) for x in s[:11]]
140
+
141
+ x0, x1 = w[0], w[2]
142
+ xm = w[1]
143
+ rgb0 = w[3:7]
144
+ rgb1 = w[7:11]
145
+
146
+ segment = SEGMENTS[int(s[11])]
147
+ cspace = int(s[12])
148
+
149
+ if cspace != 0:
150
+ msg = "cannot handle HSV colour space"
151
+ raise OSError(msg)
152
+
153
+ self.gradient.append((x0, x1, xm, rgb0, rgb1, segment))
.venv/lib/python3.12/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"])
.venv/lib/python3.12/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")
.venv/lib/python3.12/site-packages/PIL/ImageChops.py ADDED
@@ -0,0 +1,311 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # standard channel operations
6
+ #
7
+ # History:
8
+ # 1996-03-24 fl Created
9
+ # 1996-08-13 fl Added logical operations (for "1" images)
10
+ # 2000-10-12 fl Added offset method (from Image.py)
11
+ #
12
+ # Copyright (c) 1997-2000 by Secret Labs AB
13
+ # Copyright (c) 1996-2000 by Fredrik Lundh
14
+ #
15
+ # See the README file for information on usage and redistribution.
16
+ #
17
+
18
+ from __future__ import annotations
19
+
20
+ from . import Image
21
+
22
+
23
+ def constant(image: Image.Image, value: int) -> Image.Image:
24
+ """Fill a channel with a given gray level.
25
+
26
+ :rtype: :py:class:`~PIL.Image.Image`
27
+ """
28
+
29
+ return Image.new("L", image.size, value)
30
+
31
+
32
+ def duplicate(image: Image.Image) -> Image.Image:
33
+ """Copy a channel. Alias for :py:meth:`PIL.Image.Image.copy`.
34
+
35
+ :rtype: :py:class:`~PIL.Image.Image`
36
+ """
37
+
38
+ return image.copy()
39
+
40
+
41
+ def invert(image: Image.Image) -> Image.Image:
42
+ """
43
+ Invert an image (channel). ::
44
+
45
+ out = MAX - image
46
+
47
+ :rtype: :py:class:`~PIL.Image.Image`
48
+ """
49
+
50
+ image.load()
51
+ return image._new(image.im.chop_invert())
52
+
53
+
54
+ def lighter(image1: Image.Image, image2: Image.Image) -> Image.Image:
55
+ """
56
+ Compares the two images, pixel by pixel, and returns a new image containing
57
+ the lighter values. ::
58
+
59
+ out = max(image1, image2)
60
+
61
+ :rtype: :py:class:`~PIL.Image.Image`
62
+ """
63
+
64
+ image1.load()
65
+ image2.load()
66
+ return image1._new(image1.im.chop_lighter(image2.im))
67
+
68
+
69
+ def darker(image1: Image.Image, image2: Image.Image) -> Image.Image:
70
+ """
71
+ Compares the two images, pixel by pixel, and returns a new image containing
72
+ the darker values. ::
73
+
74
+ out = min(image1, image2)
75
+
76
+ :rtype: :py:class:`~PIL.Image.Image`
77
+ """
78
+
79
+ image1.load()
80
+ image2.load()
81
+ return image1._new(image1.im.chop_darker(image2.im))
82
+
83
+
84
+ def difference(image1: Image.Image, image2: Image.Image) -> Image.Image:
85
+ """
86
+ Returns the absolute value of the pixel-by-pixel difference between the two
87
+ images. ::
88
+
89
+ out = abs(image1 - image2)
90
+
91
+ :rtype: :py:class:`~PIL.Image.Image`
92
+ """
93
+
94
+ image1.load()
95
+ image2.load()
96
+ return image1._new(image1.im.chop_difference(image2.im))
97
+
98
+
99
+ def multiply(image1: Image.Image, image2: Image.Image) -> Image.Image:
100
+ """
101
+ Superimposes two images on top of each other.
102
+
103
+ If you multiply an image with a solid black image, the result is black. If
104
+ you multiply with a solid white image, the image is unaffected. ::
105
+
106
+ out = image1 * image2 / MAX
107
+
108
+ :rtype: :py:class:`~PIL.Image.Image`
109
+ """
110
+
111
+ image1.load()
112
+ image2.load()
113
+ return image1._new(image1.im.chop_multiply(image2.im))
114
+
115
+
116
+ def screen(image1: Image.Image, image2: Image.Image) -> Image.Image:
117
+ """
118
+ Superimposes two inverted images on top of each other. ::
119
+
120
+ out = MAX - ((MAX - image1) * (MAX - image2) / MAX)
121
+
122
+ :rtype: :py:class:`~PIL.Image.Image`
123
+ """
124
+
125
+ image1.load()
126
+ image2.load()
127
+ return image1._new(image1.im.chop_screen(image2.im))
128
+
129
+
130
+ def soft_light(image1: Image.Image, image2: Image.Image) -> Image.Image:
131
+ """
132
+ Superimposes two images on top of each other using the Soft Light algorithm
133
+
134
+ :rtype: :py:class:`~PIL.Image.Image`
135
+ """
136
+
137
+ image1.load()
138
+ image2.load()
139
+ return image1._new(image1.im.chop_soft_light(image2.im))
140
+
141
+
142
+ def hard_light(image1: Image.Image, image2: Image.Image) -> Image.Image:
143
+ """
144
+ Superimposes two images on top of each other using the Hard Light algorithm
145
+
146
+ :rtype: :py:class:`~PIL.Image.Image`
147
+ """
148
+
149
+ image1.load()
150
+ image2.load()
151
+ return image1._new(image1.im.chop_hard_light(image2.im))
152
+
153
+
154
+ def overlay(image1: Image.Image, image2: Image.Image) -> Image.Image:
155
+ """
156
+ Superimposes two images on top of each other using the Overlay algorithm
157
+
158
+ :rtype: :py:class:`~PIL.Image.Image`
159
+ """
160
+
161
+ image1.load()
162
+ image2.load()
163
+ return image1._new(image1.im.chop_overlay(image2.im))
164
+
165
+
166
+ def add(
167
+ image1: Image.Image, image2: Image.Image, scale: float = 1.0, offset: float = 0
168
+ ) -> Image.Image:
169
+ """
170
+ Adds two images, dividing the result by scale and adding the
171
+ offset. If omitted, scale defaults to 1.0, and offset to 0.0. ::
172
+
173
+ out = ((image1 + image2) / scale + offset)
174
+
175
+ :rtype: :py:class:`~PIL.Image.Image`
176
+ """
177
+
178
+ image1.load()
179
+ image2.load()
180
+ return image1._new(image1.im.chop_add(image2.im, scale, offset))
181
+
182
+
183
+ def subtract(
184
+ image1: Image.Image, image2: Image.Image, scale: float = 1.0, offset: float = 0
185
+ ) -> Image.Image:
186
+ """
187
+ Subtracts two images, dividing the result by scale and adding the offset.
188
+ If omitted, scale defaults to 1.0, and offset to 0.0. ::
189
+
190
+ out = ((image1 - image2) / scale + offset)
191
+
192
+ :rtype: :py:class:`~PIL.Image.Image`
193
+ """
194
+
195
+ image1.load()
196
+ image2.load()
197
+ return image1._new(image1.im.chop_subtract(image2.im, scale, offset))
198
+
199
+
200
+ def add_modulo(image1: Image.Image, image2: Image.Image) -> Image.Image:
201
+ """Add two images, without clipping the result. ::
202
+
203
+ out = ((image1 + image2) % MAX)
204
+
205
+ :rtype: :py:class:`~PIL.Image.Image`
206
+ """
207
+
208
+ image1.load()
209
+ image2.load()
210
+ return image1._new(image1.im.chop_add_modulo(image2.im))
211
+
212
+
213
+ def subtract_modulo(image1: Image.Image, image2: Image.Image) -> Image.Image:
214
+ """Subtract two images, without clipping the result. ::
215
+
216
+ out = ((image1 - image2) % MAX)
217
+
218
+ :rtype: :py:class:`~PIL.Image.Image`
219
+ """
220
+
221
+ image1.load()
222
+ image2.load()
223
+ return image1._new(image1.im.chop_subtract_modulo(image2.im))
224
+
225
+
226
+ def logical_and(image1: Image.Image, image2: Image.Image) -> Image.Image:
227
+ """Logical AND between two images.
228
+
229
+ Both of the images must have mode "1". If you would like to perform a
230
+ logical AND on an image with a mode other than "1", try
231
+ :py:meth:`~PIL.ImageChops.multiply` instead, using a black-and-white mask
232
+ as the second image. ::
233
+
234
+ out = ((image1 and image2) % MAX)
235
+
236
+ :rtype: :py:class:`~PIL.Image.Image`
237
+ """
238
+
239
+ image1.load()
240
+ image2.load()
241
+ return image1._new(image1.im.chop_and(image2.im))
242
+
243
+
244
+ def logical_or(image1: Image.Image, image2: Image.Image) -> Image.Image:
245
+ """Logical OR between two images.
246
+
247
+ Both of the images must have mode "1". ::
248
+
249
+ out = ((image1 or image2) % MAX)
250
+
251
+ :rtype: :py:class:`~PIL.Image.Image`
252
+ """
253
+
254
+ image1.load()
255
+ image2.load()
256
+ return image1._new(image1.im.chop_or(image2.im))
257
+
258
+
259
+ def logical_xor(image1: Image.Image, image2: Image.Image) -> Image.Image:
260
+ """Logical XOR between two images.
261
+
262
+ Both of the images must have mode "1". ::
263
+
264
+ out = ((bool(image1) != bool(image2)) % MAX)
265
+
266
+ :rtype: :py:class:`~PIL.Image.Image`
267
+ """
268
+
269
+ image1.load()
270
+ image2.load()
271
+ return image1._new(image1.im.chop_xor(image2.im))
272
+
273
+
274
+ def blend(image1: Image.Image, image2: Image.Image, alpha: float) -> Image.Image:
275
+ """Blend images using constant transparency weight. Alias for
276
+ :py:func:`PIL.Image.blend`.
277
+
278
+ :rtype: :py:class:`~PIL.Image.Image`
279
+ """
280
+
281
+ return Image.blend(image1, image2, alpha)
282
+
283
+
284
+ def composite(
285
+ image1: Image.Image, image2: Image.Image, mask: Image.Image
286
+ ) -> Image.Image:
287
+ """Create composite using transparency mask. Alias for
288
+ :py:func:`PIL.Image.composite`.
289
+
290
+ :rtype: :py:class:`~PIL.Image.Image`
291
+ """
292
+
293
+ return Image.composite(image1, image2, mask)
294
+
295
+
296
+ def offset(image: Image.Image, xoffset: int, yoffset: int | None = None) -> Image.Image:
297
+ """Returns a copy of the image where data has been offset by the given
298
+ distances. Data wraps around the edges. If ``yoffset`` is omitted, it
299
+ is assumed to be equal to ``xoffset``.
300
+
301
+ :param image: Input image.
302
+ :param xoffset: The horizontal distance.
303
+ :param yoffset: The vertical distance. If omitted, both
304
+ distances are set to the same value.
305
+ :rtype: :py:class:`~PIL.Image.Image`
306
+ """
307
+
308
+ if yoffset is None:
309
+ yoffset = xoffset
310
+ image.load()
311
+ return image._new(image.im.offset(xoffset, yoffset))
.venv/lib/python3.12/site-packages/PIL/ImageColor.py ADDED
@@ -0,0 +1,320 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library
3
+ # $Id$
4
+ #
5
+ # map CSS3-style colour description strings to RGB
6
+ #
7
+ # History:
8
+ # 2002-10-24 fl Added support for CSS-style color strings
9
+ # 2002-12-15 fl Added RGBA support
10
+ # 2004-03-27 fl Fixed remaining int() problems for Python 1.5.2
11
+ # 2004-07-19 fl Fixed gray/grey spelling issues
12
+ # 2009-03-05 fl Fixed rounding error in grayscale calculation
13
+ #
14
+ # Copyright (c) 2002-2004 by Secret Labs AB
15
+ # Copyright (c) 2002-2004 by Fredrik Lundh
16
+ #
17
+ # See the README file for information on usage and redistribution.
18
+ #
19
+ from __future__ import annotations
20
+
21
+ import re
22
+ from functools import lru_cache
23
+
24
+ from . import Image
25
+
26
+
27
+ @lru_cache
28
+ def getrgb(color: str) -> tuple[int, int, int] | tuple[int, int, int, int]:
29
+ """
30
+ Convert a color string to an RGB or RGBA tuple. If the string cannot be
31
+ parsed, this function raises a :py:exc:`ValueError` exception.
32
+
33
+ .. versionadded:: 1.1.4
34
+
35
+ :param color: A color string
36
+ :return: ``(red, green, blue[, alpha])``
37
+ """
38
+ if len(color) > 100:
39
+ msg = "color specifier is too long"
40
+ raise ValueError(msg)
41
+ color = color.lower()
42
+
43
+ rgb = colormap.get(color, None)
44
+ if rgb:
45
+ if isinstance(rgb, tuple):
46
+ return rgb
47
+ rgb_tuple = getrgb(rgb)
48
+ assert len(rgb_tuple) == 3
49
+ colormap[color] = rgb_tuple
50
+ return rgb_tuple
51
+
52
+ # check for known string formats
53
+ if re.match("#[a-f0-9]{3}$", color):
54
+ return int(color[1] * 2, 16), int(color[2] * 2, 16), int(color[3] * 2, 16)
55
+
56
+ if re.match("#[a-f0-9]{4}$", color):
57
+ return (
58
+ int(color[1] * 2, 16),
59
+ int(color[2] * 2, 16),
60
+ int(color[3] * 2, 16),
61
+ int(color[4] * 2, 16),
62
+ )
63
+
64
+ if re.match("#[a-f0-9]{6}$", color):
65
+ return int(color[1:3], 16), int(color[3:5], 16), int(color[5:7], 16)
66
+
67
+ if re.match("#[a-f0-9]{8}$", color):
68
+ return (
69
+ int(color[1:3], 16),
70
+ int(color[3:5], 16),
71
+ int(color[5:7], 16),
72
+ int(color[7:9], 16),
73
+ )
74
+
75
+ m = re.match(r"rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$", color)
76
+ if m:
77
+ return int(m.group(1)), int(m.group(2)), int(m.group(3))
78
+
79
+ m = re.match(r"rgb\(\s*(\d+)%\s*,\s*(\d+)%\s*,\s*(\d+)%\s*\)$", color)
80
+ if m:
81
+ return (
82
+ int((int(m.group(1)) * 255) / 100.0 + 0.5),
83
+ int((int(m.group(2)) * 255) / 100.0 + 0.5),
84
+ int((int(m.group(3)) * 255) / 100.0 + 0.5),
85
+ )
86
+
87
+ m = re.match(
88
+ r"hsl\(\s*(\d+\.?\d*)\s*,\s*(\d+\.?\d*)%\s*,\s*(\d+\.?\d*)%\s*\)$", color
89
+ )
90
+ if m:
91
+ from colorsys import hls_to_rgb
92
+
93
+ rgb_floats = hls_to_rgb(
94
+ float(m.group(1)) / 360.0,
95
+ float(m.group(3)) / 100.0,
96
+ float(m.group(2)) / 100.0,
97
+ )
98
+ return (
99
+ int(rgb_floats[0] * 255 + 0.5),
100
+ int(rgb_floats[1] * 255 + 0.5),
101
+ int(rgb_floats[2] * 255 + 0.5),
102
+ )
103
+
104
+ m = re.match(
105
+ r"hs[bv]\(\s*(\d+\.?\d*)\s*,\s*(\d+\.?\d*)%\s*,\s*(\d+\.?\d*)%\s*\)$", color
106
+ )
107
+ if m:
108
+ from colorsys import hsv_to_rgb
109
+
110
+ rgb_floats = hsv_to_rgb(
111
+ float(m.group(1)) / 360.0,
112
+ float(m.group(2)) / 100.0,
113
+ float(m.group(3)) / 100.0,
114
+ )
115
+ return (
116
+ int(rgb_floats[0] * 255 + 0.5),
117
+ int(rgb_floats[1] * 255 + 0.5),
118
+ int(rgb_floats[2] * 255 + 0.5),
119
+ )
120
+
121
+ m = re.match(r"rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$", color)
122
+ if m:
123
+ return int(m.group(1)), int(m.group(2)), int(m.group(3)), int(m.group(4))
124
+ msg = f"unknown color specifier: {repr(color)}"
125
+ raise ValueError(msg)
126
+
127
+
128
+ @lru_cache
129
+ def getcolor(color: str, mode: str) -> int | tuple[int, ...]:
130
+ """
131
+ Same as :py:func:`~PIL.ImageColor.getrgb` for most modes. However, if
132
+ ``mode`` is HSV, converts the RGB value to a HSV value, or if ``mode`` is
133
+ not color or a palette image, converts the RGB value to a grayscale value.
134
+ If the string cannot be parsed, this function raises a :py:exc:`ValueError`
135
+ exception.
136
+
137
+ .. versionadded:: 1.1.4
138
+
139
+ :param color: A color string
140
+ :param mode: Convert result to this mode
141
+ :return: ``graylevel, (graylevel, alpha) or (red, green, blue[, alpha])``
142
+ """
143
+ # same as getrgb, but converts the result to the given mode
144
+ rgb, alpha = getrgb(color), 255
145
+ if len(rgb) == 4:
146
+ alpha = rgb[3]
147
+ rgb = rgb[:3]
148
+
149
+ if mode == "HSV":
150
+ from colorsys import rgb_to_hsv
151
+
152
+ r, g, b = rgb
153
+ h, s, v = rgb_to_hsv(r / 255, g / 255, b / 255)
154
+ return int(h * 255), int(s * 255), int(v * 255)
155
+ elif Image.getmodebase(mode) == "L":
156
+ r, g, b = rgb
157
+ # ITU-R Recommendation 601-2 for nonlinear RGB
158
+ # scaled to 24 bits to match the convert's implementation.
159
+ graylevel = (r * 19595 + g * 38470 + b * 7471 + 0x8000) >> 16
160
+ if mode[-1] == "A":
161
+ return graylevel, alpha
162
+ return graylevel
163
+ elif mode[-1] == "A":
164
+ return rgb + (alpha,)
165
+ return rgb
166
+
167
+
168
+ colormap: dict[str, str | tuple[int, int, int]] = {
169
+ # X11 colour table from https://drafts.csswg.org/css-color-4/, with
170
+ # gray/grey spelling issues fixed. This is a superset of HTML 4.0
171
+ # colour names used in CSS 1.
172
+ "aliceblue": "#f0f8ff",
173
+ "antiquewhite": "#faebd7",
174
+ "aqua": "#00ffff",
175
+ "aquamarine": "#7fffd4",
176
+ "azure": "#f0ffff",
177
+ "beige": "#f5f5dc",
178
+ "bisque": "#ffe4c4",
179
+ "black": "#000000",
180
+ "blanchedalmond": "#ffebcd",
181
+ "blue": "#0000ff",
182
+ "blueviolet": "#8a2be2",
183
+ "brown": "#a52a2a",
184
+ "burlywood": "#deb887",
185
+ "cadetblue": "#5f9ea0",
186
+ "chartreuse": "#7fff00",
187
+ "chocolate": "#d2691e",
188
+ "coral": "#ff7f50",
189
+ "cornflowerblue": "#6495ed",
190
+ "cornsilk": "#fff8dc",
191
+ "crimson": "#dc143c",
192
+ "cyan": "#00ffff",
193
+ "darkblue": "#00008b",
194
+ "darkcyan": "#008b8b",
195
+ "darkgoldenrod": "#b8860b",
196
+ "darkgray": "#a9a9a9",
197
+ "darkgrey": "#a9a9a9",
198
+ "darkgreen": "#006400",
199
+ "darkkhaki": "#bdb76b",
200
+ "darkmagenta": "#8b008b",
201
+ "darkolivegreen": "#556b2f",
202
+ "darkorange": "#ff8c00",
203
+ "darkorchid": "#9932cc",
204
+ "darkred": "#8b0000",
205
+ "darksalmon": "#e9967a",
206
+ "darkseagreen": "#8fbc8f",
207
+ "darkslateblue": "#483d8b",
208
+ "darkslategray": "#2f4f4f",
209
+ "darkslategrey": "#2f4f4f",
210
+ "darkturquoise": "#00ced1",
211
+ "darkviolet": "#9400d3",
212
+ "deeppink": "#ff1493",
213
+ "deepskyblue": "#00bfff",
214
+ "dimgray": "#696969",
215
+ "dimgrey": "#696969",
216
+ "dodgerblue": "#1e90ff",
217
+ "firebrick": "#b22222",
218
+ "floralwhite": "#fffaf0",
219
+ "forestgreen": "#228b22",
220
+ "fuchsia": "#ff00ff",
221
+ "gainsboro": "#dcdcdc",
222
+ "ghostwhite": "#f8f8ff",
223
+ "gold": "#ffd700",
224
+ "goldenrod": "#daa520",
225
+ "gray": "#808080",
226
+ "grey": "#808080",
227
+ "green": "#008000",
228
+ "greenyellow": "#adff2f",
229
+ "honeydew": "#f0fff0",
230
+ "hotpink": "#ff69b4",
231
+ "indianred": "#cd5c5c",
232
+ "indigo": "#4b0082",
233
+ "ivory": "#fffff0",
234
+ "khaki": "#f0e68c",
235
+ "lavender": "#e6e6fa",
236
+ "lavenderblush": "#fff0f5",
237
+ "lawngreen": "#7cfc00",
238
+ "lemonchiffon": "#fffacd",
239
+ "lightblue": "#add8e6",
240
+ "lightcoral": "#f08080",
241
+ "lightcyan": "#e0ffff",
242
+ "lightgoldenrodyellow": "#fafad2",
243
+ "lightgreen": "#90ee90",
244
+ "lightgray": "#d3d3d3",
245
+ "lightgrey": "#d3d3d3",
246
+ "lightpink": "#ffb6c1",
247
+ "lightsalmon": "#ffa07a",
248
+ "lightseagreen": "#20b2aa",
249
+ "lightskyblue": "#87cefa",
250
+ "lightslategray": "#778899",
251
+ "lightslategrey": "#778899",
252
+ "lightsteelblue": "#b0c4de",
253
+ "lightyellow": "#ffffe0",
254
+ "lime": "#00ff00",
255
+ "limegreen": "#32cd32",
256
+ "linen": "#faf0e6",
257
+ "magenta": "#ff00ff",
258
+ "maroon": "#800000",
259
+ "mediumaquamarine": "#66cdaa",
260
+ "mediumblue": "#0000cd",
261
+ "mediumorchid": "#ba55d3",
262
+ "mediumpurple": "#9370db",
263
+ "mediumseagreen": "#3cb371",
264
+ "mediumslateblue": "#7b68ee",
265
+ "mediumspringgreen": "#00fa9a",
266
+ "mediumturquoise": "#48d1cc",
267
+ "mediumvioletred": "#c71585",
268
+ "midnightblue": "#191970",
269
+ "mintcream": "#f5fffa",
270
+ "mistyrose": "#ffe4e1",
271
+ "moccasin": "#ffe4b5",
272
+ "navajowhite": "#ffdead",
273
+ "navy": "#000080",
274
+ "oldlace": "#fdf5e6",
275
+ "olive": "#808000",
276
+ "olivedrab": "#6b8e23",
277
+ "orange": "#ffa500",
278
+ "orangered": "#ff4500",
279
+ "orchid": "#da70d6",
280
+ "palegoldenrod": "#eee8aa",
281
+ "palegreen": "#98fb98",
282
+ "paleturquoise": "#afeeee",
283
+ "palevioletred": "#db7093",
284
+ "papayawhip": "#ffefd5",
285
+ "peachpuff": "#ffdab9",
286
+ "peru": "#cd853f",
287
+ "pink": "#ffc0cb",
288
+ "plum": "#dda0dd",
289
+ "powderblue": "#b0e0e6",
290
+ "purple": "#800080",
291
+ "rebeccapurple": "#663399",
292
+ "red": "#ff0000",
293
+ "rosybrown": "#bc8f8f",
294
+ "royalblue": "#4169e1",
295
+ "saddlebrown": "#8b4513",
296
+ "salmon": "#fa8072",
297
+ "sandybrown": "#f4a460",
298
+ "seagreen": "#2e8b57",
299
+ "seashell": "#fff5ee",
300
+ "sienna": "#a0522d",
301
+ "silver": "#c0c0c0",
302
+ "skyblue": "#87ceeb",
303
+ "slateblue": "#6a5acd",
304
+ "slategray": "#708090",
305
+ "slategrey": "#708090",
306
+ "snow": "#fffafa",
307
+ "springgreen": "#00ff7f",
308
+ "steelblue": "#4682b4",
309
+ "tan": "#d2b48c",
310
+ "teal": "#008080",
311
+ "thistle": "#d8bfd8",
312
+ "tomato": "#ff6347",
313
+ "turquoise": "#40e0d0",
314
+ "violet": "#ee82ee",
315
+ "wheat": "#f5deb3",
316
+ "white": "#ffffff",
317
+ "whitesmoke": "#f5f5f5",
318
+ "yellow": "#ffff00",
319
+ "yellowgreen": "#9acd32",
320
+ }
.venv/lib/python3.12/site-packages/PIL/ImageFile.py ADDED
@@ -0,0 +1,926 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # base class for image file handlers
6
+ #
7
+ # history:
8
+ # 1995-09-09 fl Created
9
+ # 1996-03-11 fl Fixed load mechanism.
10
+ # 1996-04-15 fl Added pcx/xbm decoders.
11
+ # 1996-04-30 fl Added encoders.
12
+ # 1996-12-14 fl Added load helpers
13
+ # 1997-01-11 fl Use encode_to_file where possible
14
+ # 1997-08-27 fl Flush output in _save
15
+ # 1998-03-05 fl Use memory mapping for some modes
16
+ # 1999-02-04 fl Use memory mapping also for "I;16" and "I;16B"
17
+ # 1999-05-31 fl Added image parser
18
+ # 2000-10-12 fl Set readonly flag on memory-mapped images
19
+ # 2002-03-20 fl Use better messages for common decoder errors
20
+ # 2003-04-21 fl Fall back on mmap/map_buffer if map is not available
21
+ # 2003-10-30 fl Added StubImageFile class
22
+ # 2004-02-25 fl Made incremental parser more robust
23
+ #
24
+ # Copyright (c) 1997-2004 by Secret Labs AB
25
+ # Copyright (c) 1995-2004 by Fredrik Lundh
26
+ #
27
+ # See the README file for information on usage and redistribution.
28
+ #
29
+ from __future__ import annotations
30
+
31
+ import abc
32
+ import io
33
+ import itertools
34
+ import logging
35
+ import os
36
+ import struct
37
+ from typing import IO, Any, NamedTuple, cast
38
+
39
+ from . import ExifTags, Image
40
+ from ._util import DeferredError, is_path
41
+
42
+ TYPE_CHECKING = False
43
+ if TYPE_CHECKING:
44
+ from ._typing import StrOrBytesPath
45
+
46
+ logger = logging.getLogger(__name__)
47
+
48
+ MAXBLOCK = 65536
49
+ """
50
+ By default, Pillow processes image data in blocks. This helps to prevent excessive use
51
+ of resources. Codecs may disable this behaviour with ``_pulls_fd`` or ``_pushes_fd``.
52
+
53
+ When reading an image, this is the number of bytes to read at once.
54
+
55
+ When writing an image, this is the number of bytes to write at once.
56
+ If the image width times 4 is greater, then that will be used instead.
57
+ Plugins may also set a greater number.
58
+
59
+ User code may set this to another number.
60
+ """
61
+
62
+ SAFEBLOCK = 1024 * 1024
63
+
64
+ LOAD_TRUNCATED_IMAGES = False
65
+ """Whether or not to load truncated image files. User code may change this."""
66
+
67
+ ERRORS = {
68
+ -1: "image buffer overrun error",
69
+ -2: "decoding error",
70
+ -3: "unknown error",
71
+ -8: "bad configuration",
72
+ -9: "out of memory error",
73
+ }
74
+ """
75
+ Dict of known error codes returned from :meth:`.PyDecoder.decode`,
76
+ :meth:`.PyEncoder.encode` :meth:`.PyEncoder.encode_to_pyfd` and
77
+ :meth:`.PyEncoder.encode_to_file`.
78
+ """
79
+
80
+
81
+ #
82
+ # --------------------------------------------------------------------
83
+ # Helpers
84
+
85
+
86
+ def _get_oserror(error: int, *, encoder: bool) -> OSError:
87
+ try:
88
+ msg = Image.core.getcodecstatus(error)
89
+ except AttributeError:
90
+ msg = ERRORS.get(error)
91
+ if not msg:
92
+ msg = f"{'encoder' if encoder else 'decoder'} error {error}"
93
+ msg += f" when {'writing' if encoder else 'reading'} image file"
94
+ return OSError(msg)
95
+
96
+
97
+ def _tilesort(t: _Tile) -> int:
98
+ # sort on offset
99
+ return t[2]
100
+
101
+
102
+ class _Tile(NamedTuple):
103
+ codec_name: str
104
+ extents: tuple[int, int, int, int] | None
105
+ offset: int = 0
106
+ args: tuple[Any, ...] | str | None = None
107
+
108
+
109
+ #
110
+ # --------------------------------------------------------------------
111
+ # ImageFile base class
112
+
113
+
114
+ class ImageFile(Image.Image):
115
+ """Base class for image file format handlers."""
116
+
117
+ def __init__(
118
+ self, fp: StrOrBytesPath | IO[bytes], filename: str | bytes | None = None
119
+ ) -> None:
120
+ super().__init__()
121
+
122
+ self._min_frame = 0
123
+
124
+ self.custom_mimetype: str | None = None
125
+
126
+ self.tile: list[_Tile] = []
127
+ """ A list of tile descriptors """
128
+
129
+ self.readonly = 1 # until we know better
130
+
131
+ self.decoderconfig: tuple[Any, ...] = ()
132
+ self.decodermaxblock = MAXBLOCK
133
+
134
+ if is_path(fp):
135
+ # filename
136
+ self.fp = open(fp, "rb")
137
+ self.filename = os.fspath(fp)
138
+ self._exclusive_fp = True
139
+ else:
140
+ # stream
141
+ self.fp = cast(IO[bytes], fp)
142
+ self.filename = filename if filename is not None else ""
143
+ # can be overridden
144
+ self._exclusive_fp = False
145
+
146
+ try:
147
+ try:
148
+ self._open()
149
+ except (
150
+ IndexError, # end of data
151
+ TypeError, # end of data (ord)
152
+ KeyError, # unsupported mode
153
+ EOFError, # got header but not the first frame
154
+ struct.error,
155
+ ) as v:
156
+ raise SyntaxError(v) from v
157
+
158
+ if not self.mode or self.size[0] <= 0 or self.size[1] <= 0:
159
+ msg = "not identified by this driver"
160
+ raise SyntaxError(msg)
161
+ except BaseException:
162
+ # close the file only if we have opened it this constructor
163
+ if self._exclusive_fp:
164
+ self.fp.close()
165
+ raise
166
+
167
+ def _open(self) -> None:
168
+ pass
169
+
170
+ def _close_fp(self):
171
+ if getattr(self, "_fp", False) and not isinstance(self._fp, DeferredError):
172
+ if self._fp != self.fp:
173
+ self._fp.close()
174
+ self._fp = DeferredError(ValueError("Operation on closed image"))
175
+ if self.fp:
176
+ self.fp.close()
177
+
178
+ def close(self) -> None:
179
+ """
180
+ Closes the file pointer, if possible.
181
+
182
+ This operation will destroy the image core and release its memory.
183
+ The image data will be unusable afterward.
184
+
185
+ This function is required to close images that have multiple frames or
186
+ have not had their file read and closed by the
187
+ :py:meth:`~PIL.Image.Image.load` method. See :ref:`file-handling` for
188
+ more information.
189
+ """
190
+ try:
191
+ self._close_fp()
192
+ self.fp = None
193
+ except Exception as msg:
194
+ logger.debug("Error closing: %s", msg)
195
+
196
+ super().close()
197
+
198
+ def get_child_images(self) -> list[ImageFile]:
199
+ child_images = []
200
+ exif = self.getexif()
201
+ ifds = []
202
+ if ExifTags.Base.SubIFDs in exif:
203
+ subifd_offsets = exif[ExifTags.Base.SubIFDs]
204
+ if subifd_offsets:
205
+ if not isinstance(subifd_offsets, tuple):
206
+ subifd_offsets = (subifd_offsets,)
207
+ for subifd_offset in subifd_offsets:
208
+ ifds.append((exif._get_ifd_dict(subifd_offset), subifd_offset))
209
+ ifd1 = exif.get_ifd(ExifTags.IFD.IFD1)
210
+ if ifd1 and ifd1.get(ExifTags.Base.JpegIFOffset):
211
+ assert exif._info is not None
212
+ ifds.append((ifd1, exif._info.next))
213
+
214
+ offset = None
215
+ for ifd, ifd_offset in ifds:
216
+ assert self.fp is not None
217
+ current_offset = self.fp.tell()
218
+ if offset is None:
219
+ offset = current_offset
220
+
221
+ fp = self.fp
222
+ if ifd is not None:
223
+ thumbnail_offset = ifd.get(ExifTags.Base.JpegIFOffset)
224
+ if thumbnail_offset is not None:
225
+ thumbnail_offset += getattr(self, "_exif_offset", 0)
226
+ self.fp.seek(thumbnail_offset)
227
+
228
+ length = ifd.get(ExifTags.Base.JpegIFByteCount)
229
+ assert isinstance(length, int)
230
+ data = self.fp.read(length)
231
+ fp = io.BytesIO(data)
232
+
233
+ with Image.open(fp) as im:
234
+ from . import TiffImagePlugin
235
+
236
+ if thumbnail_offset is None and isinstance(
237
+ im, TiffImagePlugin.TiffImageFile
238
+ ):
239
+ im._frame_pos = [ifd_offset]
240
+ im._seek(0)
241
+ im.load()
242
+ child_images.append(im)
243
+
244
+ if offset is not None:
245
+ assert self.fp is not None
246
+ self.fp.seek(offset)
247
+ return child_images
248
+
249
+ def get_format_mimetype(self) -> str | None:
250
+ if self.custom_mimetype:
251
+ return self.custom_mimetype
252
+ if self.format is not None:
253
+ return Image.MIME.get(self.format.upper())
254
+ return None
255
+
256
+ def __getstate__(self) -> list[Any]:
257
+ return super().__getstate__() + [self.filename]
258
+
259
+ def __setstate__(self, state: list[Any]) -> None:
260
+ self.tile = []
261
+ if len(state) > 5:
262
+ self.filename = state[5]
263
+ super().__setstate__(state)
264
+
265
+ def verify(self) -> None:
266
+ """Check file integrity"""
267
+
268
+ # raise exception if something's wrong. must be called
269
+ # directly after open, and closes file when finished.
270
+ if self._exclusive_fp:
271
+ self.fp.close()
272
+ self.fp = None
273
+
274
+ def load(self) -> Image.core.PixelAccess | None:
275
+ """Load image data based on tile list"""
276
+
277
+ if not self.tile and self._im is None:
278
+ msg = "cannot load this image"
279
+ raise OSError(msg)
280
+
281
+ pixel = Image.Image.load(self)
282
+ if not self.tile:
283
+ return pixel
284
+
285
+ self.map: mmap.mmap | None = None
286
+ use_mmap = self.filename and len(self.tile) == 1
287
+
288
+ readonly = 0
289
+
290
+ # look for read/seek overrides
291
+ if hasattr(self, "load_read"):
292
+ read = self.load_read
293
+ # don't use mmap if there are custom read/seek functions
294
+ use_mmap = False
295
+ else:
296
+ read = self.fp.read
297
+
298
+ if hasattr(self, "load_seek"):
299
+ seek = self.load_seek
300
+ use_mmap = False
301
+ else:
302
+ seek = self.fp.seek
303
+
304
+ if use_mmap:
305
+ # try memory mapping
306
+ decoder_name, extents, offset, args = self.tile[0]
307
+ if isinstance(args, str):
308
+ args = (args, 0, 1)
309
+ if (
310
+ decoder_name == "raw"
311
+ and isinstance(args, tuple)
312
+ and len(args) >= 3
313
+ and args[0] == self.mode
314
+ and args[0] in Image._MAPMODES
315
+ ):
316
+ if offset < 0:
317
+ msg = "Tile offset cannot be negative"
318
+ raise ValueError(msg)
319
+ try:
320
+ # use mmap, if possible
321
+ import mmap
322
+
323
+ with open(self.filename) as fp:
324
+ self.map = mmap.mmap(fp.fileno(), 0, access=mmap.ACCESS_READ)
325
+ if offset + self.size[1] * args[1] > self.map.size():
326
+ msg = "buffer is not large enough"
327
+ raise OSError(msg)
328
+ self.im = Image.core.map_buffer(
329
+ self.map, self.size, decoder_name, offset, args
330
+ )
331
+ readonly = 1
332
+ # After trashing self.im,
333
+ # we might need to reload the palette data.
334
+ if self.palette:
335
+ self.palette.dirty = 1
336
+ except (AttributeError, OSError, ImportError):
337
+ self.map = None
338
+
339
+ self.load_prepare()
340
+ err_code = -3 # initialize to unknown error
341
+ if not self.map:
342
+ # sort tiles in file order
343
+ self.tile.sort(key=_tilesort)
344
+
345
+ # FIXME: This is a hack to handle TIFF's JpegTables tag.
346
+ prefix = getattr(self, "tile_prefix", b"")
347
+
348
+ # Remove consecutive duplicates that only differ by their offset
349
+ self.tile = [
350
+ list(tiles)[-1]
351
+ for _, tiles in itertools.groupby(
352
+ self.tile, lambda tile: (tile[0], tile[1], tile[3])
353
+ )
354
+ ]
355
+ for i, (decoder_name, extents, offset, args) in enumerate(self.tile):
356
+ seek(offset)
357
+ decoder = Image._getdecoder(
358
+ self.mode, decoder_name, args, self.decoderconfig
359
+ )
360
+ try:
361
+ decoder.setimage(self.im, extents)
362
+ if decoder.pulls_fd:
363
+ decoder.setfd(self.fp)
364
+ err_code = decoder.decode(b"")[1]
365
+ else:
366
+ b = prefix
367
+ while True:
368
+ read_bytes = self.decodermaxblock
369
+ if i + 1 < len(self.tile):
370
+ next_offset = self.tile[i + 1].offset
371
+ if next_offset > offset:
372
+ read_bytes = next_offset - offset
373
+ try:
374
+ s = read(read_bytes)
375
+ except (IndexError, struct.error) as e:
376
+ # truncated png/gif
377
+ if LOAD_TRUNCATED_IMAGES:
378
+ break
379
+ else:
380
+ msg = "image file is truncated"
381
+ raise OSError(msg) from e
382
+
383
+ if not s: # truncated jpeg
384
+ if LOAD_TRUNCATED_IMAGES:
385
+ break
386
+ else:
387
+ msg = (
388
+ "image file is truncated "
389
+ f"({len(b)} bytes not processed)"
390
+ )
391
+ raise OSError(msg)
392
+
393
+ b = b + s
394
+ n, err_code = decoder.decode(b)
395
+ if n < 0:
396
+ break
397
+ b = b[n:]
398
+ finally:
399
+ # Need to cleanup here to prevent leaks
400
+ decoder.cleanup()
401
+
402
+ self.tile = []
403
+ self.readonly = readonly
404
+
405
+ self.load_end()
406
+
407
+ if self._exclusive_fp and self._close_exclusive_fp_after_loading:
408
+ self.fp.close()
409
+ self.fp = None
410
+
411
+ if not self.map and not LOAD_TRUNCATED_IMAGES and err_code < 0:
412
+ # still raised if decoder fails to return anything
413
+ raise _get_oserror(err_code, encoder=False)
414
+
415
+ return Image.Image.load(self)
416
+
417
+ def load_prepare(self) -> None:
418
+ # create image memory if necessary
419
+ if self._im is None:
420
+ self.im = Image.core.new(self.mode, self.size)
421
+ # create palette (optional)
422
+ if self.mode == "P":
423
+ Image.Image.load(self)
424
+
425
+ def load_end(self) -> None:
426
+ # may be overridden
427
+ pass
428
+
429
+ # may be defined for contained formats
430
+ # def load_seek(self, pos: int) -> None:
431
+ # pass
432
+
433
+ # may be defined for blocked formats (e.g. PNG)
434
+ # def load_read(self, read_bytes: int) -> bytes:
435
+ # pass
436
+
437
+ def _seek_check(self, frame: int) -> bool:
438
+ if (
439
+ frame < self._min_frame
440
+ # Only check upper limit on frames if additional seek operations
441
+ # are not required to do so
442
+ or (
443
+ not (hasattr(self, "_n_frames") and self._n_frames is None)
444
+ and frame >= getattr(self, "n_frames") + self._min_frame
445
+ )
446
+ ):
447
+ msg = "attempt to seek outside sequence"
448
+ raise EOFError(msg)
449
+
450
+ return self.tell() != frame
451
+
452
+
453
+ class StubHandler(abc.ABC):
454
+ def open(self, im: StubImageFile) -> None:
455
+ pass
456
+
457
+ @abc.abstractmethod
458
+ def load(self, im: StubImageFile) -> Image.Image:
459
+ pass
460
+
461
+
462
+ class StubImageFile(ImageFile, metaclass=abc.ABCMeta):
463
+ """
464
+ Base class for stub image loaders.
465
+
466
+ A stub loader is an image loader that can identify files of a
467
+ certain format, but relies on external code to load the file.
468
+ """
469
+
470
+ @abc.abstractmethod
471
+ def _open(self) -> None:
472
+ pass
473
+
474
+ def load(self) -> Image.core.PixelAccess | None:
475
+ loader = self._load()
476
+ if loader is None:
477
+ msg = f"cannot find loader for this {self.format} file"
478
+ raise OSError(msg)
479
+ image = loader.load(self)
480
+ assert image is not None
481
+ # become the other object (!)
482
+ self.__class__ = image.__class__ # type: ignore[assignment]
483
+ self.__dict__ = image.__dict__
484
+ return image.load()
485
+
486
+ @abc.abstractmethod
487
+ def _load(self) -> StubHandler | None:
488
+ """(Hook) Find actual image loader."""
489
+ pass
490
+
491
+
492
+ class Parser:
493
+ """
494
+ Incremental image parser. This class implements the standard
495
+ feed/close consumer interface.
496
+ """
497
+
498
+ incremental = None
499
+ image: Image.Image | None = None
500
+ data: bytes | None = None
501
+ decoder: Image.core.ImagingDecoder | PyDecoder | None = None
502
+ offset = 0
503
+ finished = 0
504
+
505
+ def reset(self) -> None:
506
+ """
507
+ (Consumer) Reset the parser. Note that you can only call this
508
+ method immediately after you've created a parser; parser
509
+ instances cannot be reused.
510
+ """
511
+ assert self.data is None, "cannot reuse parsers"
512
+
513
+ def feed(self, data: bytes) -> None:
514
+ """
515
+ (Consumer) Feed data to the parser.
516
+
517
+ :param data: A string buffer.
518
+ :exception OSError: If the parser failed to parse the image file.
519
+ """
520
+ # collect data
521
+
522
+ if self.finished:
523
+ return
524
+
525
+ if self.data is None:
526
+ self.data = data
527
+ else:
528
+ self.data = self.data + data
529
+
530
+ # parse what we have
531
+ if self.decoder:
532
+ if self.offset > 0:
533
+ # skip header
534
+ skip = min(len(self.data), self.offset)
535
+ self.data = self.data[skip:]
536
+ self.offset = self.offset - skip
537
+ if self.offset > 0 or not self.data:
538
+ return
539
+
540
+ n, e = self.decoder.decode(self.data)
541
+
542
+ if n < 0:
543
+ # end of stream
544
+ self.data = None
545
+ self.finished = 1
546
+ if e < 0:
547
+ # decoding error
548
+ self.image = None
549
+ raise _get_oserror(e, encoder=False)
550
+ else:
551
+ # end of image
552
+ return
553
+ self.data = self.data[n:]
554
+
555
+ elif self.image:
556
+ # if we end up here with no decoder, this file cannot
557
+ # be incrementally parsed. wait until we've gotten all
558
+ # available data
559
+ pass
560
+
561
+ else:
562
+ # attempt to open this file
563
+ try:
564
+ with io.BytesIO(self.data) as fp:
565
+ im = Image.open(fp)
566
+ except OSError:
567
+ pass # not enough data
568
+ else:
569
+ flag = hasattr(im, "load_seek") or hasattr(im, "load_read")
570
+ if flag or len(im.tile) != 1:
571
+ # custom load code, or multiple tiles
572
+ self.decode = None
573
+ else:
574
+ # initialize decoder
575
+ im.load_prepare()
576
+ d, e, o, a = im.tile[0]
577
+ im.tile = []
578
+ self.decoder = Image._getdecoder(im.mode, d, a, im.decoderconfig)
579
+ self.decoder.setimage(im.im, e)
580
+
581
+ # calculate decoder offset
582
+ self.offset = o
583
+ if self.offset <= len(self.data):
584
+ self.data = self.data[self.offset :]
585
+ self.offset = 0
586
+
587
+ self.image = im
588
+
589
+ def __enter__(self) -> Parser:
590
+ return self
591
+
592
+ def __exit__(self, *args: object) -> None:
593
+ self.close()
594
+
595
+ def close(self) -> Image.Image:
596
+ """
597
+ (Consumer) Close the stream.
598
+
599
+ :returns: An image object.
600
+ :exception OSError: If the parser failed to parse the image file either
601
+ because it cannot be identified or cannot be
602
+ decoded.
603
+ """
604
+ # finish decoding
605
+ if self.decoder:
606
+ # get rid of what's left in the buffers
607
+ self.feed(b"")
608
+ self.data = self.decoder = None
609
+ if not self.finished:
610
+ msg = "image was incomplete"
611
+ raise OSError(msg)
612
+ if not self.image:
613
+ msg = "cannot parse this image"
614
+ raise OSError(msg)
615
+ if self.data:
616
+ # incremental parsing not possible; reopen the file
617
+ # not that we have all data
618
+ with io.BytesIO(self.data) as fp:
619
+ try:
620
+ self.image = Image.open(fp)
621
+ finally:
622
+ self.image.load()
623
+ return self.image
624
+
625
+
626
+ # --------------------------------------------------------------------
627
+
628
+
629
+ def _save(im: Image.Image, fp: IO[bytes], tile: list[_Tile], bufsize: int = 0) -> None:
630
+ """Helper to save image based on tile list
631
+
632
+ :param im: Image object.
633
+ :param fp: File object.
634
+ :param tile: Tile list.
635
+ :param bufsize: Optional buffer size
636
+ """
637
+
638
+ im.load()
639
+ if not hasattr(im, "encoderconfig"):
640
+ im.encoderconfig = ()
641
+ tile.sort(key=_tilesort)
642
+ # FIXME: make MAXBLOCK a configuration parameter
643
+ # It would be great if we could have the encoder specify what it needs
644
+ # But, it would need at least the image size in most cases. RawEncode is
645
+ # a tricky case.
646
+ bufsize = max(MAXBLOCK, bufsize, im.size[0] * 4) # see RawEncode.c
647
+ try:
648
+ fh = fp.fileno()
649
+ fp.flush()
650
+ _encode_tile(im, fp, tile, bufsize, fh)
651
+ except (AttributeError, io.UnsupportedOperation) as exc:
652
+ _encode_tile(im, fp, tile, bufsize, None, exc)
653
+ if hasattr(fp, "flush"):
654
+ fp.flush()
655
+
656
+
657
+ def _encode_tile(
658
+ im: Image.Image,
659
+ fp: IO[bytes],
660
+ tile: list[_Tile],
661
+ bufsize: int,
662
+ fh: int | None,
663
+ exc: BaseException | None = None,
664
+ ) -> None:
665
+ for encoder_name, extents, offset, args in tile:
666
+ if offset > 0:
667
+ fp.seek(offset)
668
+ encoder = Image._getencoder(im.mode, encoder_name, args, im.encoderconfig)
669
+ try:
670
+ encoder.setimage(im.im, extents)
671
+ if encoder.pushes_fd:
672
+ encoder.setfd(fp)
673
+ errcode = encoder.encode_to_pyfd()[1]
674
+ else:
675
+ if exc:
676
+ # compress to Python file-compatible object
677
+ while True:
678
+ errcode, data = encoder.encode(bufsize)[1:]
679
+ fp.write(data)
680
+ if errcode:
681
+ break
682
+ else:
683
+ # slight speedup: compress to real file object
684
+ assert fh is not None
685
+ errcode = encoder.encode_to_file(fh, bufsize)
686
+ if errcode < 0:
687
+ raise _get_oserror(errcode, encoder=True) from exc
688
+ finally:
689
+ encoder.cleanup()
690
+
691
+
692
+ def _safe_read(fp: IO[bytes], size: int) -> bytes:
693
+ """
694
+ Reads large blocks in a safe way. Unlike fp.read(n), this function
695
+ doesn't trust the user. If the requested size is larger than
696
+ SAFEBLOCK, the file is read block by block.
697
+
698
+ :param fp: File handle. Must implement a <b>read</b> method.
699
+ :param size: Number of bytes to read.
700
+ :returns: A string containing <i>size</i> bytes of data.
701
+
702
+ Raises an OSError if the file is truncated and the read cannot be completed
703
+
704
+ """
705
+ if size <= 0:
706
+ return b""
707
+ if size <= SAFEBLOCK:
708
+ data = fp.read(size)
709
+ if len(data) < size:
710
+ msg = "Truncated File Read"
711
+ raise OSError(msg)
712
+ return data
713
+ blocks: list[bytes] = []
714
+ remaining_size = size
715
+ while remaining_size > 0:
716
+ block = fp.read(min(remaining_size, SAFEBLOCK))
717
+ if not block:
718
+ break
719
+ blocks.append(block)
720
+ remaining_size -= len(block)
721
+ if sum(len(block) for block in blocks) < size:
722
+ msg = "Truncated File Read"
723
+ raise OSError(msg)
724
+ return b"".join(blocks)
725
+
726
+
727
+ class PyCodecState:
728
+ def __init__(self) -> None:
729
+ self.xsize = 0
730
+ self.ysize = 0
731
+ self.xoff = 0
732
+ self.yoff = 0
733
+
734
+ def extents(self) -> tuple[int, int, int, int]:
735
+ return self.xoff, self.yoff, self.xoff + self.xsize, self.yoff + self.ysize
736
+
737
+
738
+ class PyCodec:
739
+ fd: IO[bytes] | None
740
+
741
+ def __init__(self, mode: str, *args: Any) -> None:
742
+ self.im: Image.core.ImagingCore | None = None
743
+ self.state = PyCodecState()
744
+ self.fd = None
745
+ self.mode = mode
746
+ self.init(args)
747
+
748
+ def init(self, args: tuple[Any, ...]) -> None:
749
+ """
750
+ Override to perform codec specific initialization
751
+
752
+ :param args: Tuple of arg items from the tile entry
753
+ :returns: None
754
+ """
755
+ self.args = args
756
+
757
+ def cleanup(self) -> None:
758
+ """
759
+ Override to perform codec specific cleanup
760
+
761
+ :returns: None
762
+ """
763
+ pass
764
+
765
+ def setfd(self, fd: IO[bytes]) -> None:
766
+ """
767
+ Called from ImageFile to set the Python file-like object
768
+
769
+ :param fd: A Python file-like object
770
+ :returns: None
771
+ """
772
+ self.fd = fd
773
+
774
+ def setimage(
775
+ self,
776
+ im: Image.core.ImagingCore,
777
+ extents: tuple[int, int, int, int] | None = None,
778
+ ) -> None:
779
+ """
780
+ Called from ImageFile to set the core output image for the codec
781
+
782
+ :param im: A core image object
783
+ :param extents: a 4 tuple of (x0, y0, x1, y1) defining the rectangle
784
+ for this tile
785
+ :returns: None
786
+ """
787
+
788
+ # following c code
789
+ self.im = im
790
+
791
+ if extents:
792
+ (x0, y0, x1, y1) = extents
793
+ else:
794
+ (x0, y0, x1, y1) = (0, 0, 0, 0)
795
+
796
+ if x0 == 0 and x1 == 0:
797
+ self.state.xsize, self.state.ysize = self.im.size
798
+ else:
799
+ self.state.xoff = x0
800
+ self.state.yoff = y0
801
+ self.state.xsize = x1 - x0
802
+ self.state.ysize = y1 - y0
803
+
804
+ if self.state.xsize <= 0 or self.state.ysize <= 0:
805
+ msg = "Size cannot be negative"
806
+ raise ValueError(msg)
807
+
808
+ if (
809
+ self.state.xsize + self.state.xoff > self.im.size[0]
810
+ or self.state.ysize + self.state.yoff > self.im.size[1]
811
+ ):
812
+ msg = "Tile cannot extend outside image"
813
+ raise ValueError(msg)
814
+
815
+
816
+ class PyDecoder(PyCodec):
817
+ """
818
+ Python implementation of a format decoder. Override this class and
819
+ add the decoding logic in the :meth:`decode` method.
820
+
821
+ See :ref:`Writing Your Own File Codec in Python<file-codecs-py>`
822
+ """
823
+
824
+ _pulls_fd = False
825
+
826
+ @property
827
+ def pulls_fd(self) -> bool:
828
+ return self._pulls_fd
829
+
830
+ def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:
831
+ """
832
+ Override to perform the decoding process.
833
+
834
+ :param buffer: A bytes object with the data to be decoded.
835
+ :returns: A tuple of ``(bytes consumed, errcode)``.
836
+ If finished with decoding return -1 for the bytes consumed.
837
+ Err codes are from :data:`.ImageFile.ERRORS`.
838
+ """
839
+ msg = "unavailable in base decoder"
840
+ raise NotImplementedError(msg)
841
+
842
+ def set_as_raw(
843
+ self, data: bytes, rawmode: str | None = None, extra: tuple[Any, ...] = ()
844
+ ) -> None:
845
+ """
846
+ Convenience method to set the internal image from a stream of raw data
847
+
848
+ :param data: Bytes to be set
849
+ :param rawmode: The rawmode to be used for the decoder.
850
+ If not specified, it will default to the mode of the image
851
+ :param extra: Extra arguments for the decoder.
852
+ :returns: None
853
+ """
854
+
855
+ if not rawmode:
856
+ rawmode = self.mode
857
+ d = Image._getdecoder(self.mode, "raw", rawmode, extra)
858
+ assert self.im is not None
859
+ d.setimage(self.im, self.state.extents())
860
+ s = d.decode(data)
861
+
862
+ if s[0] >= 0:
863
+ msg = "not enough image data"
864
+ raise ValueError(msg)
865
+ if s[1] != 0:
866
+ msg = "cannot decode image data"
867
+ raise ValueError(msg)
868
+
869
+
870
+ class PyEncoder(PyCodec):
871
+ """
872
+ Python implementation of a format encoder. Override this class and
873
+ add the decoding logic in the :meth:`encode` method.
874
+
875
+ See :ref:`Writing Your Own File Codec in Python<file-codecs-py>`
876
+ """
877
+
878
+ _pushes_fd = False
879
+
880
+ @property
881
+ def pushes_fd(self) -> bool:
882
+ return self._pushes_fd
883
+
884
+ def encode(self, bufsize: int) -> tuple[int, int, bytes]:
885
+ """
886
+ Override to perform the encoding process.
887
+
888
+ :param bufsize: Buffer size.
889
+ :returns: A tuple of ``(bytes encoded, errcode, bytes)``.
890
+ If finished with encoding return 1 for the error code.
891
+ Err codes are from :data:`.ImageFile.ERRORS`.
892
+ """
893
+ msg = "unavailable in base encoder"
894
+ raise NotImplementedError(msg)
895
+
896
+ def encode_to_pyfd(self) -> tuple[int, int]:
897
+ """
898
+ If ``pushes_fd`` is ``True``, then this method will be used,
899
+ and ``encode()`` will only be called once.
900
+
901
+ :returns: A tuple of ``(bytes consumed, errcode)``.
902
+ Err codes are from :data:`.ImageFile.ERRORS`.
903
+ """
904
+ if not self.pushes_fd:
905
+ return 0, -8 # bad configuration
906
+ bytes_consumed, errcode, data = self.encode(0)
907
+ if data:
908
+ assert self.fd is not None
909
+ self.fd.write(data)
910
+ return bytes_consumed, errcode
911
+
912
+ def encode_to_file(self, fh: int, bufsize: int) -> int:
913
+ """
914
+ :param fh: File handle.
915
+ :param bufsize: Buffer size.
916
+
917
+ :returns: If finished successfully, return 0.
918
+ Otherwise, return an error code. Err codes are from
919
+ :data:`.ImageFile.ERRORS`.
920
+ """
921
+ errcode = 0
922
+ while errcode == 0:
923
+ status, errcode, buf = self.encode(bufsize)
924
+ if status > 0:
925
+ os.write(fh, buf[status:])
926
+ return errcode
.venv/lib/python3.12/site-packages/PIL/ImageFont.py ADDED
@@ -0,0 +1,1312 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 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+ # History:
8
+ # 1996-08-07 fl created (experimental)
9
+ # 1997-08-25 fl minor adjustments to handle fonts from pilfont 0.3
10
+ # 1999-02-06 fl rewrote most font management stuff in C
11
+ # 1999-03-17 fl take pth files into account in load_path (from Richard Jones)
12
+ # 2001-02-17 fl added freetype support
13
+ # 2001-05-09 fl added TransposedFont wrapper class
14
+ # 2002-03-04 fl make sure we have a "L" or "1" font
15
+ # 2002-12-04 fl skip non-directory entries in the system path
16
+ # 2003-04-29 fl add embedded default font
17
+ # 2003-09-27 fl added support for truetype charmap encodings
18
+ #
19
+ # Todo:
20
+ # Adapt to PILFONT2 format (16-bit fonts, compressed, single file)
21
+ #
22
+ # Copyright (c) 1997-2003 by Secret Labs AB
23
+ # Copyright (c) 1996-2003 by Fredrik Lundh
24
+ #
25
+ # See the README file for information on usage and redistribution.
26
+ #
27
+
28
+ from __future__ import annotations
29
+
30
+ import base64
31
+ import os
32
+ import sys
33
+ import warnings
34
+ from enum import IntEnum
35
+ from io import BytesIO
36
+ from types import ModuleType
37
+ from typing import IO, Any, BinaryIO, TypedDict, cast
38
+
39
+ from . import Image
40
+ from ._typing import StrOrBytesPath
41
+ from ._util import DeferredError, is_path
42
+
43
+ TYPE_CHECKING = False
44
+ if TYPE_CHECKING:
45
+ from . import ImageFile
46
+ from ._imaging import ImagingFont
47
+ from ._imagingft import Font
48
+
49
+
50
+ class Axis(TypedDict):
51
+ minimum: int | None
52
+ default: int | None
53
+ maximum: int | None
54
+ name: bytes | None
55
+
56
+
57
+ class Layout(IntEnum):
58
+ BASIC = 0
59
+ RAQM = 1
60
+
61
+
62
+ MAX_STRING_LENGTH = 1_000_000
63
+
64
+
65
+ core: ModuleType | DeferredError
66
+ try:
67
+ from . import _imagingft as core
68
+ except ImportError as ex:
69
+ core = DeferredError.new(ex)
70
+
71
+
72
+ def _string_length_check(text: str | bytes | bytearray) -> None:
73
+ if MAX_STRING_LENGTH is not None and len(text) > MAX_STRING_LENGTH:
74
+ msg = "too many characters in string"
75
+ raise ValueError(msg)
76
+
77
+
78
+ # FIXME: add support for pilfont2 format (see FontFile.py)
79
+
80
+ # --------------------------------------------------------------------
81
+ # Font metrics format:
82
+ # "PILfont" LF
83
+ # fontdescriptor LF
84
+ # (optional) key=value... LF
85
+ # "DATA" LF
86
+ # binary data: 256*10*2 bytes (dx, dy, dstbox, srcbox)
87
+ #
88
+ # To place a character, cut out srcbox and paste at dstbox,
89
+ # relative to the character position. Then move the character
90
+ # position according to dx, dy.
91
+ # --------------------------------------------------------------------
92
+
93
+
94
+ class ImageFont:
95
+ """PIL font wrapper"""
96
+
97
+ font: ImagingFont
98
+
99
+ def _load_pilfont(self, filename: str) -> None:
100
+ with open(filename, "rb") as fp:
101
+ image: ImageFile.ImageFile | None = None
102
+ root = os.path.splitext(filename)[0]
103
+
104
+ for ext in (".png", ".gif", ".pbm"):
105
+ if image:
106
+ image.close()
107
+ try:
108
+ fullname = root + ext
109
+ image = Image.open(fullname)
110
+ except Exception:
111
+ pass
112
+ else:
113
+ if image 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
+ # check image
129
+ if image.mode not in ("1", "L"):
130
+ msg = "invalid font image mode"
131
+ raise TypeError(msg)
132
+
133
+ # read PILfont header
134
+ if file.read(8) != b"PILfont\n":
135
+ msg = "Not a PILfont file"
136
+ raise SyntaxError(msg)
137
+ file.readline()
138
+ self.info = [] # FIXME: should be a dictionary
139
+ while True:
140
+ s = file.readline()
141
+ if not s or s == b"DATA\n":
142
+ break
143
+ self.info.append(s)
144
+
145
+ # read PILfont metrics
146
+ data = file.read(256 * 20)
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
+ if layout_engine not in (Layout.BASIC, Layout.RAQM):
240
+ layout_engine = Layout.BASIC
241
+ if core.HAVE_RAQM:
242
+ layout_engine = Layout.RAQM
243
+ elif layout_engine == Layout.RAQM and not core.HAVE_RAQM:
244
+ warnings.warn(
245
+ "Raqm layout was requested, but Raqm is not available. "
246
+ "Falling back to basic layout."
247
+ )
248
+ layout_engine = Layout.BASIC
249
+
250
+ self.layout_engine = layout_engine
251
+
252
+ def load_from_bytes(f: IO[bytes]) -> None:
253
+ self.font_bytes = f.read()
254
+ self.font = core.getfont(
255
+ "", size, index, encoding, self.font_bytes, layout_engine
256
+ )
257
+
258
+ if is_path(font):
259
+ font = os.fspath(font)
260
+ if sys.platform == "win32":
261
+ font_bytes_path = font if isinstance(font, bytes) else font.encode()
262
+ try:
263
+ font_bytes_path.decode("ascii")
264
+ except UnicodeDecodeError:
265
+ # FreeType cannot load fonts with non-ASCII characters on Windows
266
+ # So load it into memory first
267
+ with open(font, "rb") as f:
268
+ load_from_bytes(f)
269
+ return
270
+ self.font = core.getfont(
271
+ font, size, index, encoding, layout_engine=layout_engine
272
+ )
273
+ else:
274
+ load_from_bytes(cast(IO[bytes], font))
275
+
276
+ def __getstate__(self) -> list[Any]:
277
+ return [self.path, self.size, self.index, self.encoding, self.layout_engine]
278
+
279
+ def __setstate__(self, state: list[Any]) -> None:
280
+ path, size, index, encoding, layout_engine = state
281
+ FreeTypeFont.__init__(self, path, size, index, encoding, layout_engine)
282
+
283
+ def getname(self) -> tuple[str | None, str | None]:
284
+ """
285
+ :return: A tuple of the font family (e.g. Helvetica) and the font style
286
+ (e.g. Bold)
287
+ """
288
+ return self.font.family, self.font.style
289
+
290
+ def getmetrics(self) -> tuple[int, int]:
291
+ """
292
+ :return: A tuple of the font ascent (the distance from the baseline to
293
+ the highest outline point) and descent (the distance from the
294
+ baseline to the lowest outline point, a negative value)
295
+ """
296
+ return self.font.ascent, self.font.descent
297
+
298
+ def getlength(
299
+ self,
300
+ text: str | bytes,
301
+ mode: str = "",
302
+ direction: str | None = None,
303
+ features: list[str] | None = None,
304
+ language: str | None = None,
305
+ ) -> float:
306
+ """
307
+ Returns length (in pixels with 1/64 precision) of given text when rendered
308
+ in font with provided direction, features, and language.
309
+
310
+ This is the amount by which following text should be offset.
311
+ Text bounding box may extend past the length in some fonts,
312
+ e.g. when using italics or accents.
313
+
314
+ The result is returned as a float; it is a whole number if using basic layout.
315
+
316
+ Note that the sum of two lengths may not equal the length of a concatenated
317
+ string due to kerning. If you need to adjust for kerning, include the following
318
+ character and subtract its length.
319
+
320
+ For example, instead of ::
321
+
322
+ hello = font.getlength("Hello")
323
+ world = font.getlength("World")
324
+ hello_world = hello + world # not adjusted for kerning
325
+ assert hello_world == font.getlength("HelloWorld") # may fail
326
+
327
+ use ::
328
+
329
+ hello = font.getlength("HelloW") - font.getlength("W") # adjusted for kerning
330
+ world = font.getlength("World")
331
+ hello_world = hello + world # adjusted for kerning
332
+ assert hello_world == font.getlength("HelloWorld") # True
333
+
334
+ or disable kerning with (requires libraqm) ::
335
+
336
+ hello = draw.textlength("Hello", font, features=["-kern"])
337
+ world = draw.textlength("World", font, features=["-kern"])
338
+ hello_world = hello + world # kerning is disabled, no need to adjust
339
+ assert hello_world == draw.textlength("HelloWorld", font, features=["-kern"])
340
+
341
+ .. versionadded:: 8.0.0
342
+
343
+ :param text: Text to measure.
344
+ :param mode: Used by some graphics drivers to indicate what mode the
345
+ driver prefers; if empty, the renderer may return either
346
+ mode. Note that the mode is always a string, to simplify
347
+ C-level implementations.
348
+
349
+ :param direction: Direction of the text. It can be 'rtl' (right to
350
+ left), 'ltr' (left to right) or 'ttb' (top to bottom).
351
+ Requires libraqm.
352
+
353
+ :param features: A list of OpenType font features to be used during text
354
+ layout. This is usually used to turn on optional
355
+ font features that are not enabled by default,
356
+ for example 'dlig' or 'ss01', but can be also
357
+ used to turn off default font features for
358
+ example '-liga' to disable ligatures or '-kern'
359
+ to disable kerning. To get all supported
360
+ features, see
361
+ https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist
362
+ Requires libraqm.
363
+
364
+ :param language: Language of the text. Different languages may use
365
+ different glyph shapes or ligatures. This parameter tells
366
+ the font which language the text is in, and to apply the
367
+ correct substitutions as appropriate, if available.
368
+ It should be a `BCP 47 language code
369
+ <https://www.w3.org/International/articles/language-tags/>`_
370
+ Requires libraqm.
371
+
372
+ :return: Either width for horizontal text, or height for vertical text.
373
+ """
374
+ _string_length_check(text)
375
+ return self.font.getlength(text, mode, direction, features, language) / 64
376
+
377
+ def getbbox(
378
+ self,
379
+ text: str | bytes,
380
+ mode: str = "",
381
+ direction: str | None = None,
382
+ features: list[str] | None = None,
383
+ language: str | None = None,
384
+ stroke_width: float = 0,
385
+ anchor: str | None = None,
386
+ ) -> tuple[float, float, float, float]:
387
+ """
388
+ Returns bounding box (in pixels) of given text relative to given anchor
389
+ when rendered in font with provided direction, features, and language.
390
+
391
+ Use :py:meth:`getlength()` to get the offset of following text with
392
+ 1/64 pixel precision. The bounding box includes extra margins for
393
+ some fonts, e.g. italics or accents.
394
+
395
+ .. versionadded:: 8.0.0
396
+
397
+ :param text: Text to render.
398
+ :param mode: Used by some graphics drivers to indicate what mode the
399
+ driver prefers; if empty, the renderer may return either
400
+ mode. Note that the mode is always a string, to simplify
401
+ C-level implementations.
402
+
403
+ :param direction: Direction of the text. It can be 'rtl' (right to
404
+ left), 'ltr' (left to right) or 'ttb' (top to bottom).
405
+ Requires libraqm.
406
+
407
+ :param features: A list of OpenType font features to be used during text
408
+ layout. This is usually used to turn on optional
409
+ font features that are not enabled by default,
410
+ for example 'dlig' or 'ss01', but can be also
411
+ used to turn off default font features for
412
+ example '-liga' to disable ligatures or '-kern'
413
+ to disable kerning. To get all supported
414
+ features, see
415
+ https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist
416
+ Requires libraqm.
417
+
418
+ :param language: Language of the text. Different languages may use
419
+ different glyph shapes or ligatures. This parameter tells
420
+ the font which language the text is in, and to apply the
421
+ correct substitutions as appropriate, if available.
422
+ It should be a `BCP 47 language code
423
+ <https://www.w3.org/International/articles/language-tags/>`_
424
+ Requires libraqm.
425
+
426
+ :param stroke_width: The width of the text stroke.
427
+
428
+ :param anchor: The text anchor alignment. Determines the relative location of
429
+ the anchor to the text. The default alignment is top left,
430
+ specifically ``la`` for horizontal text and ``lt`` for
431
+ vertical text. See :ref:`text-anchors` for details.
432
+
433
+ :return: ``(left, top, right, bottom)`` bounding box
434
+ """
435
+ _string_length_check(text)
436
+ size, offset = self.font.getsize(
437
+ text, mode, direction, features, language, anchor
438
+ )
439
+ left, top = offset[0] - stroke_width, offset[1] - stroke_width
440
+ width, height = size[0] + 2 * stroke_width, size[1] + 2 * stroke_width
441
+ return left, top, left + width, top + height
442
+
443
+ def getmask(
444
+ self,
445
+ text: str | bytes,
446
+ mode: str = "",
447
+ direction: str | None = None,
448
+ features: list[str] | None = None,
449
+ language: str | None = None,
450
+ stroke_width: float = 0,
451
+ anchor: str | None = None,
452
+ ink: int = 0,
453
+ start: tuple[float, float] | None = None,
454
+ ) -> Image.core.ImagingCore:
455
+ """
456
+ Create a bitmap for the text.
457
+
458
+ If the font uses antialiasing, the bitmap should have mode ``L`` and use a
459
+ maximum value of 255. If the font has embedded color data, the bitmap
460
+ should have mode ``RGBA``. Otherwise, it should have mode ``1``.
461
+
462
+ :param text: Text to render.
463
+ :param mode: Used by some graphics drivers to indicate what mode the
464
+ driver prefers; if empty, the renderer may return either
465
+ mode. Note that the mode is always a string, to simplify
466
+ C-level implementations.
467
+
468
+ .. versionadded:: 1.1.5
469
+
470
+ :param direction: Direction of the text. It can be 'rtl' (right to
471
+ left), 'ltr' (left to right) or 'ttb' (top to bottom).
472
+ Requires libraqm.
473
+
474
+ .. versionadded:: 4.2.0
475
+
476
+ :param features: A list of OpenType font features to be used during text
477
+ layout. This is usually used to turn on optional
478
+ font features that are not enabled by default,
479
+ for example 'dlig' or 'ss01', but can be also
480
+ used to turn off default font features for
481
+ example '-liga' to disable ligatures or '-kern'
482
+ to disable kerning. To get all supported
483
+ features, see
484
+ https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist
485
+ Requires libraqm.
486
+
487
+ .. versionadded:: 4.2.0
488
+
489
+ :param language: Language of the text. Different languages may use
490
+ different glyph shapes or ligatures. This parameter tells
491
+ the font which language the text is in, and to apply the
492
+ correct substitutions as appropriate, if available.
493
+ It should be a `BCP 47 language code
494
+ <https://www.w3.org/International/articles/language-tags/>`_
495
+ Requires libraqm.
496
+
497
+ .. versionadded:: 6.0.0
498
+
499
+ :param stroke_width: The width of the text stroke.
500
+
501
+ .. versionadded:: 6.2.0
502
+
503
+ :param anchor: The text anchor alignment. Determines the relative location of
504
+ the anchor to the text. The default alignment is top left,
505
+ specifically ``la`` for horizontal text and ``lt`` for
506
+ vertical text. See :ref:`text-anchors` for details.
507
+
508
+ .. versionadded:: 8.0.0
509
+
510
+ :param ink: Foreground ink for rendering in RGBA mode.
511
+
512
+ .. versionadded:: 8.0.0
513
+
514
+ :param start: Tuple of horizontal and vertical offset, as text may render
515
+ differently when starting at fractional coordinates.
516
+
517
+ .. versionadded:: 9.4.0
518
+
519
+ :return: An internal PIL storage memory instance as defined by the
520
+ :py:mod:`PIL.Image.core` interface module.
521
+ """
522
+ return self.getmask2(
523
+ text,
524
+ mode,
525
+ direction=direction,
526
+ features=features,
527
+ language=language,
528
+ stroke_width=stroke_width,
529
+ anchor=anchor,
530
+ ink=ink,
531
+ start=start,
532
+ )[0]
533
+
534
+ def getmask2(
535
+ self,
536
+ text: str | bytes,
537
+ mode: str = "",
538
+ direction: str | None = None,
539
+ features: list[str] | None = None,
540
+ language: str | None = None,
541
+ stroke_width: float = 0,
542
+ anchor: str | None = None,
543
+ ink: int = 0,
544
+ start: tuple[float, float] | None = None,
545
+ *args: Any,
546
+ **kwargs: Any,
547
+ ) -> tuple[Image.core.ImagingCore, tuple[int, int]]:
548
+ """
549
+ Create a bitmap for the text.
550
+
551
+ If the font uses antialiasing, the bitmap should have mode ``L`` and use a
552
+ maximum value of 255. If the font has embedded color data, the bitmap
553
+ should have mode ``RGBA``. Otherwise, it should have mode ``1``.
554
+
555
+ :param text: Text to render.
556
+ :param mode: Used by some graphics drivers to indicate what mode the
557
+ driver prefers; if empty, the renderer may return either
558
+ mode. Note that the mode is always a string, to simplify
559
+ C-level implementations.
560
+
561
+ .. versionadded:: 1.1.5
562
+
563
+ :param direction: Direction of the text. It can be 'rtl' (right to
564
+ left), 'ltr' (left to right) or 'ttb' (top to bottom).
565
+ Requires libraqm.
566
+
567
+ .. versionadded:: 4.2.0
568
+
569
+ :param features: A list of OpenType font features to be used during text
570
+ layout. This is usually used to turn on optional
571
+ font features that are not enabled by default,
572
+ for example 'dlig' or 'ss01', but can be also
573
+ used to turn off default font features for
574
+ example '-liga' to disable ligatures or '-kern'
575
+ to disable kerning. To get all supported
576
+ features, see
577
+ https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist
578
+ Requires libraqm.
579
+
580
+ .. versionadded:: 4.2.0
581
+
582
+ :param language: Language of the text. Different languages may use
583
+ different glyph shapes or ligatures. This parameter tells
584
+ the font which language the text is in, and to apply the
585
+ correct substitutions as appropriate, if available.
586
+ It should be a `BCP 47 language code
587
+ <https://www.w3.org/International/articles/language-tags/>`_
588
+ Requires libraqm.
589
+
590
+ .. versionadded:: 6.0.0
591
+
592
+ :param stroke_width: The width of the text stroke.
593
+
594
+ .. versionadded:: 6.2.0
595
+
596
+ :param anchor: The text anchor alignment. Determines the relative location of
597
+ the anchor to the text. The default alignment is top left,
598
+ specifically ``la`` for horizontal text and ``lt`` for
599
+ vertical text. See :ref:`text-anchors` for details.
600
+
601
+ .. versionadded:: 8.0.0
602
+
603
+ :param ink: Foreground ink for rendering in RGBA mode.
604
+
605
+ .. versionadded:: 8.0.0
606
+
607
+ :param start: Tuple of horizontal and vertical offset, as text may render
608
+ differently when starting at fractional coordinates.
609
+
610
+ .. versionadded:: 9.4.0
611
+
612
+ :return: A tuple of an internal PIL storage memory instance as defined by the
613
+ :py:mod:`PIL.Image.core` interface module, and the text offset, the
614
+ gap between the starting coordinate and the first marking
615
+ """
616
+ _string_length_check(text)
617
+ if start is None:
618
+ start = (0, 0)
619
+
620
+ def fill(width: int, height: int) -> Image.core.ImagingCore:
621
+ size = (width, height)
622
+ Image._decompression_bomb_check(size)
623
+ return Image.core.fill("RGBA" if mode == "RGBA" else "L", size)
624
+
625
+ return self.font.render(
626
+ text,
627
+ fill,
628
+ mode,
629
+ direction,
630
+ features,
631
+ language,
632
+ stroke_width,
633
+ kwargs.get("stroke_filled", False),
634
+ anchor,
635
+ ink,
636
+ start,
637
+ )
638
+
639
+ def font_variant(
640
+ self,
641
+ font: StrOrBytesPath | BinaryIO | None = None,
642
+ size: float | None = None,
643
+ index: int | None = None,
644
+ encoding: str | None = None,
645
+ layout_engine: Layout | None = None,
646
+ ) -> FreeTypeFont:
647
+ """
648
+ Create a copy of this FreeTypeFont object,
649
+ using any specified arguments to override the settings.
650
+
651
+ Parameters are identical to the parameters used to initialize this
652
+ object.
653
+
654
+ :return: A FreeTypeFont object.
655
+ """
656
+ if font is None:
657
+ try:
658
+ font = BytesIO(self.font_bytes)
659
+ except AttributeError:
660
+ font = self.path
661
+ return FreeTypeFont(
662
+ font=font,
663
+ size=self.size if size is None else size,
664
+ index=self.index if index is None else index,
665
+ encoding=self.encoding if encoding is None else encoding,
666
+ layout_engine=layout_engine or self.layout_engine,
667
+ )
668
+
669
+ def get_variation_names(self) -> list[bytes]:
670
+ """
671
+ :returns: A list of the named styles in a variation font.
672
+ :exception OSError: If the font is not a variation font.
673
+ """
674
+ names = self.font.getvarnames()
675
+ return [name.replace(b"\x00", b"") for name in names]
676
+
677
+ def set_variation_by_name(self, name: str | bytes) -> None:
678
+ """
679
+ :param name: The name of the style.
680
+ :exception OSError: If the font is not a variation font.
681
+ """
682
+ names = self.get_variation_names()
683
+ if not isinstance(name, bytes):
684
+ name = name.encode()
685
+ index = names.index(name) + 1
686
+
687
+ if index == getattr(self, "_last_variation_index", None):
688
+ # When the same name is set twice in a row,
689
+ # there is an 'unknown freetype error'
690
+ # https://savannah.nongnu.org/bugs/?56186
691
+ return
692
+ self._last_variation_index = index
693
+
694
+ self.font.setvarname(index)
695
+
696
+ def get_variation_axes(self) -> list[Axis]:
697
+ """
698
+ :returns: A list of the axes in a variation font.
699
+ :exception OSError: If the font is not a variation font.
700
+ """
701
+ axes = self.font.getvaraxes()
702
+ for axis in axes:
703
+ if axis["name"]:
704
+ axis["name"] = axis["name"].replace(b"\x00", b"")
705
+ return axes
706
+
707
+ def set_variation_by_axes(self, axes: list[float]) -> None:
708
+ """
709
+ :param axes: A list of values for each axis.
710
+ :exception OSError: If the font is not a variation font.
711
+ """
712
+ self.font.setvaraxes(axes)
713
+
714
+
715
+ class TransposedFont:
716
+ """Wrapper for writing rotated or mirrored text"""
717
+
718
+ def __init__(
719
+ self, font: ImageFont | FreeTypeFont, orientation: Image.Transpose | None = None
720
+ ):
721
+ """
722
+ Wrapper that creates a transposed font from any existing font
723
+ object.
724
+
725
+ :param font: A font object.
726
+ :param orientation: An optional orientation. If given, this should
727
+ be one of Image.Transpose.FLIP_LEFT_RIGHT, Image.Transpose.FLIP_TOP_BOTTOM,
728
+ Image.Transpose.ROTATE_90, Image.Transpose.ROTATE_180, or
729
+ Image.Transpose.ROTATE_270.
730
+ """
731
+ self.font = font
732
+ self.orientation = orientation # any 'transpose' argument, or None
733
+
734
+ def getmask(
735
+ self, text: str | bytes, mode: str = "", *args: Any, **kwargs: Any
736
+ ) -> Image.core.ImagingCore:
737
+ im = self.font.getmask(text, mode, *args, **kwargs)
738
+ if self.orientation is not None:
739
+ return im.transpose(self.orientation)
740
+ return im
741
+
742
+ def getbbox(
743
+ self, text: str | bytes, *args: Any, **kwargs: Any
744
+ ) -> tuple[int, int, float, float]:
745
+ # TransposedFont doesn't support getmask2, move top-left point to (0, 0)
746
+ # this has no effect on ImageFont and simulates anchor="lt" for FreeTypeFont
747
+ left, top, right, bottom = self.font.getbbox(text, *args, **kwargs)
748
+ width = right - left
749
+ height = bottom - top
750
+ if self.orientation in (Image.Transpose.ROTATE_90, Image.Transpose.ROTATE_270):
751
+ return 0, 0, height, width
752
+ return 0, 0, width, height
753
+
754
+ def getlength(self, text: str | bytes, *args: Any, **kwargs: Any) -> float:
755
+ if self.orientation in (Image.Transpose.ROTATE_90, Image.Transpose.ROTATE_270):
756
+ msg = "text length is undefined for text rotated by 90 or 270 degrees"
757
+ raise ValueError(msg)
758
+ return self.font.getlength(text, *args, **kwargs)
759
+
760
+
761
+ def load(filename: str) -> ImageFont:
762
+ """
763
+ Load a font file. This function loads a font object from the given
764
+ bitmap font file, and returns the corresponding font object. For loading TrueType
765
+ or OpenType fonts instead, see :py:func:`~PIL.ImageFont.truetype`.
766
+
767
+ :param filename: Name of font file.
768
+ :return: A font object.
769
+ :exception OSError: If the file could not be read.
770
+ """
771
+ f = ImageFont()
772
+ f._load_pilfont(filename)
773
+ return f
774
+
775
+
776
+ def truetype(
777
+ font: StrOrBytesPath | BinaryIO,
778
+ size: float = 10,
779
+ index: int = 0,
780
+ encoding: str = "",
781
+ layout_engine: Layout | None = None,
782
+ ) -> FreeTypeFont:
783
+ """
784
+ Load a TrueType or OpenType font from a file or file-like object,
785
+ and create a font object. This function loads a font object from the given
786
+ file or file-like object, and creates a font object for a font of the given
787
+ size. For loading bitmap fonts instead, see :py:func:`~PIL.ImageFont.load`
788
+ and :py:func:`~PIL.ImageFont.load_path`.
789
+
790
+ Pillow uses FreeType to open font files. On Windows, be aware that FreeType
791
+ will keep the file open as long as the FreeTypeFont object exists. Windows
792
+ limits the number of files that can be open in C at once to 512, so if many
793
+ fonts are opened simultaneously and that limit is approached, an
794
+ ``OSError`` may be thrown, reporting that FreeType "cannot open resource".
795
+ A workaround would be to copy the file(s) into memory, and open that instead.
796
+
797
+ This function requires the _imagingft service.
798
+
799
+ :param font: A filename or file-like object containing a TrueType font.
800
+ If the file is not found in this filename, the loader may also
801
+ search in other directories, such as:
802
+
803
+ * The :file:`fonts/` directory on Windows,
804
+ * :file:`/Library/Fonts/`, :file:`/System/Library/Fonts/`
805
+ and :file:`~/Library/Fonts/` on macOS.
806
+ * :file:`~/.local/share/fonts`, :file:`/usr/local/share/fonts`,
807
+ and :file:`/usr/share/fonts` on Linux; or those specified by
808
+ the ``XDG_DATA_HOME`` and ``XDG_DATA_DIRS`` environment variables
809
+ for user-installed and system-wide fonts, respectively.
810
+
811
+ :param size: The requested size, in pixels.
812
+ :param index: Which font face to load (default is first available face).
813
+ :param encoding: Which font encoding to use (default is Unicode). Possible
814
+ encodings include (see the FreeType documentation for more
815
+ information):
816
+
817
+ * "unic" (Unicode)
818
+ * "symb" (Microsoft Symbol)
819
+ * "ADOB" (Adobe Standard)
820
+ * "ADBE" (Adobe Expert)
821
+ * "ADBC" (Adobe Custom)
822
+ * "armn" (Apple Roman)
823
+ * "sjis" (Shift JIS)
824
+ * "gb " (PRC)
825
+ * "big5"
826
+ * "wans" (Extended Wansung)
827
+ * "joha" (Johab)
828
+ * "lat1" (Latin-1)
829
+
830
+ This specifies the character set to use. It does not alter the
831
+ encoding of any text provided in subsequent operations.
832
+ :param layout_engine: Which layout engine to use, if available:
833
+ :attr:`.ImageFont.Layout.BASIC` or :attr:`.ImageFont.Layout.RAQM`.
834
+ If it is available, Raqm layout will be used by default.
835
+ Otherwise, basic layout will be used.
836
+
837
+ Raqm layout is recommended for all non-English text. If Raqm layout
838
+ is not required, basic layout will have better performance.
839
+
840
+ You can check support for Raqm layout using
841
+ :py:func:`PIL.features.check_feature` with ``feature="raqm"``.
842
+
843
+ .. versionadded:: 4.2.0
844
+ :return: A font object.
845
+ :exception OSError: If the file could not be read.
846
+ :exception ValueError: If the font size is not greater than zero.
847
+ """
848
+
849
+ def freetype(font: StrOrBytesPath | BinaryIO) -> FreeTypeFont:
850
+ return FreeTypeFont(font, size, index, encoding, layout_engine)
851
+
852
+ try:
853
+ return freetype(font)
854
+ except OSError:
855
+ if not is_path(font):
856
+ raise
857
+ ttf_filename = os.path.basename(font)
858
+
859
+ dirs = []
860
+ if sys.platform == "win32":
861
+ # check the windows font repository
862
+ # NOTE: must use uppercase WINDIR, to work around bugs in
863
+ # 1.5.2's os.environ.get()
864
+ windir = os.environ.get("WINDIR")
865
+ if windir:
866
+ dirs.append(os.path.join(windir, "fonts"))
867
+ elif sys.platform in ("linux", "linux2"):
868
+ data_home = os.environ.get("XDG_DATA_HOME")
869
+ if not data_home:
870
+ # The freedesktop spec defines the following default directory for
871
+ # when XDG_DATA_HOME is unset or empty. This user-level directory
872
+ # takes precedence over system-level directories.
873
+ data_home = os.path.expanduser("~/.local/share")
874
+ xdg_dirs = [data_home]
875
+
876
+ data_dirs = os.environ.get("XDG_DATA_DIRS")
877
+ if not data_dirs:
878
+ # Similarly, defaults are defined for the system-level directories
879
+ data_dirs = "/usr/local/share:/usr/share"
880
+ xdg_dirs += data_dirs.split(":")
881
+
882
+ dirs += [os.path.join(xdg_dir, "fonts") for xdg_dir in xdg_dirs]
883
+ elif sys.platform == "darwin":
884
+ dirs += [
885
+ "/Library/Fonts",
886
+ "/System/Library/Fonts",
887
+ os.path.expanduser("~/Library/Fonts"),
888
+ ]
889
+
890
+ ext = os.path.splitext(ttf_filename)[1]
891
+ first_font_with_a_different_extension = None
892
+ for directory in dirs:
893
+ for walkroot, walkdir, walkfilenames in os.walk(directory):
894
+ for walkfilename in walkfilenames:
895
+ if ext and walkfilename == ttf_filename:
896
+ return freetype(os.path.join(walkroot, walkfilename))
897
+ elif not ext and os.path.splitext(walkfilename)[0] == ttf_filename:
898
+ fontpath = os.path.join(walkroot, walkfilename)
899
+ if os.path.splitext(fontpath)[1] == ".ttf":
900
+ return freetype(fontpath)
901
+ if not ext and first_font_with_a_different_extension is None:
902
+ first_font_with_a_different_extension = fontpath
903
+ if first_font_with_a_different_extension:
904
+ return freetype(first_font_with_a_different_extension)
905
+ raise
906
+
907
+
908
+ def load_path(filename: str | bytes) -> ImageFont:
909
+ """
910
+ Load font file. Same as :py:func:`~PIL.ImageFont.load`, but searches for a
911
+ bitmap font along the Python path.
912
+
913
+ :param filename: Name of font file.
914
+ :return: A font object.
915
+ :exception OSError: If the file could not be read.
916
+ """
917
+ if not isinstance(filename, str):
918
+ filename = filename.decode("utf-8")
919
+ for directory in sys.path:
920
+ try:
921
+ return load(os.path.join(directory, filename))
922
+ except OSError:
923
+ pass
924
+ msg = f'cannot find font file "{filename}" in sys.path'
925
+ if os.path.exists(filename):
926
+ msg += f', did you mean ImageFont.load("{filename}") instead?'
927
+
928
+ raise OSError(msg)
929
+
930
+
931
+ def load_default_imagefont() -> ImageFont:
932
+ f = ImageFont()
933
+ f._load_pilfont_data(
934
+ # courB08
935
+ BytesIO(
936
+ base64.b64decode(
937
+ b"""
938
+ UElMZm9udAo7Ozs7OzsxMDsKREFUQQoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
939
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
940
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
941
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
942
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
943
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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AAYAAAAA//kABQAAAFYAAABbAAcABgAAAAD/+QAFAAAAWwAAAGAABwAGAAAAAP/5AAUAAABgAAAA
958
+ ZQAHAAYAAAAA//kABQAAAGUAAABqAAcABgAAAAD/+QAFAAAAagAAAG8ABwAGAAAAAf/8AAMAAABv
959
+ AAAAcQAEAAYAAAAA//wAAwACAHEAAAB0AAYABgAAAAD/+gAE//8AdAAAAHgABQAGAAAAAP/7AAT/
960
+ /gB4AAAAfAADAAYAAAAB//oABf//AHwAAACAAAUABgAAAAD/+gAFAAAAgAAAAIUABgAGAAAAAP/5
961
+ AAYAAQCFAAAAiwAIAAYAAP////oABgAAAIsAAACSAAYABgAA////+gAFAAAAkgAAAJgABgAGAAAA
962
+ AP/6AAUAAACYAAAAnQAGAAYAAP////oABQAAAJ0AAACjAAYABgAA////+gAFAAAAowAAAKkABgAG
963
+ AAD////6AAUAAACpAAAArwAGAAYAAAAA//oABQAAAK8AAAC0AAYABgAA////+gAGAAAAtAAAALsA
964
+ BgAGAAAAAP/6AAQAAAC7AAAAvwAGAAYAAP////oABQAAAL8AAADFAAYABgAA////+gAGAAAAxQAA
965
+ AMwABgAGAAD////6AAUAAADMAAAA0gAGAAYAAP////oABQAAANIAAADYAAYABgAA////+gAGAAAA
966
+ 2AAAAN8ABgAGAAAAAP/6AAUAAADfAAAA5AAGAAYAAP////oABQAAAOQAAADqAAYABgAAAAD/+gAF
967
+ AAEA6gAAAO8ABwAGAAD////6AAYAAADvAAAA9gAGAAYAAAAA//oABQAAAPYAAAD7AAYABgAA////
968
+ +gAFAAAA+wAAAQEABgAGAAD////6AAYAAAEBAAABCAAGAAYAAP////oABgAAAQgAAAEPAAYABgAA
969
+ ////+gAGAAABDwAAARYABgAGAAAAAP/6AAYAAAEWAAABHAAGAAYAAP////oABgAAARwAAAEjAAYA
970
+ BgAAAAD/+gAFAAABIwAAASgABgAGAAAAAf/5AAQAAQEoAAABKwAIAAYAAAAA//kABAABASsAAAEv
971
+ AAgABgAAAAH/+QAEAAEBLwAAATIACAAGAAAAAP/5AAX//AEyAAABNwADAAYAAAAAAAEABgACATcA
972
+ AAE9AAEABgAAAAH/+QAE//wBPQAAAUAAAwAGAAAAAP/7AAYAAAFAAAABRgAFAAYAAP////kABQAA
973
+ AUYAAAFMAAcABgAAAAD/+wAFAAABTAAAAVEABQAGAAAAAP/5AAYAAAFRAAABVwAHAAYAAAAA//sA
974
+ BQAAAVcAAAFcAAUABgAAAAD/+QAFAAABXAAAAWEABwAGAAAAAP/7AAYAAgFhAAABZwAHAAYAAP//
975
+ //kABQAAAWcAAAFtAAcABgAAAAD/+QAGAAABbQAAAXMABwAGAAAAAP/5AAQAAgFzAAABdwAJAAYA
976
+ AP////kABgAAAXcAAAF+AAcABgAAAAD/+QAGAAABfgAAAYQABwAGAAD////7AAUAAAGEAAABigAF
977
+ AAYAAP////sABQAAAYoAAAGQAAUABgAAAAD/+wAFAAABkAAAAZUABQAGAAD////7AAUAAgGVAAAB
978
+ mwAHAAYAAAAA//sABgACAZsAAAGhAAcABgAAAAD/+wAGAAABoQAAAacABQAGAAAAAP/7AAYAAAGn
979
+ AAABrQAFAAYAAAAA//kABgAAAa0AAAGzAAcABgAA////+wAGAAABswAAAboABQAGAAD////7AAUA
980
+ AAG6AAABwAAFAAYAAP////sABgAAAcAAAAHHAAUABgAAAAD/+wAGAAABxwAAAc0ABQAGAAD////7
981
+ AAYAAgHNAAAB1AAHAAYAAAAA//sABQAAAdQAAAHZAAUABgAAAAH/+QAFAAEB2QAAAd0ACAAGAAAA
982
+ Av/6AAMAAQHdAAAB3gAHAAYAAAAA//kABAABAd4AAAHiAAgABgAAAAD/+wAF//0B4gAAAecAAgAA
983
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
984
+ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
985
+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AYAAAIIAAAC
998
+ DgAHAAYAAAAB//kABf/+Ag4AAAISAAUABgAA////+wAGAAACEgAAAhkABQAGAAAAAP/7AAX//gIZ
999
+ AAACHgADAAYAAAAA//wABf/9Ah4AAAIjAAEABgAAAAD/+QAHAAACIwAAAioABwAGAAAAAP/6AAT/
1000
+ +wIqAAACLgABAAYAAAAA//kABP/8Ai4AAAIyAAMABgAAAAD/+gAFAAACMgAAAjcABgAGAAAAAf/5
1001
+ AAT//QI3AAACOgAEAAYAAAAB//kABP/9AjoAAAI9AAQABgAAAAL/+QAE//sCPQAAAj8AAgAGAAD/
1002
+ ///7AAYAAgI/AAACRgAHAAYAAAAA//kABgABAkYAAAJMAAgABgAAAAH//AAD//0CTAAAAk4AAQAG
1003
+ AAAAAf//AAQAAgJOAAACUQADAAYAAAAB//kABP/9AlEAAAJUAAQABgAAAAH/+QAF//4CVAAAAlgA
1004
+ BQAGAAD////7AAYAAAJYAAACXwAFAAYAAP////kABgAAAl8AAAJmAAcABgAA////+QAGAAACZgAA
1005
+ Am0ABwAGAAD////5AAYAAAJtAAACdAAHAAYAAAAA//sABQACAnQAAAJ5AAcABgAA////9wAGAAAC
1006
+ eQAAAoAACQAGAAD////3AAYAAAKAAAAChwAJAAYAAP////cABgAAAocAAAKOAAkABgAA////9wAG
1007
+ AAACjgAAApUACQAGAAD////4AAYAAAKVAAACnAAIAAYAAP////cABgAAApwAAAKjAAkABgAA////
1008
+ +gAGAAACowAAAqoABgAGAAAAAP/6AAUAAgKqAAACrwAIAAYAAP////cABQAAAq8AAAK1AAkABgAA
1009
+ ////9wAFAAACtQAAArsACQAGAAD////3AAUAAAK7AAACwQAJAAYAAP////gABQAAAsEAAALHAAgA
1010
+ BgAAAAD/9wAEAAACxwAAAssACQAGAAAAAP/3AAQAAALLAAACzwAJAAYAAAAA//cABAAAAs8AAALT
1011
+ AAkABgAAAAD/+AAEAAAC0wAAAtcACAAGAAD////6AAUAAALXAAAC3QAGAAYAAP////cABgAAAt0A
1012
+ AALkAAkABgAAAAD/9wAFAAAC5AAAAukACQAGAAAAAP/3AAUAAALpAAAC7gAJAAYAAAAA//cABQAA
1013
+ Au4AAALzAAkABgAAAAD/9wAFAAAC8wAAAvgACQAGAAAAAP/4AAUAAAL4AAAC/QAIAAYAAAAA//oA
1014
+ Bf//Av0AAAMCAAUABgAA////+gAGAAADAgAAAwkABgAGAAD////3AAYAAAMJAAADEAAJAAYAAP//
1015
+ //cABgAAAxAAAAMXAAkABgAA////9wAGAAADFwAAAx4ACQAGAAD////4AAYAAAAAAAoABwASAAYA
1016
+ AP////cABgAAAAcACgAOABMABgAA////+gAFAAAADgAKABQAEAAGAAD////6AAYAAAAUAAoAGwAQ
1017
+ AAYAAAAA//gABgAAABsACgAhABIABgAAAAD/+AAGAAAAIQAKACcAEgAGAAAAAP/4AAYAAAAnAAoA
1018
+ LQASAAYAAAAA//gABgAAAC0ACgAzABIABgAAAAD/+QAGAAAAMwAKADkAEQAGAAAAAP/3AAYAAAA5
1019
+ AAoAPwATAAYAAP////sABQAAAD8ACgBFAA8ABgAAAAD/+wAFAAIARQAKAEoAEQAGAAAAAP/4AAUA
1020
+ AABKAAoATwASAAYAAAAA//gABQAAAE8ACgBUABIABgAAAAD/+AAFAAAAVAAKAFkAEgAGAAAAAP/5
1021
+ AAUAAABZAAoAXgARAAYAAAAA//gABgAAAF4ACgBkABIABgAAAAD/+AAGAAAAZAAKAGoAEgAGAAAA
1022
+ AP/4AAYAAABqAAoAcAASAAYAAAAA//kABgAAAHAACgB2ABEABgAAAAD/+AAFAAAAdgAKAHsAEgAG
1023
+ AAD////4AAYAAAB7AAoAggASAAYAAAAA//gABQAAAIIACgCHABIABgAAAAD/+AAFAAAAhwAKAIwA
1024
+ EgAGAAAAAP/4AAUAAACMAAoAkQASAAYAAAAA//gABQAAAJEACgCWABIABgAAAAD/+QAFAAAAlgAK
1025
+ AJsAEQAGAAAAAP/6AAX//wCbAAoAoAAPAAYAAAAA//oABQABAKAACgClABEABgAA////+AAGAAAA
1026
+ pQAKAKwAEgAGAAD////4AAYAAACsAAoAswASAAYAAP////gABgAAALMACgC6ABIABgAA////+QAG
1027
+ AAAAugAKAMEAEQAGAAD////4AAYAAgDBAAoAyAAUAAYAAP////kABQACAMgACgDOABMABgAA////
1028
+ +QAGAAIAzgAKANUAEw==
1029
+ """
1030
+ )
1031
+ ),
1032
+ Image.open(
1033
+ BytesIO(
1034
+ base64.b64decode(
1035
+ b"""
1036
+ iVBORw0KGgoAAAANSUhEUgAAAx4AAAAUAQAAAAArMtZoAAAEwElEQVR4nABlAJr/AHVE4czCI/4u
1037
+ Mc4b7vuds/xzjz5/3/7u/n9vMe7vnfH/9++vPn/xyf5zhxzjt8GHw8+2d83u8x27199/nxuQ6Od9
1038
+ M43/5z2I+9n9ZtmDBwMQECDRQw/eQIQohJXxpBCNVE6QCCAAAAD//wBlAJr/AgALyj1t/wINwq0g
1039
+ LeNZUworuN1cjTPIzrTX6ofHWeo3v336qPzfEwRmBnHTtf95/fglZK5N0PDgfRTslpGBvz7LFc4F
1040
+ IUXBWQGjQ5MGCx34EDFPwXiY4YbYxavpnhHFrk14CDAAAAD//wBlAJr/AgKqRooH2gAgPeggvUAA
1041
+ Bu2WfgPoAwzRAABAAAAAAACQgLz/3Uv4Gv+gX7BJgDeeGP6AAAD1NMDzKHD7ANWr3loYbxsAD791
1042
+ NAADfcoIDyP44K/jv4Y63/Z+t98Ovt+ub4T48LAAAAD//wBlAJr/AuplMlADJAAAAGuAphWpqhMx
1043
+ in0A/fRvAYBABPgBwBUgABBQ/sYAyv9g0bCHgOLoGAAAAAAAREAAwI7nr0ArYpow7aX8//9LaP/9
1044
+ SjdavWA8ePHeBIKB//81/83ndznOaXx379wAAAD//wBlAJr/AqDxW+D3AABAAbUh/QMnbQag/gAY
1045
+ AYDAAACgtgD/gOqAAAB5IA/8AAAk+n9w0AAA8AAAmFRJuPo27ciC0cD5oeW4E7KA/wD3ECMAn2tt
1046
+ y8PgwH8AfAxFzC0JzeAMtratAsC/ffwAAAD//wBlAJr/BGKAyCAA4AAAAvgeYTAwHd1kmQF5chkG
1047
+ ABoMIHcL5xVpTfQbUqzlAAAErwAQBgAAEOClA5D9il08AEh/tUzdCBsXkbgACED+woQg8Si9VeqY
1048
+ lODCn7lmF6NhnAEYgAAA/NMIAAAAAAD//2JgjLZgVGBg5Pv/Tvpc8hwGBjYGJADjHDrAwPzAjv/H
1049
+ /Wf3PzCwtzcwHmBgYGcwbZz8wHaCAQMDOwMDQ8MCBgYOC3W7mp+f0w+wHOYxO3OG+e376hsMZjk3
1050
+ AAAAAP//YmCMY2A4wMAIN5e5gQETPD6AZisDAwMDgzSDAAPjByiHcQMDAwMDg1nOze1lByRu5/47
1051
+ c4859311AYNZzg0AAAAA//9iYGDBYihOIIMuwIjGL39/fwffA8b//xv/P2BPtzzHwCBjUQAAAAD/
1052
+ /yLFBrIBAAAA//9i1HhcwdhizX7u8NZNzyLbvT97bfrMf/QHI8evOwcSqGUJAAAA//9iYBB81iSw
1053
+ pEE170Qrg5MIYydHqwdDQRMrAwcVrQAAAAD//2J4x7j9AAMDn8Q/BgYLBoaiAwwMjPdvMDBYM1Tv
1054
+ oJodAAAAAP//Yqo/83+dxePWlxl3npsel9lvLfPcqlE9725C+acfVLMEAAAA//9i+s9gwCoaaGMR
1055
+ evta/58PTEWzr21hufPjA8N+qlnBwAAAAAD//2JiWLci5v1+HmFXDqcnULE/MxgYGBj+f6CaJQAA
1056
+ AAD//2Ji2FrkY3iYpYC5qDeGgeEMAwPDvwQBBoYvcTwOVLMEAAAA//9isDBgkP///0EOg9z35v//
1057
+ Gc/eeW7BwPj5+QGZhANUswMAAAD//2JgqGBgYGBgqEMXlvhMPUsAAAAA//8iYDd1AAAAAP//AwDR
1058
+ w7IkEbzhVQAAAABJRU5ErkJggg==
1059
+ """
1060
+ )
1061
+ )
1062
+ ),
1063
+ )
1064
+ return f
1065
+
1066
+
1067
+ def load_default(size: float | None = None) -> FreeTypeFont | ImageFont:
1068
+ """If FreeType support is available, load a version of Aileron Regular,
1069
+ https://dotcolon.net/fonts/aileron, with a more limited character set.
1070
+
1071
+ Otherwise, load a "better than nothing" font.
1072
+
1073
+ .. versionadded:: 1.1.4
1074
+
1075
+ :param size: The font size of Aileron Regular.
1076
+
1077
+ .. versionadded:: 10.1.0
1078
+
1079
+ :return: A font object.
1080
+ """
1081
+ if isinstance(core, ModuleType) or size is not None:
1082
+ return truetype(
1083
+ BytesIO(
1084
+ base64.b64decode(
1085
+ b"""
1086
+ AAEAAAAPAIAAAwBwRkZUTYwDlUAAADFoAAAAHEdERUYAqADnAAAo8AAAACRHUE9ThhmITwAAKfgAA
1087
+ AduR1NVQnHxefoAACkUAAAA4k9TLzJovoHLAAABeAAAAGBjbWFw5lFQMQAAA6gAAAGqZ2FzcP//AA
1088
+ MAACjoAAAACGdseWYmRXoPAAAGQAAAHfhoZWFkE18ayQAAAPwAAAA2aGhlYQboArEAAAE0AAAAJGh
1089
+ tdHjjERZ8AAAB2AAAAdBsb2NhuOexrgAABVQAAADqbWF4cAC7AEYAAAFYAAAAIG5hbWUr+h5lAAAk
1090
+ OAAAA6Jwb3N0D3oPTQAAJ9wAAAEKAAEAAAABGhxJDqIhXw889QALA+gAAAAA0Bqf2QAAAADhCh2h/
1091
+ 2r/LgOxAyAAAAAIAAIAAAAAAAAAAQAAA8r/GgAAA7j/av9qA7EAAQAAAAAAAAAAAAAAAAAAAHQAAQ
1092
+ AAAHQAQwAFAAAAAAACAAAAAQABAAAAQAAAAAAAAAADAfoBkAAFAAgCigJYAAAASwKKAlgAAAFeADI
1093
+ BPgAAAAAFAAAAAAAAAAAAAAcAAAAAAAAAAAAAAABVS1dOAEAAIPsCAwL/GgDIA8oA5iAAAJMAAAAA
1094
+ AhICsgAAACAAAwH0AAAAAAAAAU0AAADYAAAA8gA5AVMAVgJEAEYCRAA1AuQAKQKOAEAAsAArATsAZ
1095
+ AE7AB4CMABVAkQAUADc/+EBEgAgANwAJQEv//sCRAApAkQAggJE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1NCYnJi
1160
+ sBETMyAY59lJp8IzXN0jUVWmdjWRs5d3I4Aq4QqJWUug8EArL9mQ+PeHGHDgX92gAAAAABAGQAAAI
1161
+ vArIACwAAJRUhESEVIRUhFSEVAi/+NQHB/pUBTf6zRkYCskbwRvAAAAABAGQAAAIlArIACQAAExUh
1162
+ FSERIxEhFboBQ/69VgHBAmzwRv7KArJGAAAAAAEAL//yAo8CwAAfAAABMxEjNQcGIyImNTQ2MzIWH
1163
+ wEjJyYjIgYVFBYzMjY1IwGP90wfPnWTprSSf48LAVYCIqJofHllVG+hAU3+s3hARsicn8uAagoKpq
1164
+ N/gaN1XAAAAAEAZAAAAowCsgALAAABESMRIREjETMRIRECjFb+hFZWAXwCsv1OAS7+0gKy/sQBPAA
1165
+ AAAABAGQAAAC6ArIAAwAAMyMRM7pWVgKyAAABADf/8gHoArIAEwAAAREUBw4BIyImLwEzFxYzMjc2
1166
+ NREB6AIFcGpgbQIBVgIHfXQKAQKy/lYxIltob2EpKYyEFD0BpwAAAAABAGQAAAJ0ArIACwAACQEjA
1167
+ wcVIxEzEQEzATsBJ3ntQlZWAVVlAWH+nwEnR+ACsv6RAW8AAQBkAAACLwKyAAUAACUVIREzEQIv/j
1168
+ VWRkYCsv2UAAABAGQAAAMUArIAFAAAAREjETQ3BgcDIwMmJxYVESMRMxsBAxRWAiMxemx8NxsCVo7
1169
+ MywKy/U4BY7ZLco7+nAFmoFxLtP6dArL9lwJpAAAAAAEAZAAAAoACsgANAAAhIwEWFREjETMBJjUR
1170
+ MwKAhP67A1aEAUUDVAJeeov+pwKy/aJ5jAFZAAAAAgAv//ICuwLAAAkAEwAAEiAWFRQGICY1NBIyN
1171
+ jU0JiIGFRTbATSsrP7MrNrYenrYegLAxaKhxsahov47nIeIm5uIhwACAGQAAAJHArIADgAYAAABHg
1172
+ EVFAYHBisBESMRMzITNjQnJisBETMyAZRUX2VOHzuAVtY7GlxcGDWIiDUCrgtnVlVpCgT+5gKy/rU
1173
+ V1BUF/v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UADgAPAAAACwAQAAAAAAAAAAAAAAAAAAUAGAACAAIAAgAAAAIAGAAXAAAAGAAAABYAFgACABYAA
1303
+ gAWAAAAEQADAAoAFAAMAA0ABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASAAAAEgAGAAEAHgAkAC
1304
+ YAJwApACoALQAuAC8AMgAzADcAOAA5ADoAPAA9AEUASABOAE8AUgBTAFUAVwBZAFoAWwBcAF0AcwA
1305
+ AAAAAAQAAAADa3tfFAAAAANAan9kAAAAA4QodoQ==
1306
+ """
1307
+ )
1308
+ ),
1309
+ 10 if size is None else size,
1310
+ layout_engine=Layout.BASIC,
1311
+ )
1312
+ return load_default_imagefont()
.venv/lib/python3.12/site-packages/PIL/ImageMode.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
22
+ class ModeDescriptor(NamedTuple):
23
+ """Wrapper for mode strings."""
24
+
25
+ mode: str
26
+ bands: tuple[str, ...]
27
+ basemode: str
28
+ basetype: str
29
+ typestr: str
30
+
31
+ def __str__(self) -> str:
32
+ return self.mode
33
+
34
+
35
+ @lru_cache
36
+ def getmode(mode: str) -> ModeDescriptor:
37
+ """Gets a mode descriptor for the given mode."""
38
+ endian = "<" if sys.byteorder == "little" else ">"
39
+
40
+ modes = {
41
+ # core modes
42
+ # Bits need to be extended to bytes
43
+ "1": ("L", "L", ("1",), "|b1"),
44
+ "L": ("L", "L", ("L",), "|u1"),
45
+ "I": ("L", "I", ("I",), f"{endian}i4"),
46
+ "F": ("L", "F", ("F",), f"{endian}f4"),
47
+ "P": ("P", "L", ("P",), "|u1"),
48
+ "RGB": ("RGB", "L", ("R", "G", "B"), "|u1"),
49
+ "RGBX": ("RGB", "L", ("R", "G", "B", "X"), "|u1"),
50
+ "RGBA": ("RGB", "L", ("R", "G", "B", "A"), "|u1"),
51
+ "CMYK": ("RGB", "L", ("C", "M", "Y", "K"), "|u1"),
52
+ "YCbCr": ("RGB", "L", ("Y", "Cb", "Cr"), "|u1"),
53
+ # UNDONE - unsigned |u1i1i1
54
+ "LAB": ("RGB", "L", ("L", "A", "B"), "|u1"),
55
+ "HSV": ("RGB", "L", ("H", "S", "V"), "|u1"),
56
+ # extra experimental modes
57
+ "RGBa": ("RGB", "L", ("R", "G", "B", "a"), "|u1"),
58
+ "LA": ("L", "L", ("L", "A"), "|u1"),
59
+ "La": ("L", "L", ("L", "a"), "|u1"),
60
+ "PA": ("RGB", "L", ("P", "A"), "|u1"),
61
+ }
62
+ if mode in modes:
63
+ base_mode, base_type, bands, type_str = modes[mode]
64
+ return ModeDescriptor(mode, bands, base_mode, base_type, type_str)
65
+
66
+ mapping_modes = {
67
+ # I;16 == I;16L, and I;32 == I;32L
68
+ "I;16": "<u2",
69
+ "I;16S": "<i2",
70
+ "I;16L": "<u2",
71
+ "I;16LS": "<i2",
72
+ "I;16B": ">u2",
73
+ "I;16BS": ">i2",
74
+ "I;16N": f"{endian}u2",
75
+ "I;16NS": f"{endian}i2",
76
+ "I;32": "<u4",
77
+ "I;32B": ">u4",
78
+ "I;32L": "<u4",
79
+ "I;32S": "<i4",
80
+ "I;32BS": ">i4",
81
+ "I;32LS": "<i4",
82
+ }
83
+
84
+ type_str = mapping_modes[mode]
85
+ return ModeDescriptor(mode, ("I",), "L", "L", type_str)
.venv/lib/python3.12/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
.venv/lib/python3.12/site-packages/PIL/ImageOps.py ADDED
@@ -0,0 +1,746 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ mode = image.palette.mode
503
+ palette = ImagePalette.ImagePalette(mode, image.getpalette(mode))
504
+ if isinstance(color, tuple) and (len(color) == 3 or len(color) == 4):
505
+ color = palette.getcolor(color)
506
+ else:
507
+ palette = None
508
+ out = Image.new(image.mode, (width, height), color)
509
+ if palette:
510
+ out.putpalette(palette.palette, mode)
511
+ out.paste(image, (left, top))
512
+ return out
513
+
514
+
515
+ def fit(
516
+ image: Image.Image,
517
+ size: tuple[int, int],
518
+ method: int = Image.Resampling.BICUBIC,
519
+ bleed: float = 0.0,
520
+ centering: tuple[float, float] = (0.5, 0.5),
521
+ ) -> Image.Image:
522
+ """
523
+ Returns a resized and cropped version of the image, cropped to the
524
+ requested aspect ratio and size.
525
+
526
+ This function was contributed by Kevin Cazabon.
527
+
528
+ :param image: The image to resize and crop.
529
+ :param size: The requested output size in pixels, given as a
530
+ (width, height) tuple.
531
+ :param method: Resampling method to use. Default is
532
+ :py:attr:`~PIL.Image.Resampling.BICUBIC`.
533
+ See :ref:`concept-filters`.
534
+ :param bleed: Remove a border around the outside of the image from all
535
+ four edges. The value is a decimal percentage (use 0.01 for
536
+ one percent). The default value is 0 (no border).
537
+ Cannot be greater than or equal to 0.5.
538
+ :param centering: Control the cropping position. Use (0.5, 0.5) for
539
+ center cropping (e.g. if cropping the width, take 50% off
540
+ of the left side, and therefore 50% off the right side).
541
+ (0.0, 0.0) will crop from the top left corner (i.e. if
542
+ cropping the width, take all of the crop off of the right
543
+ side, and if cropping the height, take all of it off the
544
+ bottom). (1.0, 0.0) will crop from the bottom left
545
+ corner, etc. (i.e. if cropping the width, take all of the
546
+ crop off the left side, and if cropping the height take
547
+ none from the top, and therefore all off the bottom).
548
+ :return: An image.
549
+ """
550
+
551
+ # by Kevin Cazabon, Feb 17/2000
552
+ # kevin@cazabon.com
553
+ # https://www.cazabon.com
554
+
555
+ centering_x, centering_y = centering
556
+
557
+ if not 0.0 <= centering_x <= 1.0:
558
+ centering_x = 0.5
559
+ if not 0.0 <= centering_y <= 1.0:
560
+ centering_y = 0.5
561
+
562
+ if not 0.0 <= bleed < 0.5:
563
+ bleed = 0.0
564
+
565
+ # calculate the area to use for resizing and cropping, subtracting
566
+ # the 'bleed' around the edges
567
+
568
+ # number of pixels to trim off on Top and Bottom, Left and Right
569
+ bleed_pixels = (bleed * image.size[0], bleed * image.size[1])
570
+
571
+ live_size = (
572
+ image.size[0] - bleed_pixels[0] * 2,
573
+ image.size[1] - bleed_pixels[1] * 2,
574
+ )
575
+
576
+ # calculate the aspect ratio of the live_size
577
+ live_size_ratio = live_size[0] / live_size[1]
578
+
579
+ # calculate the aspect ratio of the output image
580
+ output_ratio = size[0] / size[1]
581
+
582
+ # figure out if the sides or top/bottom will be cropped off
583
+ if live_size_ratio == output_ratio:
584
+ # live_size is already the needed ratio
585
+ crop_width = live_size[0]
586
+ crop_height = live_size[1]
587
+ elif live_size_ratio >= output_ratio:
588
+ # live_size is wider than what's needed, crop the sides
589
+ crop_width = output_ratio * live_size[1]
590
+ crop_height = live_size[1]
591
+ else:
592
+ # live_size is taller than what's needed, crop the top and bottom
593
+ crop_width = live_size[0]
594
+ crop_height = live_size[0] / output_ratio
595
+
596
+ # make the crop
597
+ crop_left = bleed_pixels[0] + (live_size[0] - crop_width) * centering_x
598
+ crop_top = bleed_pixels[1] + (live_size[1] - crop_height) * centering_y
599
+
600
+ crop = (crop_left, crop_top, crop_left + crop_width, crop_top + crop_height)
601
+
602
+ # resize the image and return it
603
+ return image.resize(size, method, box=crop)
604
+
605
+
606
+ def flip(image: Image.Image) -> Image.Image:
607
+ """
608
+ Flip the image vertically (top to bottom).
609
+
610
+ :param image: The image to flip.
611
+ :return: An image.
612
+ """
613
+ return image.transpose(Image.Transpose.FLIP_TOP_BOTTOM)
614
+
615
+
616
+ def grayscale(image: Image.Image) -> Image.Image:
617
+ """
618
+ Convert the image to grayscale.
619
+
620
+ :param image: The image to convert.
621
+ :return: An image.
622
+ """
623
+ return image.convert("L")
624
+
625
+
626
+ def invert(image: Image.Image) -> Image.Image:
627
+ """
628
+ Invert (negate) the image.
629
+
630
+ :param image: The image to invert.
631
+ :return: An image.
632
+ """
633
+ lut = list(range(255, -1, -1))
634
+ return image.point(lut) if image.mode == "1" else _lut(image, lut)
635
+
636
+
637
+ def mirror(image: Image.Image) -> Image.Image:
638
+ """
639
+ Flip image horizontally (left to right).
640
+
641
+ :param image: The image to mirror.
642
+ :return: An image.
643
+ """
644
+ return image.transpose(Image.Transpose.FLIP_LEFT_RIGHT)
645
+
646
+
647
+ def posterize(image: Image.Image, bits: int) -> Image.Image:
648
+ """
649
+ Reduce the number of bits for each color channel.
650
+
651
+ :param image: The image to posterize.
652
+ :param bits: The number of bits to keep for each channel (1-8).
653
+ :return: An image.
654
+ """
655
+ mask = ~(2 ** (8 - bits) - 1)
656
+ lut = [i & mask for i in range(256)]
657
+ return _lut(image, lut)
658
+
659
+
660
+ def solarize(image: Image.Image, threshold: int = 128) -> Image.Image:
661
+ """
662
+ Invert all pixel values above a threshold.
663
+
664
+ :param image: The image to solarize.
665
+ :param threshold: All pixels above this grayscale level are inverted.
666
+ :return: An image.
667
+ """
668
+ lut = []
669
+ for i in range(256):
670
+ if i < threshold:
671
+ lut.append(i)
672
+ else:
673
+ lut.append(255 - i)
674
+ return _lut(image, lut)
675
+
676
+
677
+ @overload
678
+ def exif_transpose(image: Image.Image, *, in_place: Literal[True]) -> None: ...
679
+
680
+
681
+ @overload
682
+ def exif_transpose(
683
+ image: Image.Image, *, in_place: Literal[False] = False
684
+ ) -> Image.Image: ...
685
+
686
+
687
+ def exif_transpose(image: Image.Image, *, in_place: bool = False) -> Image.Image | None:
688
+ """
689
+ If an image has an EXIF Orientation tag, other than 1, transpose the image
690
+ accordingly, and remove the orientation data.
691
+
692
+ :param image: The image to transpose.
693
+ :param in_place: Boolean. Keyword-only argument.
694
+ If ``True``, the original image is modified in-place, and ``None`` is returned.
695
+ If ``False`` (default), a new :py:class:`~PIL.Image.Image` object is returned
696
+ with the transposition applied. If there is no transposition, a copy of the
697
+ image will be returned.
698
+ """
699
+ image.load()
700
+ image_exif = image.getexif()
701
+ orientation = image_exif.get(ExifTags.Base.Orientation, 1)
702
+ method = {
703
+ 2: Image.Transpose.FLIP_LEFT_RIGHT,
704
+ 3: Image.Transpose.ROTATE_180,
705
+ 4: Image.Transpose.FLIP_TOP_BOTTOM,
706
+ 5: Image.Transpose.TRANSPOSE,
707
+ 6: Image.Transpose.ROTATE_270,
708
+ 7: Image.Transpose.TRANSVERSE,
709
+ 8: Image.Transpose.ROTATE_90,
710
+ }.get(orientation)
711
+ if method is not None:
712
+ if in_place:
713
+ image.im = image.im.transpose(method)
714
+ image._size = image.im.size
715
+ else:
716
+ transposed_image = image.transpose(method)
717
+ exif_image = image if in_place else transposed_image
718
+
719
+ exif = exif_image.getexif()
720
+ if ExifTags.Base.Orientation in exif:
721
+ del exif[ExifTags.Base.Orientation]
722
+ if "exif" in exif_image.info:
723
+ exif_image.info["exif"] = exif.tobytes()
724
+ elif "Raw profile type exif" in exif_image.info:
725
+ exif_image.info["Raw profile type exif"] = exif.tobytes().hex()
726
+ for key in ("XML:com.adobe.xmp", "xmp"):
727
+ if key in exif_image.info:
728
+ for pattern in (
729
+ r'tiff:Orientation="([0-9])"',
730
+ r"<tiff:Orientation>([0-9])</tiff:Orientation>",
731
+ ):
732
+ value = exif_image.info[key]
733
+ if isinstance(value, str):
734
+ value = re.sub(pattern, "", value)
735
+ elif isinstance(value, tuple):
736
+ value = tuple(
737
+ re.sub(pattern.encode(), b"", v) for v in value
738
+ )
739
+ else:
740
+ value = re.sub(pattern.encode(), b"", value)
741
+ exif_image.info[key] = value
742
+ if not in_place:
743
+ return transposed_image
744
+ elif not in_place:
745
+ return image.copy()
746
+ return None
.venv/lib/python3.12/site-packages/PIL/ImageQt.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
23
+ from . import Image
24
+ from ._util import is_path
25
+
26
+ TYPE_CHECKING = False
27
+ if TYPE_CHECKING:
28
+ from collections.abc import Callable
29
+ from typing import Any
30
+
31
+ from . import ImageFile
32
+
33
+ QBuffer: type
34
+
35
+ qt_version: str | None
36
+ qt_versions = [
37
+ ["6", "PyQt6"],
38
+ ["side6", "PySide6"],
39
+ ]
40
+
41
+ # If a version has already been imported, attempt it first
42
+ qt_versions.sort(key=lambda version: version[1] in sys.modules, reverse=True)
43
+ for version, qt_module in qt_versions:
44
+ try:
45
+ qRgba: Callable[[int, int, int, int], int]
46
+ if qt_module == "PyQt6":
47
+ from PyQt6.QtCore import QBuffer, QByteArray, QIODevice
48
+ from PyQt6.QtGui import QImage, QPixmap, qRgba
49
+ elif qt_module == "PySide6":
50
+ from PySide6.QtCore import ( # type: ignore[assignment]
51
+ QBuffer,
52
+ QByteArray,
53
+ QIODevice,
54
+ )
55
+ from PySide6.QtGui import QImage, QPixmap, qRgba # type: ignore[assignment]
56
+ except (ImportError, RuntimeError):
57
+ continue
58
+ qt_is_installed = True
59
+ qt_version = version
60
+ break
61
+ else:
62
+ qt_is_installed = False
63
+ qt_version = None
64
+
65
+
66
+ def rgb(r: int, g: int, b: int, a: int = 255) -> int:
67
+ """(Internal) Turns an RGB color into a Qt compatible color integer."""
68
+ # use qRgb to pack the colors, and then turn the resulting long
69
+ # into a negative integer with the same bitpattern.
70
+ return qRgba(r, g, b, a) & 0xFFFFFFFF
71
+
72
+
73
+ def fromqimage(im: QImage | QPixmap) -> ImageFile.ImageFile:
74
+ """
75
+ :param im: QImage or PIL ImageQt object
76
+ """
77
+ buffer = QBuffer()
78
+ qt_openmode: object
79
+ if qt_version == "6":
80
+ try:
81
+ qt_openmode = getattr(QIODevice, "OpenModeFlag")
82
+ except AttributeError:
83
+ qt_openmode = getattr(QIODevice, "OpenMode")
84
+ else:
85
+ qt_openmode = QIODevice
86
+ buffer.open(getattr(qt_openmode, "ReadWrite"))
87
+ # preserve alpha channel with png
88
+ # otherwise ppm is more friendly with Image.open
89
+ if im.hasAlphaChannel():
90
+ im.save(buffer, "png")
91
+ else:
92
+ im.save(buffer, "ppm")
93
+
94
+ b = BytesIO()
95
+ b.write(buffer.data())
96
+ buffer.close()
97
+ b.seek(0)
98
+
99
+ return Image.open(b)
100
+
101
+
102
+ def fromqpixmap(im: QPixmap) -> ImageFile.ImageFile:
103
+ return fromqimage(im)
104
+
105
+
106
+ def align8to32(bytes: bytes, width: int, mode: str) -> bytes:
107
+ """
108
+ converts each scanline of data from 8 bit to 32 bit aligned
109
+ """
110
+
111
+ bits_per_pixel = {"1": 1, "L": 8, "P": 8, "I;16": 16}[mode]
112
+
113
+ # calculate bytes per line and the extra padding if needed
114
+ bits_per_line = bits_per_pixel * width
115
+ full_bytes_per_line, remaining_bits_per_line = divmod(bits_per_line, 8)
116
+ bytes_per_line = full_bytes_per_line + (1 if remaining_bits_per_line else 0)
117
+
118
+ extra_padding = -bytes_per_line % 4
119
+
120
+ # already 32 bit aligned by luck
121
+ if not extra_padding:
122
+ return bytes
123
+
124
+ new_data = [
125
+ bytes[i * bytes_per_line : (i + 1) * bytes_per_line] + b"\x00" * extra_padding
126
+ for i in range(len(bytes) // bytes_per_line)
127
+ ]
128
+
129
+ return b"".join(new_data)
130
+
131
+
132
+ def _toqclass_helper(im: Image.Image | str | QByteArray) -> dict[str, Any]:
133
+ data = None
134
+ colortable = None
135
+ exclusive_fp = False
136
+
137
+ # handle filename, if given instead of image name
138
+ if hasattr(im, "toUtf8"):
139
+ # FIXME - is this really the best way to do this?
140
+ im = str(im.toUtf8(), "utf-8")
141
+ if is_path(im):
142
+ im = Image.open(im)
143
+ exclusive_fp = True
144
+ assert isinstance(im, Image.Image)
145
+
146
+ qt_format = getattr(QImage, "Format") if qt_version == "6" else QImage
147
+ if im.mode == "1":
148
+ format = getattr(qt_format, "Format_Mono")
149
+ elif im.mode == "L":
150
+ format = getattr(qt_format, "Format_Indexed8")
151
+ colortable = [rgb(i, i, i) for i in range(256)]
152
+ elif im.mode == "P":
153
+ format = getattr(qt_format, "Format_Indexed8")
154
+ palette = im.getpalette()
155
+ assert palette is not None
156
+ colortable = [rgb(*palette[i : i + 3]) for i in range(0, len(palette), 3)]
157
+ elif im.mode == "RGB":
158
+ # Populate the 4th channel with 255
159
+ im = im.convert("RGBA")
160
+
161
+ data = im.tobytes("raw", "BGRA")
162
+ format = getattr(qt_format, "Format_RGB32")
163
+ elif im.mode == "RGBA":
164
+ data = im.tobytes("raw", "BGRA")
165
+ format = getattr(qt_format, "Format_ARGB32")
166
+ elif im.mode == "I;16":
167
+ im = im.point(lambda i: i * 256)
168
+
169
+ format = getattr(qt_format, "Format_Grayscale16")
170
+ else:
171
+ if exclusive_fp:
172
+ im.close()
173
+ msg = f"unsupported image mode {repr(im.mode)}"
174
+ raise ValueError(msg)
175
+
176
+ size = im.size
177
+ __data = data or align8to32(im.tobytes(), size[0], im.mode)
178
+ if exclusive_fp:
179
+ im.close()
180
+ return {"data": __data, "size": size, "format": format, "colortable": colortable}
181
+
182
+
183
+ if qt_is_installed:
184
+
185
+ class ImageQt(QImage):
186
+ def __init__(self, im: Image.Image | str | QByteArray) -> None:
187
+ """
188
+ An PIL image wrapper for Qt. This is a subclass of PyQt's QImage
189
+ class.
190
+
191
+ :param im: A PIL Image object, or a file name (given either as
192
+ Python string or a PyQt string object).
193
+ """
194
+ im_data = _toqclass_helper(im)
195
+ # must keep a reference, or Qt will crash!
196
+ # All QImage constructors that take data operate on an existing
197
+ # buffer, so this buffer has to hang on for the life of the image.
198
+ # Fixes https://github.com/python-pillow/Pillow/issues/1370
199
+ self.__data = im_data["data"]
200
+ super().__init__(
201
+ self.__data,
202
+ im_data["size"][0],
203
+ im_data["size"][1],
204
+ im_data["format"],
205
+ )
206
+ if im_data["colortable"]:
207
+ self.setColorTable(im_data["colortable"])
208
+
209
+
210
+ def toqimage(im: Image.Image | str | QByteArray) -> ImageQt:
211
+ return ImageQt(im)
212
+
213
+
214
+ def toqpixmap(im: Image.Image | str | QByteArray) -> QPixmap:
215
+ qimage = toqimage(im)
216
+ pixmap = getattr(QPixmap, "fromImage")(qimage)
217
+ if qt_version == "6":
218
+ pixmap.detach()
219
+ return pixmap
.venv/lib/python3.12/site-packages/PIL/ImageSequence.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 . import Image
20
+
21
+ TYPE_CHECKING = False
22
+ if TYPE_CHECKING:
23
+ from collections.abc import Callable
24
+
25
+
26
+ class Iterator:
27
+ """
28
+ This class implements an iterator object that can be used to loop
29
+ over an image sequence.
30
+
31
+ You can use the ``[]`` operator to access elements by index. This operator
32
+ will raise an :py:exc:`IndexError` if you try to access a nonexistent
33
+ frame.
34
+
35
+ :param im: An image object.
36
+ """
37
+
38
+ def __init__(self, im: Image.Image) -> None:
39
+ if not hasattr(im, "seek"):
40
+ msg = "im must have seek method"
41
+ raise AttributeError(msg)
42
+ self.im = im
43
+ self.position = getattr(self.im, "_min_frame", 0)
44
+
45
+ def __getitem__(self, ix: int) -> Image.Image:
46
+ try:
47
+ self.im.seek(ix)
48
+ return self.im
49
+ except EOFError as e:
50
+ msg = "end of sequence"
51
+ raise IndexError(msg) from e
52
+
53
+ def __iter__(self) -> Iterator:
54
+ return self
55
+
56
+ def __next__(self) -> Image.Image:
57
+ try:
58
+ self.im.seek(self.position)
59
+ self.position += 1
60
+ return self.im
61
+ except EOFError as e:
62
+ msg = "end of sequence"
63
+ raise StopIteration(msg) from e
64
+
65
+
66
+ def all_frames(
67
+ im: Image.Image | list[Image.Image],
68
+ func: Callable[[Image.Image], Image.Image] | None = None,
69
+ ) -> list[Image.Image]:
70
+ """
71
+ Applies a given function to all frames in an image or a list of images.
72
+ The frames are returned as a list of separate images.
73
+
74
+ :param im: An image, or a list of images.
75
+ :param func: The function to apply to all of the image frames.
76
+ :returns: A list of images.
77
+ """
78
+ if not isinstance(im, list):
79
+ im = [im]
80
+
81
+ ims = []
82
+ for imSequence in im:
83
+ current = imSequence.tell()
84
+
85
+ ims += [im_frame.copy() for im_frame in Iterator(imSequence)]
86
+
87
+ imSequence.seek(current)
88
+ return [func(im) for im in ims] if func else ims
.venv/lib/python3.12/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:]))