a1o commited on
Commit
f937a2b
·
verified ·
1 Parent(s): 5bf882e

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +7 -0
  2. .venv/.gitignore +1 -0
  3. .venv/.lock +0 -0
  4. .venv/CACHEDIR.TAG +1 -0
  5. .venv/bin/activate +130 -0
  6. .venv/bin/activate.bat +71 -0
  7. .venv/bin/activate.csh +76 -0
  8. .venv/bin/activate.fish +124 -0
  9. .venv/bin/activate.nu +117 -0
  10. .venv/bin/activate.ps1 +82 -0
  11. .venv/bin/activate_this.py +59 -0
  12. .venv/bin/deactivate.bat +39 -0
  13. .venv/bin/f2py +10 -0
  14. .venv/bin/fonttools +10 -0
  15. .venv/bin/hf +10 -0
  16. .venv/bin/httpx +10 -0
  17. .venv/bin/huggingface-cli +10 -0
  18. .venv/bin/idna +10 -0
  19. .venv/bin/natsort +10 -0
  20. .venv/bin/numba +8 -0
  21. .venv/bin/numpy-config +10 -0
  22. .venv/bin/pip +10 -0
  23. .venv/bin/pip3 +10 -0
  24. .venv/bin/pip3.11 +10 -0
  25. .venv/bin/pydoc.bat +22 -0
  26. .venv/bin/pyftmerge +10 -0
  27. .venv/bin/pyftsubset +10 -0
  28. .venv/bin/python +0 -0
  29. .venv/bin/python3 +0 -0
  30. .venv/bin/python3.11 +0 -0
  31. .venv/bin/scanpy +10 -0
  32. .venv/bin/session-info +10 -0
  33. .venv/bin/session-info2 +10 -0
  34. .venv/bin/tiny-agents +10 -0
  35. .venv/bin/tqdm +10 -0
  36. .venv/bin/ttx +10 -0
  37. .venv/bin/zarr +10 -0
  38. .venv/lib/python3.11/site-packages/PIL/AvifImagePlugin.py +295 -0
  39. .venv/lib/python3.11/site-packages/PIL/BdfFontFile.py +124 -0
  40. .venv/lib/python3.11/site-packages/PIL/BlpImagePlugin.py +498 -0
  41. .venv/lib/python3.11/site-packages/PIL/BmpImagePlugin.py +514 -0
  42. .venv/lib/python3.11/site-packages/PIL/BufrStubImagePlugin.py +72 -0
  43. .venv/lib/python3.11/site-packages/PIL/ContainerIO.py +173 -0
  44. .venv/lib/python3.11/site-packages/PIL/CurImagePlugin.py +103 -0
  45. .venv/lib/python3.11/site-packages/PIL/DcxImagePlugin.py +84 -0
  46. .venv/lib/python3.11/site-packages/PIL/DdsImagePlugin.py +632 -0
  47. .venv/lib/python3.11/site-packages/PIL/EpsImagePlugin.py +484 -0
  48. .venv/lib/python3.11/site-packages/PIL/ExifTags.py +384 -0
  49. .venv/lib/python3.11/site-packages/PIL/FitsImagePlugin.py +153 -0
  50. .venv/lib/python3.11/site-packages/PIL/FliImagePlugin.py +184 -0
.gitattributes CHANGED
@@ -33,3 +33,10 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ .venv/lib/python3.11/site-packages/PIL/_imaging.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
37
+ .venv/lib/python3.11/site-packages/PIL/_imagingcms.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
38
+ .venv/lib/python3.11/site-packages/PIL/_imagingft.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
39
+ .venv/lib/python3.11/site-packages/PIL/_imagingmath.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
40
+ .venv/lib/python3.11/site-packages/PIL/_webp.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
41
+ .venv/lib/python3.11/site-packages/__pycache__/typing_extensions.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
42
+ .venv/lib/python3.11/site-packages/anndata/_core/__pycache__/merge.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
.venv/.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ *
.venv/.lock ADDED
File without changes
.venv/CACHEDIR.TAG ADDED
@@ -0,0 +1 @@
 
 
1
+ Signature: 8a477f597d28d172789f06886806bc55
.venv/bin/activate ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2020-202x The virtualenv developers
2
+ #
3
+ # Permission is hereby granted, free of charge, to any person obtaining
4
+ # a copy of this software and associated documentation files (the
5
+ # "Software"), to deal in the Software without restriction, including
6
+ # without limitation the rights to use, copy, modify, merge, publish,
7
+ # distribute, sublicense, and/or sell copies of the Software, and to
8
+ # permit persons to whom the Software is furnished to do so, subject to
9
+ # the following conditions:
10
+ #
11
+ # The above copyright notice and this permission notice shall be
12
+ # included in all copies or substantial portions of the Software.
13
+ #
14
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
+
22
+ # This file must be used with "source bin/activate" *from bash*
23
+ # you cannot run it directly
24
+
25
+ if ! [ -z "${SCRIPT_PATH+_}" ] ; then
26
+ _OLD_SCRIPT_PATH="$SCRIPT_PATH"
27
+ fi
28
+
29
+ # Get script path (only used if environment is relocatable).
30
+ if [ -n "${BASH_VERSION:+x}" ] ; then
31
+ SCRIPT_PATH="${BASH_SOURCE[0]}"
32
+ if [ "$SCRIPT_PATH" = "$0" ]; then
33
+ # Only bash has a reasonably robust check for source'dness.
34
+ echo "You must source this script: \$ source $0" >&2
35
+ exit 33
36
+ fi
37
+ elif [ -n "${ZSH_VERSION:+x}" ] ; then
38
+ SCRIPT_PATH="${(%):-%x}"
39
+ elif [ -n "${KSH_VERSION:+x}" ] ; then
40
+ SCRIPT_PATH="${.sh.file}"
41
+ fi
42
+
43
+ deactivate () {
44
+ unset -f pydoc >/dev/null 2>&1 || true
45
+
46
+ # reset old environment variables
47
+ # ! [ -z ${VAR+_} ] returns true if VAR is declared at all
48
+ if ! [ -z "${_OLD_VIRTUAL_PATH:+_}" ] ; then
49
+ PATH="$_OLD_VIRTUAL_PATH"
50
+ export PATH
51
+ unset _OLD_VIRTUAL_PATH
52
+ fi
53
+ if ! [ -z "${_OLD_VIRTUAL_PYTHONHOME+_}" ] ; then
54
+ PYTHONHOME="$_OLD_VIRTUAL_PYTHONHOME"
55
+ export PYTHONHOME
56
+ unset _OLD_VIRTUAL_PYTHONHOME
57
+ fi
58
+
59
+ # The hash command must be called to get it to forget past
60
+ # commands. Without forgetting past commands the $PATH changes
61
+ # we made may not be respected
62
+ hash -r 2>/dev/null
63
+
64
+ if ! [ -z "${_OLD_VIRTUAL_PS1+_}" ] ; then
65
+ PS1="$_OLD_VIRTUAL_PS1"
66
+ export PS1
67
+ unset _OLD_VIRTUAL_PS1
68
+ fi
69
+
70
+ unset VIRTUAL_ENV
71
+ unset VIRTUAL_ENV_PROMPT
72
+ if [ ! "${1-}" = "nondestructive" ] ; then
73
+ # Self destruct!
74
+ unset -f deactivate
75
+ fi
76
+ }
77
+
78
+ # unset irrelevant variables
79
+ deactivate nondestructive
80
+
81
+ VIRTUAL_ENV='/gpfs/projects/p32222/aTester/state_parse_repro/.venv'
82
+ if ([ "$OSTYPE" = "cygwin" ] || [ "$OSTYPE" = "msys" ]) && $(command -v cygpath &> /dev/null) ; then
83
+ VIRTUAL_ENV=$(cygpath -u "$VIRTUAL_ENV")
84
+ fi
85
+ export VIRTUAL_ENV
86
+
87
+ # Unset the `SCRIPT_PATH` variable, now that the `VIRTUAL_ENV` variable
88
+ # has been set. This is important for relocatable environments.
89
+ if ! [ -z "${_OLD_SCRIPT_PATH+_}" ] ; then
90
+ SCRIPT_PATH="$_OLD_SCRIPT_PATH"
91
+ export SCRIPT_PATH
92
+ unset _OLD_SCRIPT_PATH
93
+ else
94
+ unset SCRIPT_PATH
95
+ fi
96
+
97
+ _OLD_VIRTUAL_PATH="$PATH"
98
+ PATH="$VIRTUAL_ENV/bin:$PATH"
99
+ export PATH
100
+
101
+ if [ "xstate_parse_repro" != x ] ; then
102
+ VIRTUAL_ENV_PROMPT="state_parse_repro"
103
+ else
104
+ VIRTUAL_ENV_PROMPT=$(basename "$VIRTUAL_ENV")
105
+ fi
106
+ export VIRTUAL_ENV_PROMPT
107
+
108
+ # unset PYTHONHOME if set
109
+ if ! [ -z "${PYTHONHOME+_}" ] ; then
110
+ _OLD_VIRTUAL_PYTHONHOME="$PYTHONHOME"
111
+ unset PYTHONHOME
112
+ fi
113
+
114
+ if [ -z "${VIRTUAL_ENV_DISABLE_PROMPT-}" ] ; then
115
+ _OLD_VIRTUAL_PS1="${PS1-}"
116
+ PS1="(${VIRTUAL_ENV_PROMPT}) ${PS1-}"
117
+ export PS1
118
+ fi
119
+
120
+ # Make sure to unalias pydoc if it's already there
121
+ alias pydoc 2>/dev/null >/dev/null && unalias pydoc || true
122
+
123
+ pydoc () {
124
+ python -m pydoc "$@"
125
+ }
126
+
127
+ # The hash command must be called to get it to forget past
128
+ # commands. Without forgetting past commands the $PATH changes
129
+ # we made may not be respected
130
+ hash -r 2>/dev/null
.venv/bin/activate.bat ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @REM Copyright (c) 2020-202x The virtualenv developers
2
+ @REM
3
+ @REM Permission is hereby granted, free of charge, to any person obtaining
4
+ @REM a copy of this software and associated documentation files (the
5
+ @REM "Software"), to deal in the Software without restriction, including
6
+ @REM without limitation the rights to use, copy, modify, merge, publish,
7
+ @REM distribute, sublicense, and/or sell copies of the Software, and to
8
+ @REM permit persons to whom the Software is furnished to do so, subject to
9
+ @REM the following conditions:
10
+ @REM
11
+ @REM The above copyright notice and this permission notice shall be
12
+ @REM included in all copies or substantial portions of the Software.
13
+ @REM
14
+ @REM THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ @REM EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ @REM MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ @REM NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ @REM LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ @REM OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ @REM WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
+
22
+ @REM This file is UTF-8 encoded, so we need to update the current code page while executing it
23
+ @for /f "tokens=2 delims=:." %%a in ('"%SystemRoot%\System32\chcp.com"') do @set _OLD_CODEPAGE=%%a
24
+ @if defined _OLD_CODEPAGE (
25
+ @"%SystemRoot%\System32\chcp.com" 65001 > nul
26
+ )
27
+
28
+ @for %%i in ("/gpfs/projects/p32222/aTester/state_parse_repro/.venv") do @set "VIRTUAL_ENV=%%~fi"
29
+
30
+ @set "VIRTUAL_ENV_PROMPT=state_parse_repro"
31
+ @if NOT DEFINED VIRTUAL_ENV_PROMPT (
32
+ @for %%d in ("%VIRTUAL_ENV%") do @set "VIRTUAL_ENV_PROMPT=%%~nxd"
33
+ )
34
+
35
+ @if defined _OLD_VIRTUAL_PROMPT (
36
+ @set "PROMPT=%_OLD_VIRTUAL_PROMPT%"
37
+ ) else (
38
+ @if not defined PROMPT (
39
+ @set "PROMPT=$P$G"
40
+ )
41
+ @if not defined VIRTUAL_ENV_DISABLE_PROMPT (
42
+ @set "_OLD_VIRTUAL_PROMPT=%PROMPT%"
43
+ )
44
+ )
45
+ @if not defined VIRTUAL_ENV_DISABLE_PROMPT (
46
+ @set "PROMPT=(%VIRTUAL_ENV_PROMPT%) %PROMPT%"
47
+ )
48
+
49
+ @REM Don't use () to avoid problems with them in %PATH%
50
+ @if defined _OLD_VIRTUAL_PYTHONHOME @goto ENDIFVHOME
51
+ @set "_OLD_VIRTUAL_PYTHONHOME=%PYTHONHOME%"
52
+ :ENDIFVHOME
53
+
54
+ @set PYTHONHOME=
55
+
56
+ @REM if defined _OLD_VIRTUAL_PATH (
57
+ @if not defined _OLD_VIRTUAL_PATH @goto ENDIFVPATH1
58
+ @set "PATH=%_OLD_VIRTUAL_PATH%"
59
+ :ENDIFVPATH1
60
+ @REM ) else (
61
+ @if defined _OLD_VIRTUAL_PATH @goto ENDIFVPATH2
62
+ @set "_OLD_VIRTUAL_PATH=%PATH%"
63
+ :ENDIFVPATH2
64
+
65
+ @set "PATH=%VIRTUAL_ENV%\bin;%PATH%"
66
+
67
+ :END
68
+ @if defined _OLD_CODEPAGE (
69
+ @"%SystemRoot%\System32\chcp.com" %_OLD_CODEPAGE% > nul
70
+ @set _OLD_CODEPAGE=
71
+ )
.venv/bin/activate.csh ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2020-202x The virtualenv developers
2
+ #
3
+ # Permission is hereby granted, free of charge, to any person obtaining
4
+ # a copy of this software and associated documentation files (the
5
+ # "Software"), to deal in the Software without restriction, including
6
+ # without limitation the rights to use, copy, modify, merge, publish,
7
+ # distribute, sublicense, and/or sell copies of the Software, and to
8
+ # permit persons to whom the Software is furnished to do so, subject to
9
+ # the following conditions:
10
+ #
11
+ # The above copyright notice and this permission notice shall be
12
+ # included in all copies or substantial portions of the Software.
13
+ #
14
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
+
22
+ # This file must be used with "source bin/activate.csh" *from csh*.
23
+ # You cannot run it directly.
24
+ # Created by Davide Di Blasi <davidedb@gmail.com>.
25
+
26
+ set newline='\
27
+ '
28
+
29
+ alias deactivate 'test $?_OLD_VIRTUAL_PATH != 0 && setenv PATH "$_OLD_VIRTUAL_PATH:q" && unset _OLD_VIRTUAL_PATH; rehash; test $?_OLD_VIRTUAL_PROMPT != 0 && set prompt="$_OLD_VIRTUAL_PROMPT:q" && unset _OLD_VIRTUAL_PROMPT; unsetenv VIRTUAL_ENV; unsetenv VIRTUAL_ENV_PROMPT; test "\!:*" != "nondestructive" && unalias deactivate && unalias pydoc'
30
+
31
+ # Unset irrelevant variables.
32
+ deactivate nondestructive
33
+
34
+ setenv VIRTUAL_ENV '/gpfs/projects/p32222/aTester/state_parse_repro/.venv'
35
+
36
+ set _OLD_VIRTUAL_PATH="$PATH:q"
37
+ setenv PATH "$VIRTUAL_ENV:q/bin:$PATH:q"
38
+
39
+
40
+
41
+ if ('state_parse_repro' != "") then
42
+ setenv VIRTUAL_ENV_PROMPT 'state_parse_repro'
43
+ else
44
+ setenv VIRTUAL_ENV_PROMPT "$VIRTUAL_ENV:t:q"
45
+ endif
46
+
47
+ if ( $?VIRTUAL_ENV_DISABLE_PROMPT ) then
48
+ if ( $VIRTUAL_ENV_DISABLE_PROMPT == "" ) then
49
+ set do_prompt = "1"
50
+ else
51
+ set do_prompt = "0"
52
+ endif
53
+ else
54
+ set do_prompt = "1"
55
+ endif
56
+
57
+ if ( $do_prompt == "1" ) then
58
+ # Could be in a non-interactive environment,
59
+ # in which case, $prompt is undefined and we wouldn't
60
+ # care about the prompt anyway.
61
+ if ( $?prompt ) then
62
+ set _OLD_VIRTUAL_PROMPT="$prompt:q"
63
+ if ( "$prompt:q" =~ *"$newline:q"* ) then
64
+ :
65
+ else
66
+ set prompt = '('"$VIRTUAL_ENV_PROMPT:q"') '"$prompt:q"
67
+ endif
68
+ endif
69
+ endif
70
+
71
+ unset env_name
72
+ unset do_prompt
73
+
74
+ alias pydoc python -m pydoc
75
+
76
+ rehash
.venv/bin/activate.fish ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2020-202x The virtualenv developers
2
+ #
3
+ # Permission is hereby granted, free of charge, to any person obtaining
4
+ # a copy of this software and associated documentation files (the
5
+ # "Software"), to deal in the Software without restriction, including
6
+ # without limitation the rights to use, copy, modify, merge, publish,
7
+ # distribute, sublicense, and/or sell copies of the Software, and to
8
+ # permit persons to whom the Software is furnished to do so, subject to
9
+ # the following conditions:
10
+ #
11
+ # The above copyright notice and this permission notice shall be
12
+ # included in all copies or substantial portions of the Software.
13
+ #
14
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
+
22
+ # This file must be used using `source bin/activate.fish` *within a running fish ( http://fishshell.com ) session*.
23
+ # Do not run it directly.
24
+
25
+ function _bashify_path -d "Converts a fish path to something bash can recognize"
26
+ set fishy_path $argv
27
+ set bashy_path $fishy_path[1]
28
+ for path_part in $fishy_path[2..-1]
29
+ set bashy_path "$bashy_path:$path_part"
30
+ end
31
+ echo $bashy_path
32
+ end
33
+
34
+ function _fishify_path -d "Converts a bash path to something fish can recognize"
35
+ echo $argv | tr ':' '\n'
36
+ end
37
+
38
+ function deactivate -d 'Exit virtualenv mode and return to the normal environment.'
39
+ # reset old environment variables
40
+ if test -n "$_OLD_VIRTUAL_PATH"
41
+ # https://github.com/fish-shell/fish-shell/issues/436 altered PATH handling
42
+ if test (echo $FISH_VERSION | head -c 1) -lt 3
43
+ set -gx PATH (_fishify_path "$_OLD_VIRTUAL_PATH")
44
+ else
45
+ set -gx PATH $_OLD_VIRTUAL_PATH
46
+ end
47
+ set -e _OLD_VIRTUAL_PATH
48
+ end
49
+
50
+ if test -n "$_OLD_VIRTUAL_PYTHONHOME"
51
+ set -gx PYTHONHOME "$_OLD_VIRTUAL_PYTHONHOME"
52
+ set -e _OLD_VIRTUAL_PYTHONHOME
53
+ end
54
+
55
+ if test -n "$_OLD_FISH_PROMPT_OVERRIDE"
56
+ and functions -q _old_fish_prompt
57
+ # Set an empty local `$fish_function_path` to allow the removal of `fish_prompt` using `functions -e`.
58
+ set -l fish_function_path
59
+
60
+ # Erase virtualenv's `fish_prompt` and restore the original.
61
+ functions -e fish_prompt
62
+ functions -c _old_fish_prompt fish_prompt
63
+ functions -e _old_fish_prompt
64
+ set -e _OLD_FISH_PROMPT_OVERRIDE
65
+ end
66
+
67
+ set -e VIRTUAL_ENV
68
+ set -e VIRTUAL_ENV_PROMPT
69
+
70
+ if test "$argv[1]" != 'nondestructive'
71
+ # Self-destruct!
72
+ functions -e pydoc
73
+ functions -e deactivate
74
+ functions -e _bashify_path
75
+ functions -e _fishify_path
76
+ end
77
+ end
78
+
79
+ # Unset irrelevant variables.
80
+ deactivate nondestructive
81
+
82
+ set -gx VIRTUAL_ENV '/gpfs/projects/p32222/aTester/state_parse_repro/.venv'
83
+
84
+ # https://github.com/fish-shell/fish-shell/issues/436 altered PATH handling
85
+ if test (echo $FISH_VERSION | head -c 1) -lt 3
86
+ set -gx _OLD_VIRTUAL_PATH (_bashify_path $PATH)
87
+ else
88
+ set -gx _OLD_VIRTUAL_PATH $PATH
89
+ end
90
+ set -gx PATH "$VIRTUAL_ENV"'/bin' $PATH
91
+
92
+ # Prompt override provided?
93
+ # If not, just use the environment name.
94
+ if test -n 'state_parse_repro'
95
+ set -gx VIRTUAL_ENV_PROMPT 'state_parse_repro'
96
+ else
97
+ set -gx VIRTUAL_ENV_PROMPT (basename "$VIRTUAL_ENV")
98
+ end
99
+
100
+ # Unset `$PYTHONHOME` if set.
101
+ if set -q PYTHONHOME
102
+ set -gx _OLD_VIRTUAL_PYTHONHOME $PYTHONHOME
103
+ set -e PYTHONHOME
104
+ end
105
+
106
+ function pydoc
107
+ python -m pydoc $argv
108
+ end
109
+
110
+ if test -z "$VIRTUAL_ENV_DISABLE_PROMPT"
111
+ # Copy the current `fish_prompt` function as `_old_fish_prompt`.
112
+ functions -c fish_prompt _old_fish_prompt
113
+
114
+ function fish_prompt
115
+ # Run the user's prompt first; it might depend on (pipe)status.
116
+ set -l prompt (_old_fish_prompt)
117
+
118
+ printf '(%s) ' $VIRTUAL_ENV_PROMPT
119
+
120
+ string join -- \n $prompt # handle multi-line prompts
121
+ end
122
+
123
+ set -gx _OLD_FISH_PROMPT_OVERRIDE "$VIRTUAL_ENV"
124
+ end
.venv/bin/activate.nu ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2020-202x The virtualenv developers
2
+ #
3
+ # Permission is hereby granted, free of charge, to any person obtaining
4
+ # a copy of this software and associated documentation files (the
5
+ # "Software"), to deal in the Software without restriction, including
6
+ # without limitation the rights to use, copy, modify, merge, publish,
7
+ # distribute, sublicense, and/or sell copies of the Software, and to
8
+ # permit persons to whom the Software is furnished to do so, subject to
9
+ # the following conditions:
10
+ #
11
+ # The above copyright notice and this permission notice shall be
12
+ # included in all copies or substantial portions of the Software.
13
+ #
14
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
+
22
+ # virtualenv activation module
23
+ # Activate with `overlay use activate.nu`
24
+ # Deactivate with `deactivate`, as usual
25
+ #
26
+ # To customize the overlay name, you can call `overlay use activate.nu as foo`,
27
+ # but then simply `deactivate` won't work because it is just an alias to hide
28
+ # the "activate" overlay. You'd need to call `overlay hide foo` manually.
29
+
30
+ export-env {
31
+ def is-string [x] {
32
+ ($x | describe) == 'string'
33
+ }
34
+
35
+ def has-env [...names] {
36
+ $names | each {|n|
37
+ $n in $env
38
+ } | all {|i| $i == true}
39
+ }
40
+
41
+ # Emulates a `test -z`, but better as it handles e.g 'false'
42
+ def is-env-true [name: string] {
43
+ if (has-env $name) {
44
+ # Try to parse 'true', '0', '1', and fail if not convertible
45
+ let parsed = (do -i { $env | get $name | into bool })
46
+ if ($parsed | describe) == 'bool' {
47
+ $parsed
48
+ } else {
49
+ not ($env | get -i $name | is-empty)
50
+ }
51
+ } else {
52
+ false
53
+ }
54
+ }
55
+
56
+ let virtual_env = '/gpfs/projects/p32222/aTester/state_parse_repro/.venv'
57
+ let bin = 'bin'
58
+
59
+ let is_windows = ($nu.os-info.family) == 'windows'
60
+ let path_name = (if (has-env 'Path') {
61
+ 'Path'
62
+ } else {
63
+ 'PATH'
64
+ }
65
+ )
66
+
67
+ let venv_path = ([$virtual_env $bin] | path join)
68
+ let new_path = ($env | get $path_name | prepend $venv_path)
69
+
70
+ # If there is no default prompt, then use the env name instead
71
+ let virtual_env_prompt = (if ('state_parse_repro' | is-empty) {
72
+ ($virtual_env | path basename)
73
+ } else {
74
+ 'state_parse_repro'
75
+ })
76
+
77
+ let new_env = {
78
+ $path_name : $new_path
79
+ VIRTUAL_ENV : $virtual_env
80
+ VIRTUAL_ENV_PROMPT : $virtual_env_prompt
81
+ }
82
+
83
+ let new_env = (if (is-env-true 'VIRTUAL_ENV_DISABLE_PROMPT') {
84
+ $new_env
85
+ } else {
86
+ # Creating the new prompt for the session
87
+ let virtual_prefix = $'(char lparen)($virtual_env_prompt)(char rparen) '
88
+
89
+ # Back up the old prompt builder
90
+ let old_prompt_command = (if (has-env 'PROMPT_COMMAND') {
91
+ $env.PROMPT_COMMAND
92
+ } else {
93
+ ''
94
+ })
95
+
96
+ let new_prompt = (if (has-env 'PROMPT_COMMAND') {
97
+ if 'closure' in ($old_prompt_command | describe) {
98
+ {|| $'($virtual_prefix)(do $old_prompt_command)' }
99
+ } else {
100
+ {|| $'($virtual_prefix)($old_prompt_command)' }
101
+ }
102
+ } else {
103
+ {|| $'($virtual_prefix)' }
104
+ })
105
+
106
+ $new_env | merge {
107
+ PROMPT_COMMAND : $new_prompt
108
+ VIRTUAL_PREFIX : $virtual_prefix
109
+ }
110
+ })
111
+
112
+ # Environment variables that will be loaded as the virtual env
113
+ load-env $new_env
114
+ }
115
+
116
+ export alias pydoc = python -m pydoc
117
+ export alias deactivate = overlay hide activate
.venv/bin/activate.ps1 ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2020-202x The virtualenv developers
2
+ #
3
+ # Permission is hereby granted, free of charge, to any person obtaining
4
+ # a copy of this software and associated documentation files (the
5
+ # "Software"), to deal in the Software without restriction, including
6
+ # without limitation the rights to use, copy, modify, merge, publish,
7
+ # distribute, sublicense, and/or sell copies of the Software, and to
8
+ # permit persons to whom the Software is furnished to do so, subject to
9
+ # the following conditions:
10
+ #
11
+ # The above copyright notice and this permission notice shall be
12
+ # included in all copies or substantial portions of the Software.
13
+ #
14
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
+
22
+ $script:THIS_PATH = $myinvocation.mycommand.path
23
+ $script:BASE_DIR = Split-Path (Resolve-Path "$THIS_PATH/..") -Parent
24
+
25
+ function global:deactivate([switch] $NonDestructive) {
26
+ if (Test-Path variable:_OLD_VIRTUAL_PATH) {
27
+ $env:PATH = $variable:_OLD_VIRTUAL_PATH
28
+ Remove-Variable "_OLD_VIRTUAL_PATH" -Scope global
29
+ }
30
+
31
+ if (Test-Path function:_old_virtual_prompt) {
32
+ $function:prompt = $function:_old_virtual_prompt
33
+ Remove-Item function:\_old_virtual_prompt
34
+ }
35
+
36
+ if ($env:VIRTUAL_ENV) {
37
+ Remove-Item env:VIRTUAL_ENV -ErrorAction SilentlyContinue
38
+ }
39
+
40
+ if ($env:VIRTUAL_ENV_PROMPT) {
41
+ Remove-Item env:VIRTUAL_ENV_PROMPT -ErrorAction SilentlyContinue
42
+ }
43
+
44
+ if (!$NonDestructive) {
45
+ # Self destruct!
46
+ Remove-Item function:deactivate
47
+ Remove-Item function:pydoc
48
+ }
49
+ }
50
+
51
+ function global:pydoc {
52
+ python -m pydoc $args
53
+ }
54
+
55
+ # unset irrelevant variables
56
+ deactivate -nondestructive
57
+
58
+ $VIRTUAL_ENV = $BASE_DIR
59
+ $env:VIRTUAL_ENV = $VIRTUAL_ENV
60
+
61
+ if ("state_parse_repro" -ne "") {
62
+ $env:VIRTUAL_ENV_PROMPT = "state_parse_repro"
63
+ }
64
+ else {
65
+ $env:VIRTUAL_ENV_PROMPT = $( Split-Path $env:VIRTUAL_ENV -Leaf )
66
+ }
67
+
68
+ New-Variable -Scope global -Name _OLD_VIRTUAL_PATH -Value $env:PATH
69
+
70
+ $env:PATH = "$env:VIRTUAL_ENV/bin:" + $env:PATH
71
+ if (!$env:VIRTUAL_ENV_DISABLE_PROMPT) {
72
+ function global:_old_virtual_prompt {
73
+ ""
74
+ }
75
+ $function:_old_virtual_prompt = $function:prompt
76
+
77
+ function global:prompt {
78
+ # Add the custom prefix to the existing prompt
79
+ $previous_prompt_value = & $function:_old_virtual_prompt
80
+ ("(" + $env:VIRTUAL_ENV_PROMPT + ") " + $previous_prompt_value)
81
+ }
82
+ }
.venv/bin/activate_this.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2020-202x The virtualenv developers
2
+ #
3
+ # Permission is hereby granted, free of charge, to any person obtaining
4
+ # a copy of this software and associated documentation files (the
5
+ # "Software"), to deal in the Software without restriction, including
6
+ # without limitation the rights to use, copy, modify, merge, publish,
7
+ # distribute, sublicense, and/or sell copies of the Software, and to
8
+ # permit persons to whom the Software is furnished to do so, subject to
9
+ # the following conditions:
10
+ #
11
+ # The above copyright notice and this permission notice shall be
12
+ # included in all copies or substantial portions of the Software.
13
+ #
14
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
+
22
+ """
23
+ Activate virtualenv for current interpreter:
24
+
25
+ import runpy
26
+ runpy.run_path(this_file)
27
+
28
+ This can be used when you must use an existing Python interpreter, not the virtualenv bin/python.
29
+ """ # noqa: D415
30
+
31
+ from __future__ import annotations
32
+
33
+ import os
34
+ import site
35
+ import sys
36
+
37
+ try:
38
+ abs_file = os.path.abspath(__file__)
39
+ except NameError as exc:
40
+ msg = "You must use import runpy; runpy.run_path(this_file)"
41
+ raise AssertionError(msg) from exc
42
+
43
+ bin_dir = os.path.dirname(abs_file)
44
+ base = bin_dir[: -len("bin") - 1] # strip away the bin part from the __file__, plus the path separator
45
+
46
+ # prepend bin to PATH (this file is inside the bin directory)
47
+ os.environ["PATH"] = os.pathsep.join([bin_dir, *os.environ.get("PATH", "").split(os.pathsep)])
48
+ os.environ["VIRTUAL_ENV"] = base # virtual env is right above bin directory
49
+ os.environ["VIRTUAL_ENV_PROMPT"] = "state_parse_repro" or os.path.basename(base) # noqa: SIM222
50
+
51
+ # add the virtual environments libraries to the host python import mechanism
52
+ prev_length = len(sys.path)
53
+ for lib in "../lib/python3.11/site-packages".split(os.pathsep):
54
+ path = os.path.realpath(os.path.join(bin_dir, lib))
55
+ site.addsitedir(path)
56
+ sys.path[:] = sys.path[prev_length:] + sys.path[0:prev_length]
57
+
58
+ sys.real_prefix = sys.prefix
59
+ sys.prefix = base
.venv/bin/deactivate.bat ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @REM Copyright (c) 2020-202x The virtualenv developers
2
+ @REM
3
+ @REM Permission is hereby granted, free of charge, to any person obtaining
4
+ @REM a copy of this software and associated documentation files (the
5
+ @REM "Software"), to deal in the Software without restriction, including
6
+ @REM without limitation the rights to use, copy, modify, merge, publish,
7
+ @REM distribute, sublicense, and/or sell copies of the Software, and to
8
+ @REM permit persons to whom the Software is furnished to do so, subject to
9
+ @REM the following conditions:
10
+ @REM
11
+ @REM The above copyright notice and this permission notice shall be
12
+ @REM included in all copies or substantial portions of the Software.
13
+ @REM
14
+ @REM THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ @REM EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ @REM MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ @REM NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ @REM LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ @REM OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ @REM WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
+
22
+ @set VIRTUAL_ENV=
23
+ @set VIRTUAL_ENV_PROMPT=
24
+
25
+ @REM Don't use () to avoid problems with them in %PATH%
26
+ @if not defined _OLD_VIRTUAL_PROMPT @goto ENDIFVPROMPT
27
+ @set "PROMPT=%_OLD_VIRTUAL_PROMPT%"
28
+ @set _OLD_VIRTUAL_PROMPT=
29
+ :ENDIFVPROMPT
30
+
31
+ @if not defined _OLD_VIRTUAL_PYTHONHOME @goto ENDIFVHOME
32
+ @set "PYTHONHOME=%_OLD_VIRTUAL_PYTHONHOME%"
33
+ @set _OLD_VIRTUAL_PYTHONHOME=
34
+ :ENDIFVHOME
35
+
36
+ @if not defined _OLD_VIRTUAL_PATH @goto ENDIFVPATH
37
+ @set "PATH=%_OLD_VIRTUAL_PATH%"
38
+ @set _OLD_VIRTUAL_PATH=
39
+ :ENDIFVPATH
.venv/bin/f2py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/gpfs/projects/p32222/aTester/state_parse_repro/.venv/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+ import sys
4
+ from numpy.f2py.f2py2e import main
5
+ if __name__ == "__main__":
6
+ if sys.argv[0].endswith("-script.pyw"):
7
+ sys.argv[0] = sys.argv[0][:-11]
8
+ elif sys.argv[0].endswith(".exe"):
9
+ sys.argv[0] = sys.argv[0][:-4]
10
+ sys.exit(main())
.venv/bin/fonttools ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/gpfs/projects/p32222/aTester/state_parse_repro/.venv/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+ import sys
4
+ from fontTools.__main__ import main
5
+ if __name__ == "__main__":
6
+ if sys.argv[0].endswith("-script.pyw"):
7
+ sys.argv[0] = sys.argv[0][:-11]
8
+ elif sys.argv[0].endswith(".exe"):
9
+ sys.argv[0] = sys.argv[0][:-4]
10
+ sys.exit(main())
.venv/bin/hf ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/gpfs/projects/p32222/aTester/state_parse_repro/.venv/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+ import sys
4
+ from huggingface_hub.cli.hf import main
5
+ if __name__ == "__main__":
6
+ if sys.argv[0].endswith("-script.pyw"):
7
+ sys.argv[0] = sys.argv[0][:-11]
8
+ elif sys.argv[0].endswith(".exe"):
9
+ sys.argv[0] = sys.argv[0][:-4]
10
+ sys.exit(main())
.venv/bin/httpx ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/gpfs/projects/p32222/aTester/state_parse_repro/.venv/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+ import sys
4
+ from httpx import main
5
+ if __name__ == "__main__":
6
+ if sys.argv[0].endswith("-script.pyw"):
7
+ sys.argv[0] = sys.argv[0][:-11]
8
+ elif sys.argv[0].endswith(".exe"):
9
+ sys.argv[0] = sys.argv[0][:-4]
10
+ sys.exit(main())
.venv/bin/huggingface-cli ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/gpfs/projects/p32222/aTester/state_parse_repro/.venv/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+ import sys
4
+ from huggingface_hub.cli.deprecated_cli import main
5
+ if __name__ == "__main__":
6
+ if sys.argv[0].endswith("-script.pyw"):
7
+ sys.argv[0] = sys.argv[0][:-11]
8
+ elif sys.argv[0].endswith(".exe"):
9
+ sys.argv[0] = sys.argv[0][:-4]
10
+ sys.exit(main())
.venv/bin/idna ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/gpfs/projects/p32222/aTester/state_parse_repro/.venv/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+ import sys
4
+ from idna.cli import main
5
+ if __name__ == "__main__":
6
+ if sys.argv[0].endswith("-script.pyw"):
7
+ sys.argv[0] = sys.argv[0][:-11]
8
+ elif sys.argv[0].endswith(".exe"):
9
+ sys.argv[0] = sys.argv[0][:-4]
10
+ sys.exit(main())
.venv/bin/natsort ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/gpfs/projects/p32222/aTester/state_parse_repro/.venv/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+ import sys
4
+ from natsort.__main__ import main
5
+ if __name__ == "__main__":
6
+ if sys.argv[0].endswith("-script.pyw"):
7
+ sys.argv[0] = sys.argv[0][:-11]
8
+ elif sys.argv[0].endswith(".exe"):
9
+ sys.argv[0] = sys.argv[0][:-4]
10
+ sys.exit(main())
.venv/bin/numba ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ #!/gpfs/projects/p32222/aTester/state_parse_repro/.venv/bin/python3
2
+ # -*- coding: UTF-8 -*-
3
+ from __future__ import print_function, division, absolute_import
4
+
5
+ from numba.misc.numba_entry import main
6
+
7
+ if __name__ == "__main__":
8
+ main()
.venv/bin/numpy-config ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/gpfs/projects/p32222/aTester/state_parse_repro/.venv/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+ import sys
4
+ from numpy._configtool import main
5
+ if __name__ == "__main__":
6
+ if sys.argv[0].endswith("-script.pyw"):
7
+ sys.argv[0] = sys.argv[0][:-11]
8
+ elif sys.argv[0].endswith(".exe"):
9
+ sys.argv[0] = sys.argv[0][:-4]
10
+ sys.exit(main())
.venv/bin/pip ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/gpfs/projects/p32222/aTester/state_parse_repro/.venv/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+ import sys
4
+ from pip._internal.cli.main import main
5
+ if __name__ == "__main__":
6
+ if sys.argv[0].endswith("-script.pyw"):
7
+ sys.argv[0] = sys.argv[0][:-11]
8
+ elif sys.argv[0].endswith(".exe"):
9
+ sys.argv[0] = sys.argv[0][:-4]
10
+ sys.exit(main())
.venv/bin/pip3 ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/gpfs/projects/p32222/aTester/state_parse_repro/.venv/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+ import sys
4
+ from pip._internal.cli.main import main
5
+ if __name__ == "__main__":
6
+ if sys.argv[0].endswith("-script.pyw"):
7
+ sys.argv[0] = sys.argv[0][:-11]
8
+ elif sys.argv[0].endswith(".exe"):
9
+ sys.argv[0] = sys.argv[0][:-4]
10
+ sys.exit(main())
.venv/bin/pip3.11 ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/gpfs/projects/p32222/aTester/state_parse_repro/.venv/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+ import sys
4
+ from pip._internal.cli.main import main
5
+ if __name__ == "__main__":
6
+ if sys.argv[0].endswith("-script.pyw"):
7
+ sys.argv[0] = sys.argv[0][:-11]
8
+ elif sys.argv[0].endswith(".exe"):
9
+ sys.argv[0] = sys.argv[0][:-4]
10
+ sys.exit(main())
.venv/bin/pydoc.bat ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @REM Copyright (c) 2020-202x The virtualenv developers
2
+ @REM
3
+ @REM Permission is hereby granted, free of charge, to any person obtaining
4
+ @REM a copy of this software and associated documentation files (the
5
+ @REM "Software"), to deal in the Software without restriction, including
6
+ @REM without limitation the rights to use, copy, modify, merge, publish,
7
+ @REM distribute, sublicense, and/or sell copies of the Software, and to
8
+ @REM permit persons to whom the Software is furnished to do so, subject to
9
+ @REM the following conditions:
10
+ @REM
11
+ @REM The above copyright notice and this permission notice shall be
12
+ @REM included in all copies or substantial portions of the Software.
13
+ @REM
14
+ @REM THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ @REM EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ @REM MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ @REM NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ @REM LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ @REM OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ @REM WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
+
22
+ python.exe -m pydoc %*
.venv/bin/pyftmerge ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/gpfs/projects/p32222/aTester/state_parse_repro/.venv/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+ import sys
4
+ from fontTools.merge import main
5
+ if __name__ == "__main__":
6
+ if sys.argv[0].endswith("-script.pyw"):
7
+ sys.argv[0] = sys.argv[0][:-11]
8
+ elif sys.argv[0].endswith(".exe"):
9
+ sys.argv[0] = sys.argv[0][:-4]
10
+ sys.exit(main())
.venv/bin/pyftsubset ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/gpfs/projects/p32222/aTester/state_parse_repro/.venv/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+ import sys
4
+ from fontTools.subset import main
5
+ if __name__ == "__main__":
6
+ if sys.argv[0].endswith("-script.pyw"):
7
+ sys.argv[0] = sys.argv[0][:-11]
8
+ elif sys.argv[0].endswith(".exe"):
9
+ sys.argv[0] = sys.argv[0][:-4]
10
+ sys.exit(main())
.venv/bin/python ADDED
Binary file (20.3 kB). View file
 
.venv/bin/python3 ADDED
Binary file (20.3 kB). View file
 
.venv/bin/python3.11 ADDED
Binary file (20.3 kB). View file
 
.venv/bin/scanpy ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/gpfs/projects/p32222/aTester/state_parse_repro/.venv/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+ import sys
4
+ from scanpy.cli import console_main
5
+ if __name__ == "__main__":
6
+ if sys.argv[0].endswith("-script.pyw"):
7
+ sys.argv[0] = sys.argv[0][:-11]
8
+ elif sys.argv[0].endswith(".exe"):
9
+ sys.argv[0] = sys.argv[0][:-4]
10
+ sys.exit(console_main())
.venv/bin/session-info ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/gpfs/projects/p32222/aTester/state_parse_repro/.venv/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+ import sys
4
+ from session_info2.cli import main
5
+ if __name__ == "__main__":
6
+ if sys.argv[0].endswith("-script.pyw"):
7
+ sys.argv[0] = sys.argv[0][:-11]
8
+ elif sys.argv[0].endswith(".exe"):
9
+ sys.argv[0] = sys.argv[0][:-4]
10
+ sys.exit(main())
.venv/bin/session-info2 ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/gpfs/projects/p32222/aTester/state_parse_repro/.venv/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+ import sys
4
+ from session_info2.cli import main
5
+ if __name__ == "__main__":
6
+ if sys.argv[0].endswith("-script.pyw"):
7
+ sys.argv[0] = sys.argv[0][:-11]
8
+ elif sys.argv[0].endswith(".exe"):
9
+ sys.argv[0] = sys.argv[0][:-4]
10
+ sys.exit(main())
.venv/bin/tiny-agents ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/gpfs/projects/p32222/aTester/state_parse_repro/.venv/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+ import sys
4
+ from huggingface_hub.inference._mcp.cli import app
5
+ if __name__ == "__main__":
6
+ if sys.argv[0].endswith("-script.pyw"):
7
+ sys.argv[0] = sys.argv[0][:-11]
8
+ elif sys.argv[0].endswith(".exe"):
9
+ sys.argv[0] = sys.argv[0][:-4]
10
+ sys.exit(app())
.venv/bin/tqdm ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/gpfs/projects/p32222/aTester/state_parse_repro/.venv/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+ import sys
4
+ from tqdm.cli import main
5
+ if __name__ == "__main__":
6
+ if sys.argv[0].endswith("-script.pyw"):
7
+ sys.argv[0] = sys.argv[0][:-11]
8
+ elif sys.argv[0].endswith(".exe"):
9
+ sys.argv[0] = sys.argv[0][:-4]
10
+ sys.exit(main())
.venv/bin/ttx ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/gpfs/projects/p32222/aTester/state_parse_repro/.venv/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+ import sys
4
+ from fontTools.ttx import main
5
+ if __name__ == "__main__":
6
+ if sys.argv[0].endswith("-script.pyw"):
7
+ sys.argv[0] = sys.argv[0][:-11]
8
+ elif sys.argv[0].endswith(".exe"):
9
+ sys.argv[0] = sys.argv[0][:-4]
10
+ sys.exit(main())
.venv/bin/zarr ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/gpfs/projects/p32222/aTester/state_parse_repro/.venv/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+ import sys
4
+ from zarr._cli.cli import app
5
+ if __name__ == "__main__":
6
+ if sys.argv[0].endswith("-script.pyw"):
7
+ sys.argv[0] = sys.argv[0][:-11]
8
+ elif sys.argv[0].endswith(".exe"):
9
+ sys.argv[0] = sys.argv[0][:-4]
10
+ sys.exit(app())
.venv/lib/python3.11/site-packages/PIL/AvifImagePlugin.py ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ from io import BytesIO
5
+ from typing import IO
6
+
7
+ from . import ExifTags, Image, ImageFile, ImageSequence
8
+
9
+ try:
10
+ from . import _avif
11
+
12
+ SUPPORTED = True
13
+ except ImportError:
14
+ SUPPORTED = False
15
+
16
+ # Decoder options as module globals, until there is a way to pass parameters
17
+ # to Image.open (see https://github.com/python-pillow/Pillow/issues/569)
18
+ DECODE_CODEC_CHOICE = "auto"
19
+ DEFAULT_MAX_THREADS = 0
20
+
21
+
22
+ def get_codec_version(codec_name: str) -> str | None:
23
+ versions = _avif.codec_versions()
24
+ for version in versions.split(", "):
25
+ if version.split(" [")[0] == codec_name:
26
+ return version.split(":")[-1].split(" ")[0]
27
+ return None
28
+
29
+
30
+ def _accept(prefix: bytes) -> bool | str:
31
+ if prefix[4:8] != b"ftyp":
32
+ return False
33
+ major_brand = prefix[8:12]
34
+ if major_brand in (
35
+ # coding brands
36
+ b"avif",
37
+ b"avis",
38
+ # We accept files with AVIF container brands; we can't yet know if
39
+ # the ftyp box has the correct compatible brands, but if it doesn't
40
+ # then the plugin will raise a SyntaxError which Pillow will catch
41
+ # before moving on to the next plugin that accepts the file.
42
+ #
43
+ # Also, because this file might not actually be an AVIF file, we
44
+ # don't raise an error if AVIF support isn't properly compiled.
45
+ b"mif1",
46
+ b"msf1",
47
+ ):
48
+ if not SUPPORTED:
49
+ return (
50
+ "image file could not be identified because AVIF support not installed"
51
+ )
52
+ return True
53
+ return False
54
+
55
+
56
+ def _get_default_max_threads() -> int:
57
+ if DEFAULT_MAX_THREADS:
58
+ return DEFAULT_MAX_THREADS
59
+ if hasattr(os, "sched_getaffinity"):
60
+ return len(os.sched_getaffinity(0))
61
+ else:
62
+ return os.cpu_count() or 1
63
+
64
+
65
+ class AvifImageFile(ImageFile.ImageFile):
66
+ format = "AVIF"
67
+ format_description = "AVIF image"
68
+ __frame = -1
69
+
70
+ def _open(self) -> None:
71
+ if not SUPPORTED:
72
+ msg = "image file could not be opened because AVIF support not installed"
73
+ raise SyntaxError(msg)
74
+
75
+ if DECODE_CODEC_CHOICE != "auto" and not _avif.decoder_codec_available(
76
+ DECODE_CODEC_CHOICE
77
+ ):
78
+ msg = "Invalid opening codec"
79
+ raise ValueError(msg)
80
+
81
+ assert self.fp is not None
82
+ self._decoder = _avif.AvifDecoder(
83
+ self.fp.read(),
84
+ DECODE_CODEC_CHOICE,
85
+ _get_default_max_threads(),
86
+ )
87
+
88
+ # Get info from decoder
89
+ self._size, self.n_frames, self._mode, icc, exif, exif_orientation, xmp = (
90
+ self._decoder.get_info()
91
+ )
92
+ self.is_animated = self.n_frames > 1
93
+
94
+ if icc:
95
+ self.info["icc_profile"] = icc
96
+ if xmp:
97
+ self.info["xmp"] = xmp
98
+
99
+ if exif_orientation != 1 or exif:
100
+ exif_data = Image.Exif()
101
+ if exif:
102
+ exif_data.load(exif)
103
+ original_orientation = exif_data.get(ExifTags.Base.Orientation, 1)
104
+ else:
105
+ original_orientation = 1
106
+ if exif_orientation != original_orientation:
107
+ exif_data[ExifTags.Base.Orientation] = exif_orientation
108
+ exif = exif_data.tobytes()
109
+ if exif:
110
+ self.info["exif"] = exif
111
+ self.seek(0)
112
+
113
+ def seek(self, frame: int) -> None:
114
+ if not self._seek_check(frame):
115
+ return
116
+
117
+ # Set tile
118
+ self.__frame = frame
119
+ self.tile = [ImageFile._Tile("raw", (0, 0) + self.size, 0, self.mode)]
120
+
121
+ def load(self) -> Image.core.PixelAccess | None:
122
+ if self.tile:
123
+ # We need to load the image data for this frame
124
+ data, timescale, pts_in_timescales, duration_in_timescales = (
125
+ self._decoder.get_frame(self.__frame)
126
+ )
127
+ self.info["timestamp"] = round(1000 * (pts_in_timescales / timescale))
128
+ self.info["duration"] = round(1000 * (duration_in_timescales / timescale))
129
+
130
+ if self.fp and self._exclusive_fp:
131
+ self.fp.close()
132
+ self.fp = BytesIO(data)
133
+
134
+ return super().load()
135
+
136
+ def load_seek(self, pos: int) -> None:
137
+ pass
138
+
139
+ def tell(self) -> int:
140
+ return self.__frame
141
+
142
+
143
+ def _save_all(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
144
+ _save(im, fp, filename, save_all=True)
145
+
146
+
147
+ def _save(
148
+ im: Image.Image, fp: IO[bytes], filename: str | bytes, save_all: bool = False
149
+ ) -> None:
150
+ info = im.encoderinfo.copy()
151
+ if save_all:
152
+ append_images = list(info.get("append_images", []))
153
+ else:
154
+ append_images = []
155
+
156
+ grayscale_modes = {"1", "L", "I", "I;16", "I;16L", "I;16B", "I;16N", "F"}
157
+ grayscale = all(
158
+ frame.mode in grayscale_modes
159
+ for ims in [im] + append_images
160
+ for frame in ImageSequence.Iterator(ims)
161
+ )
162
+
163
+ quality = info.get("quality", 75)
164
+ if not isinstance(quality, int) or quality < 0 or quality > 100:
165
+ msg = "Invalid quality setting"
166
+ raise ValueError(msg)
167
+
168
+ duration = info.get("duration", 0)
169
+ subsampling = info.get("subsampling", "4:0:0" if grayscale else "4:2:0")
170
+ speed = info.get("speed", 6)
171
+ max_threads = info.get("max_threads", _get_default_max_threads())
172
+ codec = info.get("codec", "auto")
173
+ if codec != "auto" and not _avif.encoder_codec_available(codec):
174
+ msg = "Invalid saving codec"
175
+ raise ValueError(msg)
176
+ range_ = info.get("range", "full")
177
+ tile_rows_log2 = info.get("tile_rows", 0)
178
+ tile_cols_log2 = info.get("tile_cols", 0)
179
+ alpha_premultiplied = bool(info.get("alpha_premultiplied", False))
180
+ autotiling = bool(info.get("autotiling", tile_rows_log2 == tile_cols_log2 == 0))
181
+
182
+ icc_profile = info.get("icc_profile", im.info.get("icc_profile"))
183
+ exif_orientation = 1
184
+ if exif := info.get("exif"):
185
+ if isinstance(exif, Image.Exif):
186
+ exif_data = exif
187
+ else:
188
+ exif_data = Image.Exif()
189
+ exif_data.load(exif)
190
+ if ExifTags.Base.Orientation in exif_data:
191
+ exif_orientation = exif_data.pop(ExifTags.Base.Orientation)
192
+ exif = exif_data.tobytes() if exif_data else b""
193
+ elif isinstance(exif, Image.Exif):
194
+ exif = exif_data.tobytes()
195
+
196
+ xmp = info.get("xmp")
197
+
198
+ if isinstance(xmp, str):
199
+ xmp = xmp.encode("utf-8")
200
+
201
+ advanced = info.get("advanced")
202
+ if advanced is not None:
203
+ if isinstance(advanced, dict):
204
+ advanced = advanced.items()
205
+ try:
206
+ advanced = tuple(advanced)
207
+ except TypeError:
208
+ invalid = True
209
+ else:
210
+ invalid = any(not isinstance(v, tuple) or len(v) != 2 for v in advanced)
211
+ if invalid:
212
+ msg = (
213
+ "advanced codec options must be a dict of key-value string "
214
+ "pairs or a series of key-value two-tuples"
215
+ )
216
+ raise ValueError(msg)
217
+
218
+ # Setup the AVIF encoder
219
+ enc = _avif.AvifEncoder(
220
+ im.size,
221
+ subsampling,
222
+ quality,
223
+ speed,
224
+ max_threads,
225
+ codec,
226
+ range_,
227
+ tile_rows_log2,
228
+ tile_cols_log2,
229
+ alpha_premultiplied,
230
+ autotiling,
231
+ icc_profile or b"",
232
+ exif or b"",
233
+ exif_orientation,
234
+ xmp or b"",
235
+ advanced,
236
+ )
237
+
238
+ # Add each frame
239
+ frame_idx = 0
240
+ frame_duration = 0
241
+ cur_idx = im.tell()
242
+ is_single_frame = not append_images and not getattr(im, "is_animated", False)
243
+ try:
244
+ for ims in [im] + append_images:
245
+ for frame in ImageSequence.Iterator(ims):
246
+ # Make sure image mode is supported
247
+ rawmode = frame.mode
248
+ if ims.mode not in {"L", "RGB", "RGBA"}:
249
+ if ims.has_transparency_data:
250
+ rawmode = "RGBA"
251
+ elif ims.mode in grayscale_modes:
252
+ rawmode = "L"
253
+ else:
254
+ rawmode = "RGB"
255
+ frame = frame.convert(rawmode)
256
+
257
+ # Update frame duration
258
+ if isinstance(duration, (list, tuple)):
259
+ frame_duration = duration[frame_idx]
260
+ else:
261
+ frame_duration = duration
262
+
263
+ # Append the frame to the animation encoder
264
+ enc.add(
265
+ frame.tobytes("raw", rawmode),
266
+ frame_duration,
267
+ frame.size,
268
+ rawmode,
269
+ is_single_frame,
270
+ )
271
+
272
+ # Update frame index
273
+ frame_idx += 1
274
+
275
+ if not save_all:
276
+ break
277
+
278
+ finally:
279
+ im.seek(cur_idx)
280
+
281
+ # Get the final output from the encoder
282
+ data = enc.finish()
283
+ if data is None:
284
+ msg = "cannot write file as AVIF (encoder returned None)"
285
+ raise OSError(msg)
286
+
287
+ fp.write(data)
288
+
289
+
290
+ Image.register_open(AvifImageFile.format, AvifImageFile, _accept)
291
+ if SUPPORTED:
292
+ Image.register_save(AvifImageFile.format, _save)
293
+ Image.register_save_all(AvifImageFile.format, _save_all)
294
+ Image.register_extensions(AvifImageFile.format, [".avif", ".avifs"])
295
+ Image.register_mime(AvifImageFile.format, "image/avif")
.venv/lib/python3.11/site-packages/PIL/BdfFontFile.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library
3
+ # $Id$
4
+ #
5
+ # bitmap distribution font (bdf) file parser
6
+ #
7
+ # history:
8
+ # 1996-05-16 fl created (as bdf2pil)
9
+ # 1997-08-25 fl converted to FontFile driver
10
+ # 2001-05-25 fl removed bogus __init__ call
11
+ # 2002-11-20 fl robustification (from Kevin Cazabon, Dmitry Vasiliev)
12
+ # 2003-04-22 fl more robustification (from Graham Dumpleton)
13
+ #
14
+ # Copyright (c) 1997-2003 by Secret Labs AB.
15
+ # Copyright (c) 1997-2003 by Fredrik Lundh.
16
+ #
17
+ # See the README file for information on usage and redistribution.
18
+ #
19
+
20
+ """
21
+ Parse X Bitmap Distribution Format (BDF)
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ from typing import BinaryIO
27
+
28
+ from . import FontFile, Image
29
+
30
+
31
+ def bdf_char(
32
+ f: BinaryIO,
33
+ ) -> (
34
+ tuple[
35
+ str,
36
+ int,
37
+ tuple[tuple[int, int], tuple[int, int, int, int], tuple[int, int, int, int]],
38
+ Image.Image,
39
+ ]
40
+ | None
41
+ ):
42
+ # skip to STARTCHAR
43
+ while True:
44
+ s = f.readline()
45
+ if not s:
46
+ return None
47
+ if s.startswith(b"STARTCHAR"):
48
+ break
49
+ id = s[9:].strip().decode("ascii")
50
+
51
+ # load symbol properties
52
+ props = {}
53
+ while True:
54
+ s = f.readline()
55
+ if not s or s.startswith(b"BITMAP"):
56
+ break
57
+ i = s.find(b" ")
58
+ props[s[:i].decode("ascii")] = s[i + 1 : -1].decode("ascii")
59
+
60
+ # load bitmap
61
+ bitmap = bytearray()
62
+ while True:
63
+ s = f.readline()
64
+ if not s or s.startswith(b"ENDCHAR"):
65
+ break
66
+ bitmap += s[:-1]
67
+
68
+ # The word BBX
69
+ # followed by the width in x (BBw), height in y (BBh),
70
+ # and x and y displacement (BBxoff0, BByoff0)
71
+ # of the lower left corner from the origin of the character.
72
+ width, height, x_disp, y_disp = (int(p) for p in props["BBX"].split())
73
+ Image._decompression_bomb_check((width, height))
74
+
75
+ # The word DWIDTH
76
+ # followed by the width in x and y of the character in device pixels.
77
+ dwx, dwy = (int(p) for p in props["DWIDTH"].split())
78
+
79
+ bbox = (
80
+ (dwx, dwy),
81
+ (x_disp, -y_disp - height, width + x_disp, -y_disp),
82
+ (0, 0, width, height),
83
+ )
84
+
85
+ try:
86
+ im = Image.frombytes("1", (width, height), bitmap, "hex", "1")
87
+ except ValueError:
88
+ # deal with zero-width characters
89
+ im = Image.new("1", (width, height))
90
+
91
+ return id, int(props["ENCODING"]), bbox, im
92
+
93
+
94
+ class BdfFontFile(FontFile.FontFile):
95
+ """Font file plugin for the X11 BDF format."""
96
+
97
+ def __init__(self, fp: BinaryIO) -> None:
98
+ super().__init__()
99
+
100
+ s = fp.readline()
101
+ if not s.startswith(b"STARTFONT 2.1"):
102
+ msg = "not a valid BDF file"
103
+ raise SyntaxError(msg)
104
+
105
+ props = {}
106
+ comments = []
107
+
108
+ while True:
109
+ s = fp.readline()
110
+ if not s or s.startswith(b"ENDPROPERTIES"):
111
+ break
112
+ i = s.find(b" ")
113
+ props[s[:i].decode("ascii")] = s[i + 1 : -1].decode("ascii")
114
+ if s[:i] in [b"COMMENT", b"COPYRIGHT"]:
115
+ if s.find(b"LogicalFontDescription") < 0:
116
+ comments.append(s[i + 1 : -1].decode("ascii"))
117
+
118
+ while True:
119
+ c = bdf_char(fp)
120
+ if not c:
121
+ break
122
+ id, ch, (xy, dst, src), im = c
123
+ if 0 <= ch < len(self.glyph):
124
+ self.glyph[ch] = xy, dst, src, im
.venv/lib/python3.11/site-packages/PIL/BlpImagePlugin.py ADDED
@@ -0,0 +1,498 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Blizzard Mipmap Format (.blp)
3
+ Jerome Leclanche <jerome@leclan.ch>
4
+
5
+ The contents of this file are hereby released in the public domain (CC0)
6
+ Full text of the CC0 license:
7
+ https://creativecommons.org/publicdomain/zero/1.0/
8
+
9
+ BLP1 files, used mostly in Warcraft III, are not fully supported.
10
+ All types of BLP2 files used in World of Warcraft are supported.
11
+
12
+ The BLP file structure consists of a header, up to 16 mipmaps of the
13
+ texture
14
+
15
+ Texture sizes must be powers of two, though the two dimensions do
16
+ not have to be equal; 512x256 is valid, but 512x200 is not.
17
+ The first mipmap (mipmap #0) is the full size image; each subsequent
18
+ mipmap halves both dimensions. The final mipmap should be 1x1.
19
+
20
+ BLP files come in many different flavours:
21
+ * JPEG-compressed (type == 0) - only supported for BLP1.
22
+ * RAW images (type == 1, encoding == 1). Each mipmap is stored as an
23
+ array of 8-bit values, one per pixel, left to right, top to bottom.
24
+ Each value is an index to the palette.
25
+ * DXT-compressed (type == 1, encoding == 2):
26
+ - DXT1 compression is used if alpha_encoding == 0.
27
+ - An additional alpha bit is used if alpha_depth == 1.
28
+ - DXT3 compression is used if alpha_encoding == 1.
29
+ - DXT5 compression is used if alpha_encoding == 7.
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ import abc
35
+ import os
36
+ import struct
37
+ from enum import IntEnum
38
+ from io import BytesIO
39
+ from typing import IO
40
+
41
+ from . import Image, ImageFile
42
+
43
+
44
+ class Format(IntEnum):
45
+ JPEG = 0
46
+
47
+
48
+ class Encoding(IntEnum):
49
+ UNCOMPRESSED = 1
50
+ DXT = 2
51
+ UNCOMPRESSED_RAW_BGRA = 3
52
+
53
+
54
+ class AlphaEncoding(IntEnum):
55
+ DXT1 = 0
56
+ DXT3 = 1
57
+ DXT5 = 7
58
+
59
+
60
+ def unpack_565(i: int) -> tuple[int, int, int]:
61
+ return ((i >> 11) & 0x1F) << 3, ((i >> 5) & 0x3F) << 2, (i & 0x1F) << 3
62
+
63
+
64
+ def decode_dxt1(
65
+ data: bytes, alpha: bool = False
66
+ ) -> tuple[bytearray, bytearray, bytearray, bytearray]:
67
+ """
68
+ input: one "row" of data (i.e. will produce 4*width pixels)
69
+ """
70
+
71
+ blocks = len(data) // 8 # number of blocks in row
72
+ ret = (bytearray(), bytearray(), bytearray(), bytearray())
73
+
74
+ for block_index in range(blocks):
75
+ # Decode next 8-byte block.
76
+ idx = block_index * 8
77
+ color0, color1, bits = struct.unpack_from("<HHI", data, idx)
78
+
79
+ r0, g0, b0 = unpack_565(color0)
80
+ r1, g1, b1 = unpack_565(color1)
81
+
82
+ # Decode this block into 4x4 pixels
83
+ # Accumulate the results onto our 4 row accumulators
84
+ for j in range(4):
85
+ for i in range(4):
86
+ # get next control op and generate a pixel
87
+
88
+ control = bits & 3
89
+ bits = bits >> 2
90
+
91
+ a = 0xFF
92
+ if control == 0:
93
+ r, g, b = r0, g0, b0
94
+ elif control == 1:
95
+ r, g, b = r1, g1, b1
96
+ elif control == 2:
97
+ if color0 > color1:
98
+ r = (2 * r0 + r1) // 3
99
+ g = (2 * g0 + g1) // 3
100
+ b = (2 * b0 + b1) // 3
101
+ else:
102
+ r = (r0 + r1) // 2
103
+ g = (g0 + g1) // 2
104
+ b = (b0 + b1) // 2
105
+ elif control == 3:
106
+ if color0 > color1:
107
+ r = (2 * r1 + r0) // 3
108
+ g = (2 * g1 + g0) // 3
109
+ b = (2 * b1 + b0) // 3
110
+ else:
111
+ r, g, b, a = 0, 0, 0, 0
112
+
113
+ if alpha:
114
+ ret[j].extend([r, g, b, a])
115
+ else:
116
+ ret[j].extend([r, g, b])
117
+
118
+ return ret
119
+
120
+
121
+ def decode_dxt3(data: bytes) -> tuple[bytearray, bytearray, bytearray, bytearray]:
122
+ """
123
+ input: one "row" of data (i.e. will produce 4*width pixels)
124
+ """
125
+
126
+ blocks = len(data) // 16 # number of blocks in row
127
+ ret = (bytearray(), bytearray(), bytearray(), bytearray())
128
+
129
+ for block_index in range(blocks):
130
+ idx = block_index * 16
131
+ block = data[idx : idx + 16]
132
+ # Decode next 16-byte block.
133
+ bits = struct.unpack_from("<8B", block)
134
+ color0, color1 = struct.unpack_from("<HH", block, 8)
135
+
136
+ (code,) = struct.unpack_from("<I", block, 12)
137
+
138
+ r0, g0, b0 = unpack_565(color0)
139
+ r1, g1, b1 = unpack_565(color1)
140
+
141
+ for j in range(4):
142
+ high = False # Do we want the higher bits?
143
+ for i in range(4):
144
+ alphacode_index = (4 * j + i) // 2
145
+ a = bits[alphacode_index]
146
+ if high:
147
+ high = False
148
+ a >>= 4
149
+ else:
150
+ high = True
151
+ a &= 0xF
152
+ a *= 17 # We get a value between 0 and 15
153
+
154
+ color_code = (code >> 2 * (4 * j + i)) & 0x03
155
+
156
+ if color_code == 0:
157
+ r, g, b = r0, g0, b0
158
+ elif color_code == 1:
159
+ r, g, b = r1, g1, b1
160
+ elif color_code == 2:
161
+ r = (2 * r0 + r1) // 3
162
+ g = (2 * g0 + g1) // 3
163
+ b = (2 * b0 + b1) // 3
164
+ elif color_code == 3:
165
+ r = (2 * r1 + r0) // 3
166
+ g = (2 * g1 + g0) // 3
167
+ b = (2 * b1 + b0) // 3
168
+
169
+ ret[j].extend([r, g, b, a])
170
+
171
+ return ret
172
+
173
+
174
+ def decode_dxt5(data: bytes) -> tuple[bytearray, bytearray, bytearray, bytearray]:
175
+ """
176
+ input: one "row" of data (i.e. will produce 4 * width pixels)
177
+ """
178
+
179
+ blocks = len(data) // 16 # number of blocks in row
180
+ ret = (bytearray(), bytearray(), bytearray(), bytearray())
181
+
182
+ for block_index in range(blocks):
183
+ idx = block_index * 16
184
+ block = data[idx : idx + 16]
185
+ # Decode next 16-byte block.
186
+ a0, a1 = struct.unpack_from("<BB", block)
187
+
188
+ bits = struct.unpack_from("<6B", block, 2)
189
+ alphacode1 = bits[2] | (bits[3] << 8) | (bits[4] << 16) | (bits[5] << 24)
190
+ alphacode2 = bits[0] | (bits[1] << 8)
191
+
192
+ color0, color1 = struct.unpack_from("<HH", block, 8)
193
+
194
+ (code,) = struct.unpack_from("<I", block, 12)
195
+
196
+ r0, g0, b0 = unpack_565(color0)
197
+ r1, g1, b1 = unpack_565(color1)
198
+
199
+ for j in range(4):
200
+ for i in range(4):
201
+ # get next control op and generate a pixel
202
+ alphacode_index = 3 * (4 * j + i)
203
+
204
+ if alphacode_index <= 12:
205
+ alphacode = (alphacode2 >> alphacode_index) & 0x07
206
+ elif alphacode_index == 15:
207
+ alphacode = (alphacode2 >> 15) | ((alphacode1 << 1) & 0x06)
208
+ else: # alphacode_index >= 18 and alphacode_index <= 45
209
+ alphacode = (alphacode1 >> (alphacode_index - 16)) & 0x07
210
+
211
+ if alphacode == 0:
212
+ a = a0
213
+ elif alphacode == 1:
214
+ a = a1
215
+ elif a0 > a1:
216
+ a = ((8 - alphacode) * a0 + (alphacode - 1) * a1) // 7
217
+ elif alphacode == 6:
218
+ a = 0
219
+ elif alphacode == 7:
220
+ a = 255
221
+ else:
222
+ a = ((6 - alphacode) * a0 + (alphacode - 1) * a1) // 5
223
+
224
+ color_code = (code >> 2 * (4 * j + i)) & 0x03
225
+
226
+ if color_code == 0:
227
+ r, g, b = r0, g0, b0
228
+ elif color_code == 1:
229
+ r, g, b = r1, g1, b1
230
+ elif color_code == 2:
231
+ r = (2 * r0 + r1) // 3
232
+ g = (2 * g0 + g1) // 3
233
+ b = (2 * b0 + b1) // 3
234
+ elif color_code == 3:
235
+ r = (2 * r1 + r0) // 3
236
+ g = (2 * g1 + g0) // 3
237
+ b = (2 * b1 + b0) // 3
238
+
239
+ ret[j].extend([r, g, b, a])
240
+
241
+ return ret
242
+
243
+
244
+ class BLPFormatError(NotImplementedError):
245
+ pass
246
+
247
+
248
+ def _accept(prefix: bytes) -> bool:
249
+ return prefix.startswith((b"BLP1", b"BLP2"))
250
+
251
+
252
+ class BlpImageFile(ImageFile.ImageFile):
253
+ """
254
+ Blizzard Mipmap Format
255
+ """
256
+
257
+ format = "BLP"
258
+ format_description = "Blizzard Mipmap Format"
259
+
260
+ def _open(self) -> None:
261
+ assert self.fp is not None
262
+ self.magic = self.fp.read(4)
263
+ if not _accept(self.magic):
264
+ msg = f"Bad BLP magic {repr(self.magic)}"
265
+ raise BLPFormatError(msg)
266
+
267
+ compression = struct.unpack("<i", self.fp.read(4))[0]
268
+ if self.magic == b"BLP1":
269
+ alpha = struct.unpack("<I", self.fp.read(4))[0] != 0
270
+ else:
271
+ encoding = struct.unpack("<b", self.fp.read(1))[0]
272
+ alpha = struct.unpack("<b", self.fp.read(1))[0] != 0
273
+ alpha_encoding = struct.unpack("<b", self.fp.read(1))[0]
274
+ self.fp.seek(1, os.SEEK_CUR) # mips
275
+
276
+ self._size = struct.unpack("<II", self.fp.read(8))
277
+
278
+ args: tuple[int, int, bool] | tuple[int, int, bool, int]
279
+ if self.magic == b"BLP1":
280
+ encoding = struct.unpack("<i", self.fp.read(4))[0]
281
+ self.fp.seek(4, os.SEEK_CUR) # subtype
282
+
283
+ args = (compression, encoding, alpha)
284
+ offset = 28
285
+ else:
286
+ args = (compression, encoding, alpha, alpha_encoding)
287
+ offset = 20
288
+
289
+ decoder = self.magic.decode()
290
+
291
+ self._mode = "RGBA" if alpha else "RGB"
292
+ self.tile = [ImageFile._Tile(decoder, (0, 0) + self.size, offset, args)]
293
+
294
+
295
+ class _BLPBaseDecoder(abc.ABC, ImageFile.PyDecoder):
296
+ _pulls_fd = True
297
+
298
+ def decode(self, buffer: Image.DecoderInput) -> tuple[int, int]:
299
+ try:
300
+ self._read_header()
301
+ self._load()
302
+ except struct.error as e:
303
+ msg = "Truncated BLP file"
304
+ raise OSError(msg) from e
305
+ return -1, 0
306
+
307
+ @abc.abstractmethod
308
+ def _load(self) -> None:
309
+ pass
310
+
311
+ def _read_header(self) -> None:
312
+ self._offsets = struct.unpack("<16I", self._safe_read(16 * 4))
313
+ self._lengths = struct.unpack("<16I", self._safe_read(16 * 4))
314
+
315
+ def _safe_read(self, length: int) -> bytes:
316
+ assert self.fd is not None
317
+ return ImageFile._safe_read(self.fd, length)
318
+
319
+ def _read_palette(self) -> list[tuple[int, int, int, int]]:
320
+ ret = []
321
+ for i in range(256):
322
+ try:
323
+ b, g, r, a = struct.unpack("<4B", self._safe_read(4))
324
+ except struct.error:
325
+ break
326
+ ret.append((b, g, r, a))
327
+ return ret
328
+
329
+ def _read_bgra(
330
+ self, palette: list[tuple[int, int, int, int]], alpha: bool
331
+ ) -> bytearray:
332
+ data = bytearray()
333
+ _data = BytesIO(self._safe_read(self._lengths[0]))
334
+ while True:
335
+ try:
336
+ (offset,) = struct.unpack("<B", _data.read(1))
337
+ except struct.error:
338
+ break
339
+ b, g, r, a = palette[offset]
340
+ d: tuple[int, ...] = (r, g, b)
341
+ if alpha:
342
+ d += (a,)
343
+ data.extend(d)
344
+ return data
345
+
346
+
347
+ class BLP1Decoder(_BLPBaseDecoder):
348
+ def _load(self) -> None:
349
+ self._compression, self._encoding, alpha = self.args
350
+
351
+ if self._compression == Format.JPEG:
352
+ self._decode_jpeg_stream()
353
+
354
+ elif self._compression == 1:
355
+ if self._encoding in (4, 5):
356
+ palette = self._read_palette()
357
+ data = self._read_bgra(palette, alpha)
358
+ self.set_as_raw(data)
359
+ else:
360
+ msg = f"Unsupported BLP encoding {repr(self._encoding)}"
361
+ raise BLPFormatError(msg)
362
+ else:
363
+ msg = f"Unsupported BLP compression {repr(self._encoding)}"
364
+ raise BLPFormatError(msg)
365
+
366
+ def _decode_jpeg_stream(self) -> None:
367
+ from .JpegImagePlugin import JpegImageFile
368
+
369
+ (jpeg_header_size,) = struct.unpack("<I", self._safe_read(4))
370
+ jpeg_header = self._safe_read(jpeg_header_size)
371
+ assert self.fd is not None
372
+ self._safe_read(self._offsets[0] - self.fd.tell()) # What IS this?
373
+ data = self._safe_read(self._lengths[0])
374
+ data = jpeg_header + data
375
+ image = JpegImageFile(BytesIO(data))
376
+ Image._decompression_bomb_check(image.size)
377
+ if image.mode == "CMYK":
378
+ args = image.tile[0].args
379
+ assert isinstance(args, tuple)
380
+ image.tile = [image.tile[0]._replace(args=(args[0], "CMYK"))]
381
+ self.set_as_raw(image.convert("RGB").tobytes(), "BGR")
382
+
383
+
384
+ class BLP2Decoder(_BLPBaseDecoder):
385
+ def _load(self) -> None:
386
+ self._compression, self._encoding, alpha, self._alpha_encoding = self.args
387
+
388
+ palette = self._read_palette()
389
+
390
+ assert self.fd is not None
391
+ self.fd.seek(self._offsets[0])
392
+
393
+ if self._compression == 1:
394
+ # Uncompressed or DirectX compression
395
+
396
+ if self._encoding == Encoding.UNCOMPRESSED:
397
+ data = self._read_bgra(palette, alpha)
398
+
399
+ elif self._encoding == Encoding.DXT:
400
+ data = bytearray()
401
+ if self._alpha_encoding == AlphaEncoding.DXT1:
402
+ linesize = (self.state.xsize + 3) // 4 * 8
403
+ for yb in range((self.state.ysize + 3) // 4):
404
+ for d in decode_dxt1(self._safe_read(linesize), alpha):
405
+ data += d
406
+
407
+ elif self._alpha_encoding == AlphaEncoding.DXT3:
408
+ linesize = (self.state.xsize + 3) // 4 * 16
409
+ for yb in range((self.state.ysize + 3) // 4):
410
+ for d in decode_dxt3(self._safe_read(linesize)):
411
+ data += d
412
+
413
+ elif self._alpha_encoding == AlphaEncoding.DXT5:
414
+ linesize = (self.state.xsize + 3) // 4 * 16
415
+ for yb in range((self.state.ysize + 3) // 4):
416
+ for d in decode_dxt5(self._safe_read(linesize)):
417
+ data += d
418
+ else:
419
+ msg = f"Unsupported alpha encoding {repr(self._alpha_encoding)}"
420
+ raise BLPFormatError(msg)
421
+ else:
422
+ msg = f"Unknown BLP encoding {repr(self._encoding)}"
423
+ raise BLPFormatError(msg)
424
+
425
+ else:
426
+ msg = f"Unknown BLP compression {repr(self._compression)}"
427
+ raise BLPFormatError(msg)
428
+
429
+ self.set_as_raw(data)
430
+
431
+
432
+ class BLPEncoder(ImageFile.PyEncoder):
433
+ _pushes_fd = True
434
+
435
+ def _write_palette(self) -> bytes:
436
+ data = b""
437
+ assert self.im is not None
438
+ palette = self.im.getpalette("RGBA", "RGBA")
439
+ for i in range(len(palette) // 4):
440
+ r, g, b, a = palette[i * 4 : (i + 1) * 4]
441
+ data += struct.pack("<4B", b, g, r, a)
442
+ while len(data) < 256 * 4:
443
+ data += b"\x00" * 4
444
+ return data
445
+
446
+ def encode(self, bufsize: int) -> tuple[int, int, bytes]:
447
+ palette_data = self._write_palette()
448
+
449
+ offset = 20 + 16 * 4 * 2 + len(palette_data)
450
+ data = struct.pack("<16I", offset, *((0,) * 15))
451
+
452
+ assert self.im is not None
453
+ w, h = self.im.size
454
+ data += struct.pack("<16I", w * h, *((0,) * 15))
455
+
456
+ data += palette_data
457
+
458
+ for y in range(h):
459
+ for x in range(w):
460
+ data += struct.pack("<B", self.im.getpixel((x, y)))
461
+
462
+ return len(data), 0, data
463
+
464
+
465
+ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
466
+ if im.mode != "P":
467
+ msg = "Unsupported BLP image mode"
468
+ raise ValueError(msg)
469
+
470
+ magic = b"BLP1" if im.encoderinfo.get("blp_version") == "BLP1" else b"BLP2"
471
+ fp.write(magic)
472
+
473
+ assert im.palette is not None
474
+ fp.write(struct.pack("<i", 1)) # Uncompressed or DirectX compression
475
+
476
+ alpha_depth = 1 if im.palette.mode == "RGBA" else 0
477
+ if magic == b"BLP1":
478
+ fp.write(struct.pack("<L", alpha_depth))
479
+ else:
480
+ fp.write(struct.pack("<b", Encoding.UNCOMPRESSED))
481
+ fp.write(struct.pack("<b", alpha_depth))
482
+ fp.write(struct.pack("<b", 0)) # alpha encoding
483
+ fp.write(struct.pack("<b", 0)) # mips
484
+ fp.write(struct.pack("<II", *im.size))
485
+ if magic == b"BLP1":
486
+ fp.write(struct.pack("<i", 5))
487
+ fp.write(struct.pack("<i", 0))
488
+
489
+ ImageFile._save(im, fp, [ImageFile._Tile("BLP", (0, 0) + im.size, 0, im.mode)])
490
+
491
+
492
+ Image.register_open(BlpImageFile.format, BlpImageFile, _accept)
493
+ Image.register_extension(BlpImageFile.format, ".blp")
494
+ Image.register_decoder("BLP1", BLP1Decoder)
495
+ Image.register_decoder("BLP2", BLP2Decoder)
496
+
497
+ Image.register_save(BlpImageFile.format, _save)
498
+ Image.register_encoder("BLP", BLPEncoder)
.venv/lib/python3.11/site-packages/PIL/BmpImagePlugin.py ADDED
@@ -0,0 +1,514 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # BMP file handler
6
+ #
7
+ # Windows (and OS/2) native bitmap storage format.
8
+ #
9
+ # history:
10
+ # 1995-09-01 fl Created
11
+ # 1996-04-30 fl Added save
12
+ # 1997-08-27 fl Fixed save of 1-bit images
13
+ # 1998-03-06 fl Load P images as L where possible
14
+ # 1998-07-03 fl Load P images as 1 where possible
15
+ # 1998-12-29 fl Handle small palettes
16
+ # 2002-12-30 fl Fixed load of 1-bit palette images
17
+ # 2003-04-21 fl Fixed load of 1-bit monochrome images
18
+ # 2003-04-23 fl Added limited support for BI_BITFIELDS compression
19
+ #
20
+ # Copyright (c) 1997-2003 by Secret Labs AB
21
+ # Copyright (c) 1995-2003 by Fredrik Lundh
22
+ #
23
+ # See the README file for information on usage and redistribution.
24
+ #
25
+ from __future__ import annotations
26
+
27
+ import os
28
+ from typing import IO, Any
29
+
30
+ from . import Image, ImageFile, ImagePalette
31
+ from ._binary import i16le as i16
32
+ from ._binary import i32le as i32
33
+ from ._binary import o8
34
+ from ._binary import o16le as o16
35
+ from ._binary import o32le as o32
36
+
37
+ #
38
+ # --------------------------------------------------------------------
39
+ # Read BMP file
40
+
41
+ BIT2MODE = {
42
+ # bits => mode, rawmode
43
+ 1: ("P", "P;1"),
44
+ 4: ("P", "P;4"),
45
+ 8: ("P", "P"),
46
+ 16: ("RGB", "BGR;15"),
47
+ 24: ("RGB", "BGR"),
48
+ 32: ("RGB", "BGRX"),
49
+ }
50
+
51
+ USE_RAW_ALPHA = False
52
+
53
+
54
+ def _accept(prefix: bytes) -> bool:
55
+ return prefix.startswith(b"BM")
56
+
57
+
58
+ def _dib_accept(prefix: bytes) -> bool:
59
+ return i32(prefix) in [12, 40, 52, 56, 64, 108, 124]
60
+
61
+
62
+ # =============================================================================
63
+ # Image plugin for the Windows BMP format.
64
+ # =============================================================================
65
+ class BmpImageFile(ImageFile.ImageFile):
66
+ """Image plugin for the Windows Bitmap format (BMP)"""
67
+
68
+ # ------------------------------------------------------------- Description
69
+ format_description = "Windows Bitmap"
70
+ format = "BMP"
71
+
72
+ # -------------------------------------------------- BMP Compression values
73
+ COMPRESSIONS = {"RAW": 0, "RLE8": 1, "RLE4": 2, "BITFIELDS": 3, "JPEG": 4, "PNG": 5}
74
+ for k, v in COMPRESSIONS.items():
75
+ vars()[k] = v
76
+
77
+ def _bitmap(self, header: int = 0, offset: int = 0) -> None:
78
+ """Read relevant info about the BMP"""
79
+ assert self.fp is not None
80
+ read, seek = self.fp.read, self.fp.seek
81
+ if header:
82
+ seek(header)
83
+ # read bmp header size @offset 14 (this is part of the header size)
84
+ file_info: dict[str, bool | int | tuple[int, ...]] = {
85
+ "header_size": i32(read(4)),
86
+ "direction": -1,
87
+ }
88
+
89
+ # -------------------- If requested, read header at a specific position
90
+ # read the rest of the bmp header, without its size
91
+ assert isinstance(file_info["header_size"], int)
92
+ header_data = ImageFile._safe_read(self.fp, file_info["header_size"] - 4)
93
+
94
+ # ------------------------------- Windows Bitmap v2, IBM OS/2 Bitmap v1
95
+ # ----- This format has different offsets because of width/height types
96
+ # 12: BITMAPCOREHEADER/OS21XBITMAPHEADER
97
+ if file_info["header_size"] == 12:
98
+ file_info["width"] = i16(header_data, 0)
99
+ file_info["height"] = i16(header_data, 2)
100
+ file_info["planes"] = i16(header_data, 4)
101
+ file_info["bits"] = i16(header_data, 6)
102
+ file_info["compression"] = self.COMPRESSIONS["RAW"]
103
+ file_info["palette_padding"] = 3
104
+
105
+ # --------------------------------------------- Windows Bitmap v3 to v5
106
+ # 40: BITMAPINFOHEADER
107
+ # 52: BITMAPV2HEADER
108
+ # 56: BITMAPV3HEADER
109
+ # 64: BITMAPCOREHEADER2/OS22XBITMAPHEADER
110
+ # 108: BITMAPV4HEADER
111
+ # 124: BITMAPV5HEADER
112
+ elif file_info["header_size"] in (40, 52, 56, 64, 108, 124):
113
+ file_info["y_flip"] = header_data[7] == 0xFF
114
+ file_info["direction"] = 1 if file_info["y_flip"] else -1
115
+ file_info["width"] = i32(header_data, 0)
116
+ file_info["height"] = (
117
+ i32(header_data, 4)
118
+ if not file_info["y_flip"]
119
+ else 2**32 - i32(header_data, 4)
120
+ )
121
+ file_info["planes"] = i16(header_data, 8)
122
+ file_info["bits"] = i16(header_data, 10)
123
+ file_info["compression"] = i32(header_data, 12)
124
+ # byte size of pixel data
125
+ file_info["data_size"] = i32(header_data, 16)
126
+ file_info["pixels_per_meter"] = (
127
+ i32(header_data, 20),
128
+ i32(header_data, 24),
129
+ )
130
+ file_info["colors"] = i32(header_data, 28)
131
+ file_info["palette_padding"] = 4
132
+ assert isinstance(file_info["pixels_per_meter"], tuple)
133
+ self.info["dpi"] = tuple(x / 39.3701 for x in file_info["pixels_per_meter"])
134
+ if file_info["compression"] == self.COMPRESSIONS["BITFIELDS"]:
135
+ masks = ["r_mask", "g_mask", "b_mask"]
136
+ if len(header_data) >= 48:
137
+ if len(header_data) >= 52:
138
+ masks.append("a_mask")
139
+ else:
140
+ file_info["a_mask"] = 0x0
141
+ for idx, mask in enumerate(masks):
142
+ file_info[mask] = i32(header_data, 36 + idx * 4)
143
+ else:
144
+ # 40 byte headers only have the three components in the
145
+ # bitfields masks, ref:
146
+ # https://msdn.microsoft.com/en-us/library/windows/desktop/dd183376(v=vs.85).aspx
147
+ # See also
148
+ # https://github.com/python-pillow/Pillow/issues/1293
149
+ # There is a 4th component in the RGBQuad, in the alpha
150
+ # location, but it is listed as a reserved component,
151
+ # and it is not generally an alpha channel
152
+ file_info["a_mask"] = 0x0
153
+ for mask in masks:
154
+ file_info[mask] = i32(read(4))
155
+ assert isinstance(file_info["r_mask"], int)
156
+ assert isinstance(file_info["g_mask"], int)
157
+ assert isinstance(file_info["b_mask"], int)
158
+ assert isinstance(file_info["a_mask"], int)
159
+ file_info["rgb_mask"] = (
160
+ file_info["r_mask"],
161
+ file_info["g_mask"],
162
+ file_info["b_mask"],
163
+ )
164
+ file_info["rgba_mask"] = (
165
+ file_info["r_mask"],
166
+ file_info["g_mask"],
167
+ file_info["b_mask"],
168
+ file_info["a_mask"],
169
+ )
170
+ else:
171
+ msg = f"Unsupported BMP header type ({file_info['header_size']})"
172
+ raise OSError(msg)
173
+
174
+ # ------------------ Special case : header is reported 40, which
175
+ # ---------------------- is shorter than real size for bpp >= 16
176
+ assert isinstance(file_info["width"], int)
177
+ assert isinstance(file_info["height"], int)
178
+ self._size = file_info["width"], file_info["height"]
179
+
180
+ # ------- If color count was not found in the header, compute from bits
181
+ assert isinstance(file_info["bits"], int)
182
+ if not file_info.get("colors", 0):
183
+ file_info["colors"] = 1 << file_info["bits"]
184
+ assert isinstance(file_info["palette_padding"], int)
185
+ assert isinstance(file_info["colors"], int)
186
+ if offset == 14 + file_info["header_size"] and file_info["bits"] <= 8:
187
+ offset += file_info["palette_padding"] * file_info["colors"]
188
+
189
+ # ---------------------- Check bit depth for unusual unsupported values
190
+ self._mode, raw_mode = BIT2MODE.get(file_info["bits"], ("", ""))
191
+ if not self.mode:
192
+ msg = f"Unsupported BMP pixel depth ({file_info['bits']})"
193
+ raise OSError(msg)
194
+
195
+ # ---------------- Process BMP with Bitfields compression (not palette)
196
+ decoder_name = "raw"
197
+ if file_info["compression"] == self.COMPRESSIONS["BITFIELDS"]:
198
+ SUPPORTED: dict[int, list[tuple[int, ...]]] = {
199
+ 32: [
200
+ (0xFF0000, 0xFF00, 0xFF, 0x0),
201
+ (0xFF000000, 0xFF0000, 0xFF00, 0x0),
202
+ (0xFF000000, 0xFF00, 0xFF, 0x0),
203
+ (0xFF000000, 0xFF0000, 0xFF00, 0xFF),
204
+ (0xFF, 0xFF00, 0xFF0000, 0xFF000000),
205
+ (0xFF0000, 0xFF00, 0xFF, 0xFF000000),
206
+ (0xFF000000, 0xFF00, 0xFF, 0xFF0000),
207
+ (0x0, 0x0, 0x0, 0x0),
208
+ ],
209
+ 24: [(0xFF0000, 0xFF00, 0xFF)],
210
+ 16: [(0xF800, 0x7E0, 0x1F), (0x7C00, 0x3E0, 0x1F)],
211
+ }
212
+ MASK_MODES = {
213
+ (32, (0xFF0000, 0xFF00, 0xFF, 0x0)): "BGRX",
214
+ (32, (0xFF000000, 0xFF0000, 0xFF00, 0x0)): "XBGR",
215
+ (32, (0xFF000000, 0xFF00, 0xFF, 0x0)): "BGXR",
216
+ (32, (0xFF000000, 0xFF0000, 0xFF00, 0xFF)): "ABGR",
217
+ (32, (0xFF, 0xFF00, 0xFF0000, 0xFF000000)): "RGBA",
218
+ (32, (0xFF0000, 0xFF00, 0xFF, 0xFF000000)): "BGRA",
219
+ (32, (0xFF000000, 0xFF00, 0xFF, 0xFF0000)): "BGAR",
220
+ (32, (0x0, 0x0, 0x0, 0x0)): "BGRA",
221
+ (24, (0xFF0000, 0xFF00, 0xFF)): "BGR",
222
+ (16, (0xF800, 0x7E0, 0x1F)): "BGR;16",
223
+ (16, (0x7C00, 0x3E0, 0x1F)): "BGR;15",
224
+ }
225
+ if file_info["bits"] in SUPPORTED:
226
+ if (
227
+ file_info["bits"] == 32
228
+ and file_info["rgba_mask"] in SUPPORTED[file_info["bits"]]
229
+ ):
230
+ assert isinstance(file_info["rgba_mask"], tuple)
231
+ raw_mode = MASK_MODES[(file_info["bits"], file_info["rgba_mask"])]
232
+ self._mode = "RGBA" if "A" in raw_mode else self.mode
233
+ elif (
234
+ file_info["bits"] in (24, 16)
235
+ and file_info["rgb_mask"] in SUPPORTED[file_info["bits"]]
236
+ ):
237
+ assert isinstance(file_info["rgb_mask"], tuple)
238
+ raw_mode = MASK_MODES[(file_info["bits"], file_info["rgb_mask"])]
239
+ else:
240
+ msg = "Unsupported BMP bitfields layout"
241
+ raise OSError(msg)
242
+ else:
243
+ msg = "Unsupported BMP bitfields layout"
244
+ raise OSError(msg)
245
+ elif file_info["compression"] == self.COMPRESSIONS["RAW"]:
246
+ if file_info["bits"] == 32 and (
247
+ header == 22 or USE_RAW_ALPHA # 32-bit .cur offset
248
+ ):
249
+ raw_mode, self._mode = "BGRA", "RGBA"
250
+ elif file_info["compression"] in (
251
+ self.COMPRESSIONS["RLE8"],
252
+ self.COMPRESSIONS["RLE4"],
253
+ ):
254
+ decoder_name = "bmp_rle"
255
+ else:
256
+ msg = f"Unsupported BMP compression ({file_info['compression']})"
257
+ raise OSError(msg)
258
+
259
+ # --------------- Once the header is processed, process the palette/LUT
260
+ if self.mode == "P": # Paletted for 1, 4 and 8 bit images
261
+ # ---------------------------------------------------- 1-bit images
262
+ if not (0 < file_info["colors"] <= 65536):
263
+ msg = f"Unsupported BMP Palette size ({file_info['colors']})"
264
+ raise OSError(msg)
265
+ else:
266
+ padding = file_info["palette_padding"]
267
+ palette = read(padding * file_info["colors"])
268
+ grayscale = True
269
+ indices = (
270
+ (0, 255)
271
+ if file_info["colors"] == 2
272
+ else list(range(file_info["colors"]))
273
+ )
274
+
275
+ # ----------------- Check if grayscale and ignore palette if so
276
+ for ind, val in enumerate(indices):
277
+ rgb = palette[ind * padding : ind * padding + 3]
278
+ if rgb != o8(val) * 3:
279
+ grayscale = False
280
+
281
+ # ------- If all colors are gray, white or black, ditch palette
282
+ if grayscale:
283
+ self._mode = "1" if file_info["colors"] == 2 else "L"
284
+ raw_mode = self.mode
285
+ else:
286
+ self._mode = "P"
287
+ self.palette = ImagePalette.raw(
288
+ "BGRX" if padding == 4 else "BGR", palette
289
+ )
290
+
291
+ # ---------------------------- Finally set the tile data for the plugin
292
+ self.info["compression"] = file_info["compression"]
293
+ args: list[Any] = [raw_mode]
294
+ if decoder_name == "bmp_rle":
295
+ args.append(file_info["compression"] == self.COMPRESSIONS["RLE4"])
296
+ else:
297
+ assert isinstance(file_info["width"], int)
298
+ args.append(((file_info["width"] * file_info["bits"] + 31) >> 3) & (~3))
299
+ args.append(file_info["direction"])
300
+ self.tile = [
301
+ ImageFile._Tile(
302
+ decoder_name,
303
+ (0, 0, file_info["width"], file_info["height"]),
304
+ offset or self.fp.tell(),
305
+ tuple(args),
306
+ )
307
+ ]
308
+
309
+ def _open(self) -> None:
310
+ """Open file, check magic number and read header"""
311
+ # read 14 bytes: magic number, filesize, reserved, header final offset
312
+ assert self.fp is not None
313
+ head_data = self.fp.read(14)
314
+ # choke if the file does not have the required magic bytes
315
+ if not _accept(head_data):
316
+ msg = "Not a BMP file"
317
+ raise SyntaxError(msg)
318
+ # read the start position of the BMP image data (u32)
319
+ offset = i32(head_data, 10)
320
+ # load bitmap information (offset=raster info)
321
+ self._bitmap(offset=offset)
322
+
323
+
324
+ class BmpRleDecoder(ImageFile.PyDecoder):
325
+ _pulls_fd = True
326
+
327
+ def decode(self, buffer: Image.DecoderInput) -> tuple[int, int]:
328
+ assert self.fd is not None
329
+ rle4 = self.args[1]
330
+ data = bytearray()
331
+ x = 0
332
+ dest_length = self.state.xsize * self.state.ysize
333
+ while len(data) < dest_length:
334
+ pixels = self.fd.read(1)
335
+ byte = self.fd.read(1)
336
+ if not pixels or not byte:
337
+ break
338
+ num_pixels = pixels[0]
339
+ if num_pixels:
340
+ # encoded mode
341
+ if x + num_pixels > self.state.xsize:
342
+ # Too much data for row
343
+ num_pixels = max(0, self.state.xsize - x)
344
+ if rle4:
345
+ first_pixel = o8(byte[0] >> 4)
346
+ second_pixel = o8(byte[0] & 0x0F)
347
+ for index in range(num_pixels):
348
+ if index % 2 == 0:
349
+ data += first_pixel
350
+ else:
351
+ data += second_pixel
352
+ else:
353
+ data += byte * num_pixels
354
+ x += num_pixels
355
+ else:
356
+ if byte[0] == 0:
357
+ # end of line
358
+ while len(data) % self.state.xsize != 0:
359
+ data += b"\x00"
360
+ x = 0
361
+ elif byte[0] == 1:
362
+ # end of bitmap
363
+ break
364
+ elif byte[0] == 2:
365
+ # delta
366
+ bytes_read = self.fd.read(2)
367
+ if len(bytes_read) < 2:
368
+ break
369
+ right, up = bytes_read
370
+ data += b"\x00" * (right + up * self.state.xsize)
371
+ x = len(data) % self.state.xsize
372
+ else:
373
+ # absolute mode
374
+ if rle4:
375
+ # 2 pixels per byte
376
+ byte_count = byte[0] // 2
377
+ bytes_read = self.fd.read(byte_count)
378
+ for byte_read in bytes_read:
379
+ data += o8(byte_read >> 4)
380
+ data += o8(byte_read & 0x0F)
381
+ else:
382
+ byte_count = byte[0]
383
+ bytes_read = self.fd.read(byte_count)
384
+ data += bytes_read
385
+ if len(bytes_read) < byte_count:
386
+ break
387
+ x += byte[0]
388
+
389
+ # align to 16-bit word boundary
390
+ if self.fd.tell() % 2 != 0:
391
+ self.fd.seek(1, os.SEEK_CUR)
392
+ rawmode = "L" if self.mode == "L" else "P"
393
+ self.set_as_raw(bytes(data), rawmode, (0, self.args[-1]))
394
+ return -1, 0
395
+
396
+
397
+ # =============================================================================
398
+ # Image plugin for the DIB format (BMP alias)
399
+ # =============================================================================
400
+ class DibImageFile(BmpImageFile):
401
+ format = "DIB"
402
+ format_description = "Windows Bitmap"
403
+
404
+ def _open(self) -> None:
405
+ self._bitmap()
406
+
407
+
408
+ #
409
+ # --------------------------------------------------------------------
410
+ # Write BMP file
411
+
412
+
413
+ SAVE = {
414
+ "1": ("1", 1, 2),
415
+ "L": ("L", 8, 256),
416
+ "P": ("P", 8, 256),
417
+ "RGB": ("BGR", 24, 0),
418
+ "RGBA": ("BGRA", 32, 0),
419
+ }
420
+
421
+
422
+ def _dib_save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
423
+ _save(im, fp, filename, False)
424
+
425
+
426
+ def _save(
427
+ im: Image.Image, fp: IO[bytes], filename: str | bytes, bitmap_header: bool = True
428
+ ) -> None:
429
+ try:
430
+ rawmode, bits, colors = SAVE[im.mode]
431
+ except KeyError as e:
432
+ msg = f"cannot write mode {im.mode} as BMP"
433
+ raise OSError(msg) from e
434
+
435
+ info = im.encoderinfo
436
+
437
+ dpi = info.get("dpi", (96, 96))
438
+
439
+ # 1 meter == 39.3701 inches
440
+ ppm = tuple(int(x * 39.3701 + 0.5) for x in dpi)
441
+
442
+ stride = ((im.size[0] * bits + 7) // 8 + 3) & (~3)
443
+ header = 40 # or 64 for OS/2 version 2
444
+ image = stride * im.size[1]
445
+
446
+ if im.mode == "1":
447
+ palette = b"".join(o8(i) * 3 + b"\x00" for i in (0, 255))
448
+ elif im.mode == "L":
449
+ palette = b"".join(o8(i) * 3 + b"\x00" for i in range(256))
450
+ elif im.mode == "P":
451
+ palette = im.im.getpalette("RGB", "BGRX")
452
+ colors = len(palette) // 4
453
+ else:
454
+ palette = None
455
+
456
+ # bitmap header
457
+ if bitmap_header:
458
+ offset = 14 + header + colors * 4
459
+ file_size = offset + image
460
+ if file_size > 2**32 - 1:
461
+ msg = "File size is too large for the BMP format"
462
+ raise ValueError(msg)
463
+ fp.write(
464
+ b"BM" # file type (magic)
465
+ + o32(file_size) # file size
466
+ + o32(0) # reserved
467
+ + o32(offset) # image data offset
468
+ )
469
+
470
+ # bitmap info header
471
+ fp.write(
472
+ o32(header) # info header size
473
+ + o32(im.size[0]) # width
474
+ + o32(im.size[1]) # height
475
+ + o16(1) # planes
476
+ + o16(bits) # depth
477
+ + o32(0) # compression (0=uncompressed)
478
+ + o32(image) # size of bitmap
479
+ + o32(ppm[0]) # resolution
480
+ + o32(ppm[1]) # resolution
481
+ + o32(colors) # colors used
482
+ + o32(colors) # colors important
483
+ )
484
+
485
+ fp.write(b"\0" * (header - 40)) # padding (for OS/2 format)
486
+
487
+ if palette:
488
+ fp.write(palette)
489
+
490
+ ImageFile._save(
491
+ im, fp, [ImageFile._Tile("raw", (0, 0) + im.size, 0, (rawmode, stride, -1))]
492
+ )
493
+
494
+
495
+ #
496
+ # --------------------------------------------------------------------
497
+ # Registry
498
+
499
+
500
+ Image.register_open(BmpImageFile.format, BmpImageFile, _accept)
501
+ Image.register_save(BmpImageFile.format, _save)
502
+
503
+ Image.register_extension(BmpImageFile.format, ".bmp")
504
+
505
+ Image.register_mime(BmpImageFile.format, "image/bmp")
506
+
507
+ Image.register_decoder("bmp_rle", BmpRleDecoder)
508
+
509
+ Image.register_open(DibImageFile.format, DibImageFile, _dib_accept)
510
+ Image.register_save(DibImageFile.format, _dib_save)
511
+
512
+ Image.register_extension(DibImageFile.format, ".dib")
513
+
514
+ Image.register_mime(DibImageFile.format, "image/bmp")
.venv/lib/python3.11/site-packages/PIL/BufrStubImagePlugin.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library
3
+ # $Id$
4
+ #
5
+ # BUFR stub adapter
6
+ #
7
+ # Copyright (c) 1996-2003 by Fredrik Lundh
8
+ #
9
+ # See the README file for information on usage and redistribution.
10
+ #
11
+ from __future__ import annotations
12
+
13
+ import os
14
+ from typing import IO
15
+
16
+ from . import Image, ImageFile
17
+
18
+ _handler = None
19
+
20
+
21
+ def register_handler(handler: ImageFile.StubHandler | None) -> None:
22
+ """
23
+ Install application-specific BUFR image handler.
24
+
25
+ :param handler: Handler object.
26
+ """
27
+ global _handler
28
+ _handler = handler
29
+
30
+
31
+ # --------------------------------------------------------------------
32
+ # Image adapter
33
+
34
+
35
+ def _accept(prefix: bytes) -> bool:
36
+ return prefix.startswith((b"BUFR", b"ZCZC"))
37
+
38
+
39
+ class BufrStubImageFile(ImageFile.StubImageFile):
40
+ format = "BUFR"
41
+ format_description = "BUFR"
42
+
43
+ def _open(self) -> None:
44
+ assert self.fp is not None
45
+ if not _accept(self.fp.read(4)):
46
+ msg = "Not a BUFR file"
47
+ raise SyntaxError(msg)
48
+
49
+ self.fp.seek(-4, os.SEEK_CUR)
50
+
51
+ # make something up
52
+ self._mode = "F"
53
+ self._size = 1, 1
54
+
55
+ def _load(self) -> ImageFile.StubHandler | None:
56
+ return _handler
57
+
58
+
59
+ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
60
+ if _handler is None or not hasattr(_handler, "save"):
61
+ msg = "BUFR save handler not installed"
62
+ raise OSError(msg)
63
+ _handler.save(im, fp, filename)
64
+
65
+
66
+ # --------------------------------------------------------------------
67
+ # Registry
68
+
69
+ Image.register_open(BufrStubImageFile.format, BufrStubImageFile, _accept)
70
+ Image.register_save(BufrStubImageFile.format, _save)
71
+
72
+ Image.register_extension(BufrStubImageFile.format, ".bufr")
.venv/lib/python3.11/site-packages/PIL/ContainerIO.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # a class to read from a container file
6
+ #
7
+ # History:
8
+ # 1995-06-18 fl Created
9
+ # 1995-09-07 fl Added readline(), readlines()
10
+ #
11
+ # Copyright (c) 1997-2001 by Secret Labs AB
12
+ # Copyright (c) 1995 by Fredrik Lundh
13
+ #
14
+ # See the README file for information on usage and redistribution.
15
+ #
16
+ from __future__ import annotations
17
+
18
+ import io
19
+ from collections.abc import Iterable
20
+ from typing import IO, AnyStr, NoReturn
21
+
22
+
23
+ class ContainerIO(IO[AnyStr]):
24
+ """
25
+ A file object that provides read access to a part of an existing
26
+ file (for example a TAR file).
27
+ """
28
+
29
+ def __init__(self, file: IO[AnyStr], offset: int, length: int) -> None:
30
+ """
31
+ Create file object.
32
+
33
+ :param file: Existing file.
34
+ :param offset: Start of region, in bytes.
35
+ :param length: Size of region, in bytes.
36
+ """
37
+ self.fh: IO[AnyStr] = file
38
+ self.pos = 0
39
+ self.offset = offset
40
+ self.length = length
41
+ self.fh.seek(offset)
42
+
43
+ ##
44
+ # Always false.
45
+
46
+ def isatty(self) -> bool:
47
+ return False
48
+
49
+ def seekable(self) -> bool:
50
+ return True
51
+
52
+ def seek(self, offset: int, mode: int = io.SEEK_SET) -> int:
53
+ """
54
+ Move file pointer.
55
+
56
+ :param offset: Offset in bytes.
57
+ :param mode: Starting position. Use 0 for beginning of region, 1
58
+ for current offset, and 2 for end of region. You cannot move
59
+ the pointer outside the defined region.
60
+ :returns: Offset from start of region, in bytes.
61
+ """
62
+ if mode == 1:
63
+ self.pos = self.pos + offset
64
+ elif mode == 2:
65
+ self.pos = self.length + offset
66
+ else:
67
+ self.pos = offset
68
+ # clamp
69
+ self.pos = max(0, min(self.pos, self.length))
70
+ self.fh.seek(self.offset + self.pos)
71
+ return self.pos
72
+
73
+ def tell(self) -> int:
74
+ """
75
+ Get current file pointer.
76
+
77
+ :returns: Offset from start of region, in bytes.
78
+ """
79
+ return self.pos
80
+
81
+ def readable(self) -> bool:
82
+ return True
83
+
84
+ def read(self, n: int = -1) -> AnyStr:
85
+ """
86
+ Read data.
87
+
88
+ :param n: Number of bytes to read. If omitted, zero or negative,
89
+ read until end of region.
90
+ :returns: An 8-bit string.
91
+ """
92
+ if n > 0:
93
+ n = min(n, self.length - self.pos)
94
+ else:
95
+ n = self.length - self.pos
96
+ if n <= 0: # EOF
97
+ return b"" if "b" in self.fh.mode else "" # type: ignore[return-value]
98
+ self.pos = self.pos + n
99
+ return self.fh.read(n)
100
+
101
+ def readline(self, n: int = -1) -> AnyStr:
102
+ """
103
+ Read a line of text.
104
+
105
+ :param n: Number of bytes to read. If omitted, zero or negative,
106
+ read until end of line.
107
+ :returns: An 8-bit string.
108
+ """
109
+ s: AnyStr = b"" if "b" in self.fh.mode else "" # type: ignore[assignment]
110
+ newline_character = b"\n" if "b" in self.fh.mode else "\n"
111
+ while True:
112
+ c = self.read(1)
113
+ if not c:
114
+ break
115
+ s = s + c
116
+ if c == newline_character or len(s) == n:
117
+ break
118
+ return s
119
+
120
+ def readlines(self, n: int | None = -1) -> list[AnyStr]:
121
+ """
122
+ Read multiple lines of text.
123
+
124
+ :param n: Number of lines to read. If omitted, zero, negative or None,
125
+ read until end of region.
126
+ :returns: A list of 8-bit strings.
127
+ """
128
+ lines = []
129
+ while True:
130
+ s = self.readline()
131
+ if not s:
132
+ break
133
+ lines.append(s)
134
+ if len(lines) == n:
135
+ break
136
+ return lines
137
+
138
+ def writable(self) -> bool:
139
+ return False
140
+
141
+ def write(self, b: AnyStr) -> NoReturn:
142
+ raise NotImplementedError()
143
+
144
+ def writelines(self, lines: Iterable[AnyStr]) -> NoReturn:
145
+ raise NotImplementedError()
146
+
147
+ def truncate(self, size: int | None = None) -> int:
148
+ raise NotImplementedError()
149
+
150
+ def __enter__(self) -> ContainerIO[AnyStr]:
151
+ return self
152
+
153
+ def __exit__(self, *args: object) -> None:
154
+ self.close()
155
+
156
+ def __iter__(self) -> ContainerIO[AnyStr]:
157
+ return self
158
+
159
+ def __next__(self) -> AnyStr:
160
+ line = self.readline()
161
+ if not line:
162
+ msg = "end of region"
163
+ raise StopIteration(msg)
164
+ return line
165
+
166
+ def fileno(self) -> int:
167
+ return self.fh.fileno()
168
+
169
+ def flush(self) -> None:
170
+ self.fh.flush()
171
+
172
+ def close(self) -> None:
173
+ self.fh.close()
.venv/lib/python3.11/site-packages/PIL/CurImagePlugin.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, ImageOps
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
+ self._masked = self.mode in ("1", "L")
65
+ if self._masked:
66
+ self._rawmode = self.mode
67
+ self._mode = "LA"
68
+
69
+ # patch up the bitmap height
70
+ self._size = self.width, self.height // 2
71
+ if not self._masked:
72
+ self.tile = [self.tile[0]._replace(extents=(0, 0) + self.size)]
73
+
74
+ def load_prepare(self) -> None:
75
+ if self._masked:
76
+ self._mode = self._rawmode
77
+ self._size = self.width, self.height * 2
78
+ super().load_prepare()
79
+
80
+ def load_end(self) -> None:
81
+ if not self._masked:
82
+ return
83
+ self._mode = "LA"
84
+ new_height = self.height // 2
85
+
86
+ and_mask = self.im.crop((0, 0, self.width, new_height))
87
+ xor_mask = self.im.crop((0, new_height, self.width, self.height))
88
+
89
+ self._size = self.width, new_height
90
+ self._im = Image.core.fill(self.mode, self.size)
91
+ self._im.paste(
92
+ xor_mask.convert(self.mode),
93
+ (0, 0) + self.size,
94
+ ImageOps.invert(Image.Image()._new(and_mask)).im,
95
+ )
96
+
97
+
98
+ #
99
+ # --------------------------------------------------------------------
100
+
101
+ Image.register_open(CurImageFile.format, CurImageFile, _accept)
102
+
103
+ Image.register_extension(CurImageFile.format, ".cur")
.venv/lib/python3.11/site-packages/PIL/DcxImagePlugin.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # DCX file handling
6
+ #
7
+ # DCX is a container file format defined by Intel, commonly used
8
+ # for fax applications. Each DCX file consists of a directory
9
+ # (a list of file offsets) followed by a set of (usually 1-bit)
10
+ # PCX files.
11
+ #
12
+ # History:
13
+ # 1995-09-09 fl Created
14
+ # 1996-03-20 fl Properly derived from PcxImageFile.
15
+ # 1998-07-15 fl Renamed offset attribute to avoid name clash
16
+ # 2002-07-30 fl Fixed file handling
17
+ #
18
+ # Copyright (c) 1997-98 by Secret Labs AB.
19
+ # Copyright (c) 1995-96 by Fredrik Lundh.
20
+ #
21
+ # See the README file for information on usage and redistribution.
22
+ #
23
+ from __future__ import annotations
24
+
25
+ from . import Image
26
+ from ._binary import i32le as i32
27
+ from ._util import DeferredError
28
+ from .PcxImagePlugin import PcxImageFile
29
+
30
+ MAGIC = 0x3ADE68B1 # QUIZ: what's this value, then?
31
+
32
+
33
+ def _accept(prefix: bytes) -> bool:
34
+ return len(prefix) >= 4 and i32(prefix) == MAGIC
35
+
36
+
37
+ ##
38
+ # Image plugin for the Intel DCX format.
39
+
40
+
41
+ class DcxImageFile(PcxImageFile):
42
+ format = "DCX"
43
+ format_description = "Intel DCX"
44
+ _close_exclusive_fp_after_loading = False
45
+
46
+ def _open(self) -> None:
47
+ # Header
48
+ assert self.fp is not None
49
+ s = self.fp.read(4)
50
+ if not _accept(s):
51
+ msg = "not a DCX file"
52
+ raise SyntaxError(msg)
53
+
54
+ # Component directory
55
+ self._offset = []
56
+ for i in range(1024):
57
+ offset = i32(self.fp.read(4))
58
+ if not offset:
59
+ break
60
+ self._offset.append(offset)
61
+
62
+ self._fp = self.fp
63
+ self.frame = -1
64
+ self.n_frames = len(self._offset)
65
+ self.is_animated = self.n_frames > 1
66
+ self.seek(0)
67
+
68
+ def seek(self, frame: int) -> None:
69
+ if not self._seek_check(frame):
70
+ return
71
+ if isinstance(self._fp, DeferredError):
72
+ raise self._fp.ex
73
+ self.frame = frame
74
+ self.fp = self._fp
75
+ self.fp.seek(self._offset[frame])
76
+ PcxImageFile._open(self)
77
+
78
+ def tell(self) -> int:
79
+ return self.frame
80
+
81
+
82
+ Image.register_open(DcxImageFile.format, DcxImageFile, _accept)
83
+
84
+ Image.register_extension(DcxImageFile.format, ".dcx")
.venv/lib/python3.11/site-packages/PIL/DdsImagePlugin.py ADDED
@@ -0,0 +1,632 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A Pillow plugin for .dds files (S3TC-compressed aka DXTC)
3
+ Jerome Leclanche <jerome@leclan.ch>
4
+
5
+ Documentation:
6
+ https://web.archive.org/web/20170802060935/http://oss.sgi.com/projects/ogl-sample/registry/EXT/texture_compression_s3tc.txt
7
+
8
+ The contents of this file are hereby released in the public domain (CC0)
9
+ Full text of the CC0 license:
10
+ https://creativecommons.org/publicdomain/zero/1.0/
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import struct
16
+ import sys
17
+ from enum import IntEnum, IntFlag
18
+ from typing import IO
19
+
20
+ from . import Image, ImageFile, ImagePalette
21
+ from ._binary import i32le as i32
22
+ from ._binary import o8
23
+ from ._binary import o32le as o32
24
+
25
+ # Magic ("DDS ")
26
+ DDS_MAGIC = 0x20534444
27
+
28
+
29
+ # DDS flags
30
+ class DDSD(IntFlag):
31
+ CAPS = 0x1
32
+ HEIGHT = 0x2
33
+ WIDTH = 0x4
34
+ PITCH = 0x8
35
+ PIXELFORMAT = 0x1000
36
+ MIPMAPCOUNT = 0x20000
37
+ LINEARSIZE = 0x80000
38
+ DEPTH = 0x800000
39
+
40
+
41
+ # DDS caps
42
+ class DDSCAPS(IntFlag):
43
+ COMPLEX = 0x8
44
+ TEXTURE = 0x1000
45
+ MIPMAP = 0x400000
46
+
47
+
48
+ class DDSCAPS2(IntFlag):
49
+ CUBEMAP = 0x200
50
+ CUBEMAP_POSITIVEX = 0x400
51
+ CUBEMAP_NEGATIVEX = 0x800
52
+ CUBEMAP_POSITIVEY = 0x1000
53
+ CUBEMAP_NEGATIVEY = 0x2000
54
+ CUBEMAP_POSITIVEZ = 0x4000
55
+ CUBEMAP_NEGATIVEZ = 0x8000
56
+ VOLUME = 0x200000
57
+
58
+
59
+ # Pixel Format
60
+ class DDPF(IntFlag):
61
+ ALPHAPIXELS = 0x1
62
+ ALPHA = 0x2
63
+ FOURCC = 0x4
64
+ PALETTEINDEXED8 = 0x20
65
+ RGB = 0x40
66
+ LUMINANCE = 0x20000
67
+
68
+
69
+ # dxgiformat.h
70
+ class DXGI_FORMAT(IntEnum):
71
+ UNKNOWN = 0
72
+ R32G32B32A32_TYPELESS = 1
73
+ R32G32B32A32_FLOAT = 2
74
+ R32G32B32A32_UINT = 3
75
+ R32G32B32A32_SINT = 4
76
+ R32G32B32_TYPELESS = 5
77
+ R32G32B32_FLOAT = 6
78
+ R32G32B32_UINT = 7
79
+ R32G32B32_SINT = 8
80
+ R16G16B16A16_TYPELESS = 9
81
+ R16G16B16A16_FLOAT = 10
82
+ R16G16B16A16_UNORM = 11
83
+ R16G16B16A16_UINT = 12
84
+ R16G16B16A16_SNORM = 13
85
+ R16G16B16A16_SINT = 14
86
+ R32G32_TYPELESS = 15
87
+ R32G32_FLOAT = 16
88
+ R32G32_UINT = 17
89
+ R32G32_SINT = 18
90
+ R32G8X24_TYPELESS = 19
91
+ D32_FLOAT_S8X24_UINT = 20
92
+ R32_FLOAT_X8X24_TYPELESS = 21
93
+ X32_TYPELESS_G8X24_UINT = 22
94
+ R10G10B10A2_TYPELESS = 23
95
+ R10G10B10A2_UNORM = 24
96
+ R10G10B10A2_UINT = 25
97
+ R11G11B10_FLOAT = 26
98
+ R8G8B8A8_TYPELESS = 27
99
+ R8G8B8A8_UNORM = 28
100
+ R8G8B8A8_UNORM_SRGB = 29
101
+ R8G8B8A8_UINT = 30
102
+ R8G8B8A8_SNORM = 31
103
+ R8G8B8A8_SINT = 32
104
+ R16G16_TYPELESS = 33
105
+ R16G16_FLOAT = 34
106
+ R16G16_UNORM = 35
107
+ R16G16_UINT = 36
108
+ R16G16_SNORM = 37
109
+ R16G16_SINT = 38
110
+ R32_TYPELESS = 39
111
+ D32_FLOAT = 40
112
+ R32_FLOAT = 41
113
+ R32_UINT = 42
114
+ R32_SINT = 43
115
+ R24G8_TYPELESS = 44
116
+ D24_UNORM_S8_UINT = 45
117
+ R24_UNORM_X8_TYPELESS = 46
118
+ X24_TYPELESS_G8_UINT = 47
119
+ R8G8_TYPELESS = 48
120
+ R8G8_UNORM = 49
121
+ R8G8_UINT = 50
122
+ R8G8_SNORM = 51
123
+ R8G8_SINT = 52
124
+ R16_TYPELESS = 53
125
+ R16_FLOAT = 54
126
+ D16_UNORM = 55
127
+ R16_UNORM = 56
128
+ R16_UINT = 57
129
+ R16_SNORM = 58
130
+ R16_SINT = 59
131
+ R8_TYPELESS = 60
132
+ R8_UNORM = 61
133
+ R8_UINT = 62
134
+ R8_SNORM = 63
135
+ R8_SINT = 64
136
+ A8_UNORM = 65
137
+ R1_UNORM = 66
138
+ R9G9B9E5_SHAREDEXP = 67
139
+ R8G8_B8G8_UNORM = 68
140
+ G8R8_G8B8_UNORM = 69
141
+ BC1_TYPELESS = 70
142
+ BC1_UNORM = 71
143
+ BC1_UNORM_SRGB = 72
144
+ BC2_TYPELESS = 73
145
+ BC2_UNORM = 74
146
+ BC2_UNORM_SRGB = 75
147
+ BC3_TYPELESS = 76
148
+ BC3_UNORM = 77
149
+ BC3_UNORM_SRGB = 78
150
+ BC4_TYPELESS = 79
151
+ BC4_UNORM = 80
152
+ BC4_SNORM = 81
153
+ BC5_TYPELESS = 82
154
+ BC5_UNORM = 83
155
+ BC5_SNORM = 84
156
+ B5G6R5_UNORM = 85
157
+ B5G5R5A1_UNORM = 86
158
+ B8G8R8A8_UNORM = 87
159
+ B8G8R8X8_UNORM = 88
160
+ R10G10B10_XR_BIAS_A2_UNORM = 89
161
+ B8G8R8A8_TYPELESS = 90
162
+ B8G8R8A8_UNORM_SRGB = 91
163
+ B8G8R8X8_TYPELESS = 92
164
+ B8G8R8X8_UNORM_SRGB = 93
165
+ BC6H_TYPELESS = 94
166
+ BC6H_UF16 = 95
167
+ BC6H_SF16 = 96
168
+ BC7_TYPELESS = 97
169
+ BC7_UNORM = 98
170
+ BC7_UNORM_SRGB = 99
171
+ AYUV = 100
172
+ Y410 = 101
173
+ Y416 = 102
174
+ NV12 = 103
175
+ P010 = 104
176
+ P016 = 105
177
+ OPAQUE_420 = 106
178
+ YUY2 = 107
179
+ Y210 = 108
180
+ Y216 = 109
181
+ NV11 = 110
182
+ AI44 = 111
183
+ IA44 = 112
184
+ P8 = 113
185
+ A8P8 = 114
186
+ B4G4R4A4_UNORM = 115
187
+ P208 = 130
188
+ V208 = 131
189
+ V408 = 132
190
+ SAMPLER_FEEDBACK_MIN_MIP_OPAQUE = 189
191
+ SAMPLER_FEEDBACK_MIP_REGION_USED_OPAQUE = 190
192
+
193
+
194
+ class D3DFMT(IntEnum):
195
+ UNKNOWN = 0
196
+ R8G8B8 = 20
197
+ A8R8G8B8 = 21
198
+ X8R8G8B8 = 22
199
+ R5G6B5 = 23
200
+ X1R5G5B5 = 24
201
+ A1R5G5B5 = 25
202
+ A4R4G4B4 = 26
203
+ R3G3B2 = 27
204
+ A8 = 28
205
+ A8R3G3B2 = 29
206
+ X4R4G4B4 = 30
207
+ A2B10G10R10 = 31
208
+ A8B8G8R8 = 32
209
+ X8B8G8R8 = 33
210
+ G16R16 = 34
211
+ A2R10G10B10 = 35
212
+ A16B16G16R16 = 36
213
+ A8P8 = 40
214
+ P8 = 41
215
+ L8 = 50
216
+ A8L8 = 51
217
+ A4L4 = 52
218
+ V8U8 = 60
219
+ L6V5U5 = 61
220
+ X8L8V8U8 = 62
221
+ Q8W8V8U8 = 63
222
+ V16U16 = 64
223
+ A2W10V10U10 = 67
224
+ D16_LOCKABLE = 70
225
+ D32 = 71
226
+ D15S1 = 73
227
+ D24S8 = 75
228
+ D24X8 = 77
229
+ D24X4S4 = 79
230
+ D16 = 80
231
+ D32F_LOCKABLE = 82
232
+ D24FS8 = 83
233
+ D32_LOCKABLE = 84
234
+ S8_LOCKABLE = 85
235
+ L16 = 81
236
+ VERTEXDATA = 100
237
+ INDEX16 = 101
238
+ INDEX32 = 102
239
+ Q16W16V16U16 = 110
240
+ R16F = 111
241
+ G16R16F = 112
242
+ A16B16G16R16F = 113
243
+ R32F = 114
244
+ G32R32F = 115
245
+ A32B32G32R32F = 116
246
+ CxV8U8 = 117
247
+ A1 = 118
248
+ A2B10G10R10_XR_BIAS = 119
249
+ BINARYBUFFER = 199
250
+
251
+ UYVY = i32(b"UYVY")
252
+ R8G8_B8G8 = i32(b"RGBG")
253
+ YUY2 = i32(b"YUY2")
254
+ G8R8_G8B8 = i32(b"GRGB")
255
+ DXT1 = i32(b"DXT1")
256
+ DXT2 = i32(b"DXT2")
257
+ DXT3 = i32(b"DXT3")
258
+ DXT4 = i32(b"DXT4")
259
+ DXT5 = i32(b"DXT5")
260
+ DX10 = i32(b"DX10")
261
+ BC4S = i32(b"BC4S")
262
+ BC4U = i32(b"BC4U")
263
+ BC5S = i32(b"BC5S")
264
+ BC5U = i32(b"BC5U")
265
+ ATI1 = i32(b"ATI1")
266
+ ATI2 = i32(b"ATI2")
267
+ MULTI2_ARGB8 = i32(b"MET1")
268
+
269
+
270
+ # Backward compatibility layer
271
+ module = sys.modules[__name__]
272
+ for item in DDSD:
273
+ assert item.name is not None
274
+ setattr(module, f"DDSD_{item.name}", item.value)
275
+ for item1 in DDSCAPS:
276
+ assert item1.name is not None
277
+ setattr(module, f"DDSCAPS_{item1.name}", item1.value)
278
+ for item2 in DDSCAPS2:
279
+ assert item2.name is not None
280
+ setattr(module, f"DDSCAPS2_{item2.name}", item2.value)
281
+ for item3 in DDPF:
282
+ assert item3.name is not None
283
+ setattr(module, f"DDPF_{item3.name}", item3.value)
284
+
285
+ DDS_FOURCC = DDPF.FOURCC
286
+ DDS_RGB = DDPF.RGB
287
+ DDS_RGBA = DDPF.RGB | DDPF.ALPHAPIXELS
288
+ DDS_LUMINANCE = DDPF.LUMINANCE
289
+ DDS_LUMINANCEA = DDPF.LUMINANCE | DDPF.ALPHAPIXELS
290
+ DDS_ALPHA = DDPF.ALPHA
291
+ DDS_PAL8 = DDPF.PALETTEINDEXED8
292
+
293
+ DDS_HEADER_FLAGS_TEXTURE = DDSD.CAPS | DDSD.HEIGHT | DDSD.WIDTH | DDSD.PIXELFORMAT
294
+ DDS_HEADER_FLAGS_MIPMAP = DDSD.MIPMAPCOUNT
295
+ DDS_HEADER_FLAGS_VOLUME = DDSD.DEPTH
296
+ DDS_HEADER_FLAGS_PITCH = DDSD.PITCH
297
+ DDS_HEADER_FLAGS_LINEARSIZE = DDSD.LINEARSIZE
298
+
299
+ DDS_HEIGHT = DDSD.HEIGHT
300
+ DDS_WIDTH = DDSD.WIDTH
301
+
302
+ DDS_SURFACE_FLAGS_TEXTURE = DDSCAPS.TEXTURE
303
+ DDS_SURFACE_FLAGS_MIPMAP = DDSCAPS.COMPLEX | DDSCAPS.MIPMAP
304
+ DDS_SURFACE_FLAGS_CUBEMAP = DDSCAPS.COMPLEX
305
+
306
+ DDS_CUBEMAP_POSITIVEX = DDSCAPS2.CUBEMAP | DDSCAPS2.CUBEMAP_POSITIVEX
307
+ DDS_CUBEMAP_NEGATIVEX = DDSCAPS2.CUBEMAP | DDSCAPS2.CUBEMAP_NEGATIVEX
308
+ DDS_CUBEMAP_POSITIVEY = DDSCAPS2.CUBEMAP | DDSCAPS2.CUBEMAP_POSITIVEY
309
+ DDS_CUBEMAP_NEGATIVEY = DDSCAPS2.CUBEMAP | DDSCAPS2.CUBEMAP_NEGATIVEY
310
+ DDS_CUBEMAP_POSITIVEZ = DDSCAPS2.CUBEMAP | DDSCAPS2.CUBEMAP_POSITIVEZ
311
+ DDS_CUBEMAP_NEGATIVEZ = DDSCAPS2.CUBEMAP | DDSCAPS2.CUBEMAP_NEGATIVEZ
312
+
313
+ DXT1_FOURCC = D3DFMT.DXT1
314
+ DXT3_FOURCC = D3DFMT.DXT3
315
+ DXT5_FOURCC = D3DFMT.DXT5
316
+
317
+ DXGI_FORMAT_R8G8B8A8_TYPELESS = DXGI_FORMAT.R8G8B8A8_TYPELESS
318
+ DXGI_FORMAT_R8G8B8A8_UNORM = DXGI_FORMAT.R8G8B8A8_UNORM
319
+ DXGI_FORMAT_R8G8B8A8_UNORM_SRGB = DXGI_FORMAT.R8G8B8A8_UNORM_SRGB
320
+ DXGI_FORMAT_BC5_TYPELESS = DXGI_FORMAT.BC5_TYPELESS
321
+ DXGI_FORMAT_BC5_UNORM = DXGI_FORMAT.BC5_UNORM
322
+ DXGI_FORMAT_BC5_SNORM = DXGI_FORMAT.BC5_SNORM
323
+ DXGI_FORMAT_BC6H_UF16 = DXGI_FORMAT.BC6H_UF16
324
+ DXGI_FORMAT_BC6H_SF16 = DXGI_FORMAT.BC6H_SF16
325
+ DXGI_FORMAT_BC7_TYPELESS = DXGI_FORMAT.BC7_TYPELESS
326
+ DXGI_FORMAT_BC7_UNORM = DXGI_FORMAT.BC7_UNORM
327
+ DXGI_FORMAT_BC7_UNORM_SRGB = DXGI_FORMAT.BC7_UNORM_SRGB
328
+
329
+
330
+ class DdsImageFile(ImageFile.ImageFile):
331
+ format = "DDS"
332
+ format_description = "DirectDraw Surface"
333
+
334
+ def _open(self) -> None:
335
+ assert self.fp is not None
336
+ if not _accept(self.fp.read(4)):
337
+ msg = "not a DDS file"
338
+ raise SyntaxError(msg)
339
+ (header_size,) = struct.unpack("<I", self.fp.read(4))
340
+ if header_size != 124:
341
+ msg = f"Unsupported header size {repr(header_size)}"
342
+ raise OSError(msg)
343
+ header = self.fp.read(header_size - 4)
344
+ if len(header) != 120:
345
+ msg = f"Incomplete header: {len(header)} bytes"
346
+ raise OSError(msg)
347
+
348
+ flags, height, width = struct.unpack("<3I", header[:12])
349
+ self._size = (width, height)
350
+ extents = (0, 0) + self.size
351
+
352
+ pitch, depth, mipmaps = struct.unpack("<3I", header[12:24])
353
+ struct.unpack("<11I", header[24:68]) # reserved
354
+
355
+ # pixel format
356
+ pfsize, pfflags, fourcc, bitcount = struct.unpack("<4I", header[68:84])
357
+ n = 0
358
+ rawmode = None
359
+ if pfflags & DDPF.RGB:
360
+ # Texture contains uncompressed RGB data
361
+ if pfflags & DDPF.ALPHAPIXELS:
362
+ self._mode = "RGBA"
363
+ mask_count = 4
364
+ else:
365
+ self._mode = "RGB"
366
+ mask_count = 3
367
+
368
+ masks = struct.unpack(f"<{mask_count}I", header[84 : 84 + mask_count * 4])
369
+ self.tile = [ImageFile._Tile("dds_rgb", extents, 0, (bitcount, masks))]
370
+ return
371
+ elif pfflags & DDPF.LUMINANCE:
372
+ if bitcount == 8:
373
+ self._mode = "L"
374
+ elif bitcount == 16 and pfflags & DDPF.ALPHAPIXELS:
375
+ self._mode = "LA"
376
+ else:
377
+ msg = f"Unsupported bitcount {bitcount} for {pfflags}"
378
+ raise OSError(msg)
379
+ elif pfflags & DDPF.PALETTEINDEXED8:
380
+ self._mode = "P"
381
+ self.palette = ImagePalette.raw("RGBA", self.fp.read(1024))
382
+ self.palette.mode = "RGBA"
383
+ elif pfflags & DDPF.FOURCC:
384
+ offset = header_size + 4
385
+ if fourcc == D3DFMT.DXT1:
386
+ self._mode = "RGBA"
387
+ self.pixel_format = "DXT1"
388
+ n = 1
389
+ elif fourcc == D3DFMT.DXT3:
390
+ self._mode = "RGBA"
391
+ self.pixel_format = "DXT3"
392
+ n = 2
393
+ elif fourcc == D3DFMT.DXT5:
394
+ self._mode = "RGBA"
395
+ self.pixel_format = "DXT5"
396
+ n = 3
397
+ elif fourcc in (D3DFMT.BC4U, D3DFMT.ATI1):
398
+ self._mode = "L"
399
+ self.pixel_format = "BC4"
400
+ n = 4
401
+ elif fourcc == D3DFMT.BC5S:
402
+ self._mode = "RGB"
403
+ self.pixel_format = "BC5S"
404
+ n = 5
405
+ elif fourcc in (D3DFMT.BC5U, D3DFMT.ATI2):
406
+ self._mode = "RGB"
407
+ self.pixel_format = "BC5"
408
+ n = 5
409
+ elif fourcc == D3DFMT.DX10:
410
+ offset += 20
411
+ # ignoring flags which pertain to volume textures and cubemaps
412
+ (dxgi_format,) = struct.unpack("<I", self.fp.read(4))
413
+ self.fp.read(16)
414
+ if dxgi_format in (
415
+ DXGI_FORMAT.BC1_UNORM,
416
+ DXGI_FORMAT.BC1_TYPELESS,
417
+ ):
418
+ self._mode = "RGBA"
419
+ self.pixel_format = "BC1"
420
+ n = 1
421
+ elif dxgi_format in (DXGI_FORMAT.BC2_TYPELESS, DXGI_FORMAT.BC2_UNORM):
422
+ self._mode = "RGBA"
423
+ self.pixel_format = "BC2"
424
+ n = 2
425
+ elif dxgi_format in (DXGI_FORMAT.BC3_TYPELESS, DXGI_FORMAT.BC3_UNORM):
426
+ self._mode = "RGBA"
427
+ self.pixel_format = "BC3"
428
+ n = 3
429
+ elif dxgi_format in (DXGI_FORMAT.BC4_TYPELESS, DXGI_FORMAT.BC4_UNORM):
430
+ self._mode = "L"
431
+ self.pixel_format = "BC4"
432
+ n = 4
433
+ elif dxgi_format in (DXGI_FORMAT.BC5_TYPELESS, DXGI_FORMAT.BC5_UNORM):
434
+ self._mode = "RGB"
435
+ self.pixel_format = "BC5"
436
+ n = 5
437
+ elif dxgi_format == DXGI_FORMAT.BC5_SNORM:
438
+ self._mode = "RGB"
439
+ self.pixel_format = "BC5S"
440
+ n = 5
441
+ elif dxgi_format == DXGI_FORMAT.BC6H_UF16:
442
+ self._mode = "RGB"
443
+ self.pixel_format = "BC6H"
444
+ n = 6
445
+ elif dxgi_format == DXGI_FORMAT.BC6H_SF16:
446
+ self._mode = "RGB"
447
+ self.pixel_format = "BC6HS"
448
+ n = 6
449
+ elif dxgi_format in (
450
+ DXGI_FORMAT.BC7_TYPELESS,
451
+ DXGI_FORMAT.BC7_UNORM,
452
+ DXGI_FORMAT.BC7_UNORM_SRGB,
453
+ ):
454
+ self._mode = "RGBA"
455
+ self.pixel_format = "BC7"
456
+ n = 7
457
+ if dxgi_format == DXGI_FORMAT.BC7_UNORM_SRGB:
458
+ self.info["gamma"] = 1 / 2.2
459
+ elif dxgi_format in (
460
+ DXGI_FORMAT.R8G8B8A8_TYPELESS,
461
+ DXGI_FORMAT.R8G8B8A8_UNORM,
462
+ DXGI_FORMAT.R8G8B8A8_UNORM_SRGB,
463
+ ):
464
+ self._mode = "RGBA"
465
+ if dxgi_format == DXGI_FORMAT.R8G8B8A8_UNORM_SRGB:
466
+ self.info["gamma"] = 1 / 2.2
467
+ else:
468
+ msg = f"Unimplemented DXGI format {dxgi_format}"
469
+ raise NotImplementedError(msg)
470
+ else:
471
+ msg = f"Unimplemented pixel format {repr(fourcc)}"
472
+ raise NotImplementedError(msg)
473
+ else:
474
+ msg = f"Unknown pixel format flags {pfflags}"
475
+ raise NotImplementedError(msg)
476
+
477
+ if n:
478
+ self.tile = [
479
+ ImageFile._Tile("bcn", extents, offset, (n, self.pixel_format))
480
+ ]
481
+ else:
482
+ self.tile = [ImageFile._Tile("raw", extents, 0, rawmode or self.mode)]
483
+
484
+ def load_seek(self, pos: int) -> None:
485
+ pass
486
+
487
+
488
+ class DdsRgbDecoder(ImageFile.PyDecoder):
489
+ _pulls_fd = True
490
+
491
+ def decode(self, buffer: Image.DecoderInput) -> tuple[int, int]:
492
+ bitcount, masks = self.args
493
+
494
+ data = bytearray()
495
+ bytecount = bitcount // 8
496
+ if not bytecount:
497
+ self.set_as_raw(data)
498
+ return -1, 0
499
+
500
+ # Some masks will be padded with zeros, e.g. R 0b11 G 0b1100
501
+ # Calculate how many zeros each mask is padded with
502
+ mask_offsets = []
503
+ # And the maximum value of each channel without the padding
504
+ mask_totals = []
505
+ for mask in masks:
506
+ offset = 0
507
+ if mask != 0:
508
+ while mask >> (offset + 1) << (offset + 1) == mask:
509
+ offset += 1
510
+ mask_offsets.append(offset)
511
+ mask_totals.append(mask >> offset)
512
+
513
+ assert self.fd is not None
514
+ dest_length = self.state.xsize * self.state.ysize * len(masks)
515
+ while len(data) < dest_length:
516
+ bytes_read = self.fd.read(bytecount)
517
+ if len(bytes_read) < bytecount:
518
+ break
519
+ value = int.from_bytes(bytes_read, "little")
520
+ for i, mask in enumerate(masks):
521
+ masked_value = value & mask
522
+ # Remove the zero padding, and scale it to 8 bits
523
+ data += o8(
524
+ int(((masked_value >> mask_offsets[i]) / mask_totals[i]) * 255)
525
+ if mask_totals[i]
526
+ else 0
527
+ )
528
+ self.set_as_raw(data)
529
+ return -1, 0
530
+
531
+
532
+ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
533
+ if im.mode not in ("RGB", "RGBA", "L", "LA"):
534
+ msg = f"cannot write mode {im.mode} as DDS"
535
+ raise OSError(msg)
536
+
537
+ flags = DDSD.CAPS | DDSD.HEIGHT | DDSD.WIDTH | DDSD.PIXELFORMAT
538
+ bitcount = len(im.getbands()) * 8
539
+ pixel_format = im.encoderinfo.get("pixel_format")
540
+ args: tuple[int] | str
541
+ if pixel_format:
542
+ codec_name = "bcn"
543
+ flags |= DDSD.LINEARSIZE
544
+ pitch = (im.width + 3) * 4
545
+ rgba_mask = [0, 0, 0, 0]
546
+ pixel_flags = DDPF.FOURCC
547
+ if pixel_format == "DXT1":
548
+ fourcc = D3DFMT.DXT1
549
+ args = (1,)
550
+ elif pixel_format == "DXT3":
551
+ fourcc = D3DFMT.DXT3
552
+ args = (2,)
553
+ elif pixel_format == "DXT5":
554
+ fourcc = D3DFMT.DXT5
555
+ args = (3,)
556
+ else:
557
+ fourcc = D3DFMT.DX10
558
+ if pixel_format == "BC2":
559
+ args = (2,)
560
+ dxgi_format = DXGI_FORMAT.BC2_TYPELESS
561
+ elif pixel_format == "BC3":
562
+ args = (3,)
563
+ dxgi_format = DXGI_FORMAT.BC3_TYPELESS
564
+ elif pixel_format == "BC5":
565
+ args = (5,)
566
+ dxgi_format = DXGI_FORMAT.BC5_TYPELESS
567
+ if im.mode != "RGB":
568
+ msg = "only RGB mode can be written as BC5"
569
+ raise OSError(msg)
570
+ else:
571
+ msg = f"cannot write pixel format {pixel_format}"
572
+ raise OSError(msg)
573
+ else:
574
+ codec_name = "raw"
575
+ flags |= DDSD.PITCH
576
+ pitch = (im.width * bitcount + 7) // 8
577
+
578
+ alpha = im.mode[-1] == "A"
579
+ if im.mode[0] == "L":
580
+ pixel_flags = DDPF.LUMINANCE
581
+ args = im.mode
582
+ if alpha:
583
+ rgba_mask = [0x000000FF, 0x000000FF, 0x000000FF]
584
+ else:
585
+ rgba_mask = [0xFF000000, 0xFF000000, 0xFF000000]
586
+ else:
587
+ pixel_flags = DDPF.RGB
588
+ args = im.mode[::-1]
589
+ rgba_mask = [0x00FF0000, 0x0000FF00, 0x000000FF]
590
+
591
+ if alpha:
592
+ r, g, b, a = im.split()
593
+ im = Image.merge("RGBA", (a, r, g, b))
594
+ if alpha:
595
+ pixel_flags |= DDPF.ALPHAPIXELS
596
+ rgba_mask.append(0xFF000000 if alpha else 0)
597
+
598
+ fourcc = D3DFMT.UNKNOWN
599
+ fp.write(
600
+ o32(DDS_MAGIC)
601
+ + struct.pack(
602
+ "<7I",
603
+ 124, # header size
604
+ flags, # flags
605
+ im.height,
606
+ im.width,
607
+ pitch,
608
+ 0, # depth
609
+ 0, # mipmaps
610
+ )
611
+ + struct.pack("11I", *((0,) * 11)) # reserved
612
+ # pfsize, pfflags, fourcc, bitcount
613
+ + struct.pack("<4I", 32, pixel_flags, fourcc, bitcount)
614
+ + struct.pack("<4I", *rgba_mask) # dwRGBABitMask
615
+ + struct.pack("<5I", DDSCAPS.TEXTURE, 0, 0, 0, 0)
616
+ )
617
+ if fourcc == D3DFMT.DX10:
618
+ fp.write(
619
+ # dxgi_format, 2D resource, misc, array size, straight alpha
620
+ struct.pack("<5I", dxgi_format, 3, 0, 0, 1)
621
+ )
622
+ ImageFile._save(im, fp, [ImageFile._Tile(codec_name, (0, 0) + im.size, 0, args)])
623
+
624
+
625
+ def _accept(prefix: bytes) -> bool:
626
+ return prefix.startswith(b"DDS ")
627
+
628
+
629
+ Image.register_open(DdsImageFile.format, DdsImageFile, _accept)
630
+ Image.register_decoder("dds_rgb", DdsRgbDecoder)
631
+ Image.register_save(DdsImageFile.format, _save)
632
+ Image.register_extension(DdsImageFile.format, ".dds")
.venv/lib/python3.11/site-packages/PIL/EpsImagePlugin.py ADDED
@@ -0,0 +1,484 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # EPS file handling
6
+ #
7
+ # History:
8
+ # 1995-09-01 fl Created (0.1)
9
+ # 1996-05-18 fl Don't choke on "atend" fields, Ghostscript interface (0.2)
10
+ # 1996-08-22 fl Don't choke on floating point BoundingBox values
11
+ # 1996-08-23 fl Handle files from Macintosh (0.3)
12
+ # 2001-02-17 fl Use 're' instead of 'regex' (Python 2.1) (0.4)
13
+ # 2003-09-07 fl Check gs.close status (from Federico Di Gregorio) (0.5)
14
+ # 2014-05-07 e Handling of EPS with binary preview and fixed resolution
15
+ # resizing
16
+ #
17
+ # Copyright (c) 1997-2003 by Secret Labs AB.
18
+ # Copyright (c) 1995-2003 by Fredrik Lundh
19
+ #
20
+ # See the README file for information on usage and redistribution.
21
+ #
22
+ from __future__ import annotations
23
+
24
+ import io
25
+ import os
26
+ import re
27
+ import subprocess
28
+ import sys
29
+ import tempfile
30
+ from typing import IO
31
+
32
+ from . import Image, ImageFile
33
+ from ._binary import i32le as i32
34
+
35
+ # --------------------------------------------------------------------
36
+
37
+
38
+ split = re.compile(r"^%%([^:]*):[ \t]*(.*)[ \t]*$")
39
+ field = re.compile(r"^%[%!\w]([^:]*)[ \t]*$")
40
+
41
+ gs_binary: str | bool | None = None
42
+ gs_windows_binary = None
43
+
44
+
45
+ def has_ghostscript() -> bool:
46
+ global gs_binary, gs_windows_binary
47
+ if gs_binary is None:
48
+ if sys.platform.startswith("win"):
49
+ if gs_windows_binary is None:
50
+ import shutil
51
+
52
+ for binary in ("gswin32c", "gswin64c", "gs"):
53
+ if shutil.which(binary) is not None:
54
+ gs_windows_binary = binary
55
+ break
56
+ else:
57
+ gs_windows_binary = False
58
+ gs_binary = gs_windows_binary
59
+ else:
60
+ try:
61
+ subprocess.check_call(["gs", "--version"], stdout=subprocess.DEVNULL)
62
+ gs_binary = "gs"
63
+ except OSError:
64
+ gs_binary = False
65
+ return gs_binary is not False
66
+
67
+
68
+ def Ghostscript(
69
+ tile: list[ImageFile._Tile],
70
+ size: tuple[int, int],
71
+ fp: IO[bytes],
72
+ scale: int = 1,
73
+ transparency: bool = False,
74
+ ) -> Image.core.ImagingCore:
75
+ """Render an image using Ghostscript"""
76
+ global gs_binary
77
+ if not has_ghostscript():
78
+ msg = "Unable to locate Ghostscript on paths"
79
+ raise OSError(msg)
80
+ assert isinstance(gs_binary, str)
81
+
82
+ # Unpack decoder tile
83
+ args = tile[0].args
84
+ assert isinstance(args, tuple)
85
+ length, bbox = args
86
+
87
+ # Hack to support hi-res rendering
88
+ scale = int(scale) or 1
89
+ width = size[0] * scale
90
+ height = size[1] * scale
91
+ # resolution is dependent on bbox and size
92
+ res_x = 72.0 * width / (bbox[2] - bbox[0])
93
+ res_y = 72.0 * height / (bbox[3] - bbox[1])
94
+
95
+ out_fd, outfile = tempfile.mkstemp()
96
+ os.close(out_fd)
97
+
98
+ infile_temp = None
99
+ if hasattr(fp, "name") and os.path.exists(fp.name):
100
+ infile = fp.name
101
+ else:
102
+ in_fd, infile_temp = tempfile.mkstemp()
103
+ os.close(in_fd)
104
+ infile = infile_temp
105
+
106
+ # Ignore length and offset!
107
+ # Ghostscript can read it
108
+ # Copy whole file to read in Ghostscript
109
+ with open(infile_temp, "wb") as f:
110
+ # fetch length of fp
111
+ fp.seek(0, io.SEEK_END)
112
+ fsize = fp.tell()
113
+ # ensure start position
114
+ # go back
115
+ fp.seek(0)
116
+ lengthfile = fsize
117
+ while lengthfile > 0:
118
+ s = fp.read(min(lengthfile, 100 * 1024))
119
+ if not s:
120
+ break
121
+ lengthfile -= len(s)
122
+ f.write(s)
123
+
124
+ if transparency:
125
+ # "RGBA"
126
+ device = "pngalpha"
127
+ else:
128
+ # "pnmraw" automatically chooses between
129
+ # PBM ("1"), PGM ("L"), and PPM ("RGB").
130
+ device = "pnmraw"
131
+
132
+ # Build Ghostscript command
133
+ command = [
134
+ gs_binary,
135
+ "-q", # quiet mode
136
+ f"-g{width:d}x{height:d}", # set output geometry (pixels)
137
+ f"-r{res_x:f}x{res_y:f}", # set input DPI (dots per inch)
138
+ "-dBATCH", # exit after processing
139
+ "-dNOPAUSE", # don't pause between pages
140
+ "-dSAFER", # safe mode
141
+ f"-sDEVICE={device}",
142
+ f"-sOutputFile={outfile}", # output file
143
+ # adjust for image origin
144
+ "-c",
145
+ f"{-bbox[0]} {-bbox[1]} translate",
146
+ "-f",
147
+ infile, # input file
148
+ # showpage (see https://bugs.ghostscript.com/show_bug.cgi?id=698272)
149
+ "-c",
150
+ "showpage",
151
+ ]
152
+
153
+ # push data through Ghostscript
154
+ try:
155
+ startupinfo = None
156
+ if sys.platform.startswith("win"):
157
+ startupinfo = subprocess.STARTUPINFO()
158
+ startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
159
+ subprocess.check_call(command, startupinfo=startupinfo)
160
+ with Image.open(outfile) as out_im:
161
+ out_im.load()
162
+ return out_im.im.copy()
163
+ finally:
164
+ try:
165
+ os.unlink(outfile)
166
+ if infile_temp:
167
+ os.unlink(infile_temp)
168
+ except OSError:
169
+ pass
170
+
171
+
172
+ def _accept(prefix: bytes) -> bool:
173
+ return prefix.startswith(b"%!PS") or (
174
+ len(prefix) >= 4 and i32(prefix) == 0xC6D3D0C5
175
+ )
176
+
177
+
178
+ ##
179
+ # Image plugin for Encapsulated PostScript. This plugin supports only
180
+ # a few variants of this format.
181
+
182
+
183
+ class EpsImageFile(ImageFile.ImageFile):
184
+ """EPS File Parser for the Python Imaging Library"""
185
+
186
+ format = "EPS"
187
+ format_description = "Encapsulated Postscript"
188
+
189
+ mode_map = {1: "L", 2: "LAB", 3: "RGB", 4: "CMYK"}
190
+
191
+ def _open(self) -> None:
192
+ assert self.fp is not None
193
+ length, offset = self._find_offset(self.fp)
194
+
195
+ # go to offset - start of "%!PS"
196
+ self.fp.seek(offset)
197
+
198
+ self._mode = "RGB"
199
+
200
+ # When reading header comments, the first comment is used.
201
+ # When reading trailer comments, the last comment is used.
202
+ bounding_box: list[int] | None = None
203
+ imagedata_size: tuple[int, int] | None = None
204
+
205
+ byte_arr = bytearray(255)
206
+ bytes_mv = memoryview(byte_arr)
207
+ bytes_read = 0
208
+ reading_header_comments = True
209
+ reading_trailer_comments = False
210
+ trailer_reached = False
211
+
212
+ def check_required_header_comments() -> None:
213
+ """
214
+ The EPS specification requires that some headers exist.
215
+ This should be checked when the header comments formally end,
216
+ when image data starts, or when the file ends, whichever comes first.
217
+ """
218
+ if "PS-Adobe" not in self.info:
219
+ msg = 'EPS header missing "%!PS-Adobe" comment'
220
+ raise SyntaxError(msg)
221
+ if "BoundingBox" not in self.info:
222
+ msg = 'EPS header missing "%%BoundingBox" comment'
223
+ raise SyntaxError(msg)
224
+
225
+ def read_comment(s: str) -> bool:
226
+ nonlocal bounding_box, reading_trailer_comments
227
+ try:
228
+ m = split.match(s)
229
+ except re.error as e:
230
+ msg = "not an EPS file"
231
+ raise SyntaxError(msg) from e
232
+
233
+ if not m:
234
+ return False
235
+
236
+ k, v = m.group(1, 2)
237
+ self.info[k] = v
238
+ if k == "BoundingBox":
239
+ if v == "(atend)":
240
+ reading_trailer_comments = True
241
+ elif not bounding_box or (trailer_reached and reading_trailer_comments):
242
+ try:
243
+ # Note: The DSC spec says that BoundingBox
244
+ # fields should be integers, but some drivers
245
+ # put floating point values there anyway.
246
+ bounding_box = [int(float(i)) for i in v.split()]
247
+ except Exception:
248
+ pass
249
+ return True
250
+
251
+ while True:
252
+ byte = self.fp.read(1)
253
+ if byte == b"":
254
+ # if we didn't read a byte we must be at the end of the file
255
+ if bytes_read == 0:
256
+ if reading_header_comments:
257
+ check_required_header_comments()
258
+ break
259
+ elif byte in b"\r\n":
260
+ # if we read a line ending character, ignore it and parse what
261
+ # we have already read. if we haven't read any other characters,
262
+ # continue reading
263
+ if bytes_read == 0:
264
+ continue
265
+ else:
266
+ # ASCII/hexadecimal lines in an EPS file must not exceed
267
+ # 255 characters, not including line ending characters
268
+ if bytes_read >= 255:
269
+ # only enforce this for lines starting with a "%",
270
+ # otherwise assume it's binary data
271
+ if byte_arr[0] == ord("%"):
272
+ msg = "not an EPS file"
273
+ raise SyntaxError(msg)
274
+ else:
275
+ if reading_header_comments:
276
+ check_required_header_comments()
277
+ reading_header_comments = False
278
+ # reset bytes_read so we can keep reading
279
+ # data until the end of the line
280
+ bytes_read = 0
281
+ byte_arr[bytes_read] = byte[0]
282
+ bytes_read += 1
283
+ continue
284
+
285
+ if reading_header_comments:
286
+ # Load EPS header
287
+
288
+ # if this line doesn't start with a "%",
289
+ # or does start with "%%EndComments",
290
+ # then we've reached the end of the header/comments
291
+ if byte_arr[0] != ord("%") or bytes_mv[:13] == b"%%EndComments":
292
+ check_required_header_comments()
293
+ reading_header_comments = False
294
+ continue
295
+
296
+ s = str(bytes_mv[:bytes_read], "latin-1")
297
+ if not read_comment(s):
298
+ m = field.match(s)
299
+ if m:
300
+ k = m.group(1)
301
+ if k.startswith("PS-Adobe"):
302
+ self.info["PS-Adobe"] = k[9:]
303
+ else:
304
+ self.info[k] = ""
305
+ elif s[0] == "%":
306
+ # handle non-DSC PostScript comments that some
307
+ # tools mistakenly put in the Comments section
308
+ pass
309
+ else:
310
+ msg = "bad EPS header"
311
+ raise OSError(msg)
312
+ elif bytes_mv[:11] == b"%ImageData:":
313
+ # Check for an "ImageData" descriptor
314
+ # https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#50577413_pgfId-1035096
315
+
316
+ # If we've already read an "ImageData" descriptor,
317
+ # don't read another one.
318
+ if imagedata_size:
319
+ bytes_read = 0
320
+ continue
321
+
322
+ # Values:
323
+ # columns
324
+ # rows
325
+ # bit depth (1 or 8)
326
+ # mode (1: L, 2: LAB, 3: RGB, 4: CMYK)
327
+ # number of padding channels
328
+ # block size (number of bytes per row per channel)
329
+ # binary/ascii (1: binary, 2: ascii)
330
+ # data start identifier (the image data follows after a single line
331
+ # consisting only of this quoted value)
332
+ image_data_values = byte_arr[11:bytes_read].split(None, 7)
333
+ columns, rows, bit_depth, mode_id = (
334
+ int(value) for value in image_data_values[:4]
335
+ )
336
+
337
+ if bit_depth == 1:
338
+ self._mode = "1"
339
+ elif bit_depth == 8:
340
+ try:
341
+ self._mode = self.mode_map[mode_id]
342
+ except ValueError:
343
+ break
344
+ else:
345
+ break
346
+
347
+ # Parse the columns and rows after checking the bit depth and mode
348
+ # in case the bit depth and/or mode are invalid.
349
+ imagedata_size = columns, rows
350
+ elif bytes_mv[:5] == b"%%EOF":
351
+ break
352
+ elif trailer_reached and reading_trailer_comments:
353
+ # Load EPS trailer
354
+ s = str(bytes_mv[:bytes_read], "latin-1")
355
+ read_comment(s)
356
+ elif bytes_mv[:9] == b"%%Trailer":
357
+ trailer_reached = True
358
+ elif bytes_mv[:14] == b"%%BeginBinary:":
359
+ bytecount = int(byte_arr[14:bytes_read])
360
+ if bytecount < 0:
361
+ msg = "BeginBinary bytecount cannot be negative"
362
+ raise ValueError(msg)
363
+ self.fp.seek(bytecount, os.SEEK_CUR)
364
+ bytes_read = 0
365
+
366
+ # A "BoundingBox" is always required,
367
+ # even if an "ImageData" descriptor size exists.
368
+ if not bounding_box:
369
+ msg = "cannot determine EPS bounding box"
370
+ raise OSError(msg)
371
+
372
+ # An "ImageData" size takes precedence over the "BoundingBox".
373
+ self._size = imagedata_size or (
374
+ bounding_box[2] - bounding_box[0],
375
+ bounding_box[3] - bounding_box[1],
376
+ )
377
+
378
+ self.tile = [
379
+ ImageFile._Tile("eps", (0, 0) + self.size, offset, (length, bounding_box))
380
+ ]
381
+
382
+ def _find_offset(self, fp: IO[bytes]) -> tuple[int, int]:
383
+ s = fp.read(4)
384
+
385
+ if s == b"%!PS":
386
+ # for HEAD without binary preview
387
+ fp.seek(0, io.SEEK_END)
388
+ length = fp.tell()
389
+ offset = 0
390
+ elif i32(s) == 0xC6D3D0C5:
391
+ # FIX for: Some EPS file not handled correctly / issue #302
392
+ # EPS can contain binary data
393
+ # or start directly with latin coding
394
+ # more info see:
395
+ # https://web.archive.org/web/20160528181353/http://partners.adobe.com/public/developer/en/ps/5002.EPSF_Spec.pdf
396
+ s = fp.read(8)
397
+ offset = i32(s)
398
+ length = i32(s, 4)
399
+ else:
400
+ msg = "not an EPS file"
401
+ raise SyntaxError(msg)
402
+
403
+ return length, offset
404
+
405
+ def load(
406
+ self, scale: int = 1, transparency: bool = False
407
+ ) -> Image.core.PixelAccess | None:
408
+ # Load EPS via Ghostscript
409
+ if self.tile:
410
+ assert self.fp is not None
411
+ self.im = Ghostscript(self.tile, self.size, self.fp, scale, transparency)
412
+ self._mode = self.im.mode
413
+ self._size = self.im.size
414
+ self.tile = []
415
+ return Image.Image.load(self)
416
+
417
+ def load_seek(self, pos: int) -> None:
418
+ # we can't incrementally load, so force ImageFile.parser to
419
+ # use our custom load method by defining this method.
420
+ pass
421
+
422
+
423
+ # --------------------------------------------------------------------
424
+
425
+
426
+ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes, eps: int = 1) -> None:
427
+ """EPS Writer for the Python Imaging Library."""
428
+
429
+ # make sure image data is available
430
+ im.load()
431
+
432
+ # determine PostScript image mode
433
+ if im.mode == "L":
434
+ operator = (8, 1, b"image")
435
+ elif im.mode == "RGB":
436
+ operator = (8, 3, b"false 3 colorimage")
437
+ elif im.mode == "CMYK":
438
+ operator = (8, 4, b"false 4 colorimage")
439
+ else:
440
+ msg = "image mode is not supported"
441
+ raise ValueError(msg)
442
+
443
+ if eps:
444
+ # write EPS header
445
+ fp.write(b"%!PS-Adobe-3.0 EPSF-3.0\n")
446
+ fp.write(b"%%Creator: PIL 0.1 EpsEncode\n")
447
+ # fp.write("%%CreationDate: %s"...)
448
+ fp.write(b"%%%%BoundingBox: 0 0 %d %d\n" % im.size)
449
+ fp.write(b"%%Pages: 1\n")
450
+ fp.write(b"%%EndComments\n")
451
+ fp.write(b"%%Page: 1 1\n")
452
+ fp.write(b"%%ImageData: %d %d " % im.size)
453
+ fp.write(b'%d %d 0 1 1 "%s"\n' % operator)
454
+
455
+ # image header
456
+ fp.write(b"gsave\n")
457
+ fp.write(b"10 dict begin\n")
458
+ fp.write(b"/buf %d string def\n" % (im.size[0] * operator[1]))
459
+ fp.write(b"%d %d scale\n" % im.size)
460
+ fp.write(b"%d %d 8\n" % im.size) # <= bits
461
+ fp.write(b"[%d 0 0 -%d 0 %d]\n" % (im.size[0], im.size[1], im.size[1]))
462
+ fp.write(b"{ currentfile buf readhexstring pop } bind\n")
463
+ fp.write(operator[2] + b"\n")
464
+ if hasattr(fp, "flush"):
465
+ fp.flush()
466
+
467
+ ImageFile._save(im, fp, [ImageFile._Tile("eps", (0, 0) + im.size)])
468
+
469
+ fp.write(b"\n%%%%EndBinary\n")
470
+ fp.write(b"grestore end\n")
471
+ if hasattr(fp, "flush"):
472
+ fp.flush()
473
+
474
+
475
+ # --------------------------------------------------------------------
476
+
477
+
478
+ Image.register_open(EpsImageFile.format, EpsImageFile, _accept)
479
+
480
+ Image.register_save(EpsImageFile.format, _save)
481
+
482
+ Image.register_extensions(EpsImageFile.format, [".ps", ".eps"])
483
+
484
+ Image.register_mime(EpsImageFile.format, "application/postscript")
.venv/lib/python3.11/site-packages/PIL/ExifTags.py ADDED
@@ -0,0 +1,384 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # EXIF tags
6
+ #
7
+ # Copyright (c) 2003 by Secret Labs AB
8
+ #
9
+ # See the README file for information on usage and redistribution.
10
+ #
11
+
12
+ """
13
+ This module provides constants and clear-text names for various
14
+ well-known EXIF tags.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from enum import IntEnum
20
+
21
+
22
+ class Base(IntEnum):
23
+ # possibly incomplete
24
+ InteropIndex = 0x0001
25
+ ProcessingSoftware = 0x000B
26
+ NewSubfileType = 0x00FE
27
+ SubfileType = 0x00FF
28
+ ImageWidth = 0x0100
29
+ ImageLength = 0x0101
30
+ BitsPerSample = 0x0102
31
+ Compression = 0x0103
32
+ PhotometricInterpretation = 0x0106
33
+ Thresholding = 0x0107
34
+ CellWidth = 0x0108
35
+ CellLength = 0x0109
36
+ FillOrder = 0x010A
37
+ DocumentName = 0x010D
38
+ ImageDescription = 0x010E
39
+ Make = 0x010F
40
+ Model = 0x0110
41
+ StripOffsets = 0x0111
42
+ Orientation = 0x0112
43
+ SamplesPerPixel = 0x0115
44
+ RowsPerStrip = 0x0116
45
+ StripByteCounts = 0x0117
46
+ MinSampleValue = 0x0118
47
+ MaxSampleValue = 0x0119
48
+ XResolution = 0x011A
49
+ YResolution = 0x011B
50
+ PlanarConfiguration = 0x011C
51
+ PageName = 0x011D
52
+ FreeOffsets = 0x0120
53
+ FreeByteCounts = 0x0121
54
+ GrayResponseUnit = 0x0122
55
+ GrayResponseCurve = 0x0123
56
+ T4Options = 0x0124
57
+ T6Options = 0x0125
58
+ ResolutionUnit = 0x0128
59
+ PageNumber = 0x0129
60
+ TransferFunction = 0x012D
61
+ Software = 0x0131
62
+ DateTime = 0x0132
63
+ Artist = 0x013B
64
+ HostComputer = 0x013C
65
+ Predictor = 0x013D
66
+ WhitePoint = 0x013E
67
+ PrimaryChromaticities = 0x013F
68
+ ColorMap = 0x0140
69
+ HalftoneHints = 0x0141
70
+ TileWidth = 0x0142
71
+ TileLength = 0x0143
72
+ TileOffsets = 0x0144
73
+ TileByteCounts = 0x0145
74
+ SubIFDs = 0x014A
75
+ InkSet = 0x014C
76
+ InkNames = 0x014D
77
+ NumberOfInks = 0x014E
78
+ DotRange = 0x0150
79
+ TargetPrinter = 0x0151
80
+ ExtraSamples = 0x0152
81
+ SampleFormat = 0x0153
82
+ SMinSampleValue = 0x0154
83
+ SMaxSampleValue = 0x0155
84
+ TransferRange = 0x0156
85
+ ClipPath = 0x0157
86
+ XClipPathUnits = 0x0158
87
+ YClipPathUnits = 0x0159
88
+ Indexed = 0x015A
89
+ JPEGTables = 0x015B
90
+ OPIProxy = 0x015F
91
+ JPEGProc = 0x0200
92
+ JpegIFOffset = 0x0201
93
+ JpegIFByteCount = 0x0202
94
+ JpegRestartInterval = 0x0203
95
+ JpegLosslessPredictors = 0x0205
96
+ JpegPointTransforms = 0x0206
97
+ JpegQTables = 0x0207
98
+ JpegDCTables = 0x0208
99
+ JpegACTables = 0x0209
100
+ YCbCrCoefficients = 0x0211
101
+ YCbCrSubSampling = 0x0212
102
+ YCbCrPositioning = 0x0213
103
+ ReferenceBlackWhite = 0x0214
104
+ XMLPacket = 0x02BC
105
+ RelatedImageFileFormat = 0x1000
106
+ RelatedImageWidth = 0x1001
107
+ RelatedImageLength = 0x1002
108
+ Rating = 0x4746
109
+ RatingPercent = 0x4749
110
+ ImageID = 0x800D
111
+ CFARepeatPatternDim = 0x828D
112
+ BatteryLevel = 0x828F
113
+ Copyright = 0x8298
114
+ ExposureTime = 0x829A
115
+ FNumber = 0x829D
116
+ IPTCNAA = 0x83BB
117
+ ImageResources = 0x8649
118
+ ExifOffset = 0x8769
119
+ InterColorProfile = 0x8773
120
+ ExposureProgram = 0x8822
121
+ SpectralSensitivity = 0x8824
122
+ GPSInfo = 0x8825
123
+ ISOSpeedRatings = 0x8827
124
+ OECF = 0x8828
125
+ Interlace = 0x8829
126
+ TimeZoneOffset = 0x882A
127
+ SelfTimerMode = 0x882B
128
+ SensitivityType = 0x8830
129
+ StandardOutputSensitivity = 0x8831
130
+ RecommendedExposureIndex = 0x8832
131
+ ISOSpeed = 0x8833
132
+ ISOSpeedLatitudeyyy = 0x8834
133
+ ISOSpeedLatitudezzz = 0x8835
134
+ ExifVersion = 0x9000
135
+ DateTimeOriginal = 0x9003
136
+ DateTimeDigitized = 0x9004
137
+ OffsetTime = 0x9010
138
+ OffsetTimeOriginal = 0x9011
139
+ OffsetTimeDigitized = 0x9012
140
+ ComponentsConfiguration = 0x9101
141
+ CompressedBitsPerPixel = 0x9102
142
+ ShutterSpeedValue = 0x9201
143
+ ApertureValue = 0x9202
144
+ BrightnessValue = 0x9203
145
+ ExposureBiasValue = 0x9204
146
+ MaxApertureValue = 0x9205
147
+ SubjectDistance = 0x9206
148
+ MeteringMode = 0x9207
149
+ LightSource = 0x9208
150
+ Flash = 0x9209
151
+ FocalLength = 0x920A
152
+ Noise = 0x920D
153
+ ImageNumber = 0x9211
154
+ SecurityClassification = 0x9212
155
+ ImageHistory = 0x9213
156
+ TIFFEPStandardID = 0x9216
157
+ MakerNote = 0x927C
158
+ UserComment = 0x9286
159
+ SubsecTime = 0x9290
160
+ SubsecTimeOriginal = 0x9291
161
+ SubsecTimeDigitized = 0x9292
162
+ AmbientTemperature = 0x9400
163
+ Humidity = 0x9401
164
+ Pressure = 0x9402
165
+ WaterDepth = 0x9403
166
+ Acceleration = 0x9404
167
+ CameraElevationAngle = 0x9405
168
+ XPTitle = 0x9C9B
169
+ XPComment = 0x9C9C
170
+ XPAuthor = 0x9C9D
171
+ XPKeywords = 0x9C9E
172
+ XPSubject = 0x9C9F
173
+ FlashPixVersion = 0xA000
174
+ ColorSpace = 0xA001
175
+ ExifImageWidth = 0xA002
176
+ ExifImageHeight = 0xA003
177
+ RelatedSoundFile = 0xA004
178
+ ExifInteroperabilityOffset = 0xA005
179
+ FlashEnergy = 0xA20B
180
+ SpatialFrequencyResponse = 0xA20C
181
+ FocalPlaneXResolution = 0xA20E
182
+ FocalPlaneYResolution = 0xA20F
183
+ FocalPlaneResolutionUnit = 0xA210
184
+ SubjectLocation = 0xA214
185
+ ExposureIndex = 0xA215
186
+ SensingMethod = 0xA217
187
+ FileSource = 0xA300
188
+ SceneType = 0xA301
189
+ CFAPattern = 0xA302
190
+ CustomRendered = 0xA401
191
+ ExposureMode = 0xA402
192
+ WhiteBalance = 0xA403
193
+ DigitalZoomRatio = 0xA404
194
+ FocalLengthIn35mmFilm = 0xA405
195
+ SceneCaptureType = 0xA406
196
+ GainControl = 0xA407
197
+ Contrast = 0xA408
198
+ Saturation = 0xA409
199
+ Sharpness = 0xA40A
200
+ DeviceSettingDescription = 0xA40B
201
+ SubjectDistanceRange = 0xA40C
202
+ ImageUniqueID = 0xA420
203
+ CameraOwnerName = 0xA430
204
+ BodySerialNumber = 0xA431
205
+ LensSpecification = 0xA432
206
+ LensMake = 0xA433
207
+ LensModel = 0xA434
208
+ LensSerialNumber = 0xA435
209
+ CompositeImage = 0xA460
210
+ CompositeImageCount = 0xA461
211
+ CompositeImageExposureTimes = 0xA462
212
+ Gamma = 0xA500
213
+ PrintImageMatching = 0xC4A5
214
+ DNGVersion = 0xC612
215
+ DNGBackwardVersion = 0xC613
216
+ UniqueCameraModel = 0xC614
217
+ LocalizedCameraModel = 0xC615
218
+ CFAPlaneColor = 0xC616
219
+ CFALayout = 0xC617
220
+ LinearizationTable = 0xC618
221
+ BlackLevelRepeatDim = 0xC619
222
+ BlackLevel = 0xC61A
223
+ BlackLevelDeltaH = 0xC61B
224
+ BlackLevelDeltaV = 0xC61C
225
+ WhiteLevel = 0xC61D
226
+ DefaultScale = 0xC61E
227
+ DefaultCropOrigin = 0xC61F
228
+ DefaultCropSize = 0xC620
229
+ ColorMatrix1 = 0xC621
230
+ ColorMatrix2 = 0xC622
231
+ CameraCalibration1 = 0xC623
232
+ CameraCalibration2 = 0xC624
233
+ ReductionMatrix1 = 0xC625
234
+ ReductionMatrix2 = 0xC626
235
+ AnalogBalance = 0xC627
236
+ AsShotNeutral = 0xC628
237
+ AsShotWhiteXY = 0xC629
238
+ BaselineExposure = 0xC62A
239
+ BaselineNoise = 0xC62B
240
+ BaselineSharpness = 0xC62C
241
+ BayerGreenSplit = 0xC62D
242
+ LinearResponseLimit = 0xC62E
243
+ CameraSerialNumber = 0xC62F
244
+ LensInfo = 0xC630
245
+ ChromaBlurRadius = 0xC631
246
+ AntiAliasStrength = 0xC632
247
+ ShadowScale = 0xC633
248
+ DNGPrivateData = 0xC634
249
+ MakerNoteSafety = 0xC635
250
+ CalibrationIlluminant1 = 0xC65A
251
+ CalibrationIlluminant2 = 0xC65B
252
+ BestQualityScale = 0xC65C
253
+ RawDataUniqueID = 0xC65D
254
+ OriginalRawFileName = 0xC68B
255
+ OriginalRawFileData = 0xC68C
256
+ ActiveArea = 0xC68D
257
+ MaskedAreas = 0xC68E
258
+ AsShotICCProfile = 0xC68F
259
+ AsShotPreProfileMatrix = 0xC690
260
+ CurrentICCProfile = 0xC691
261
+ CurrentPreProfileMatrix = 0xC692
262
+ ColorimetricReference = 0xC6BF
263
+ CameraCalibrationSignature = 0xC6F3
264
+ ProfileCalibrationSignature = 0xC6F4
265
+ AsShotProfileName = 0xC6F6
266
+ NoiseReductionApplied = 0xC6F7
267
+ ProfileName = 0xC6F8
268
+ ProfileHueSatMapDims = 0xC6F9
269
+ ProfileHueSatMapData1 = 0xC6FA
270
+ ProfileHueSatMapData2 = 0xC6FB
271
+ ProfileToneCurve = 0xC6FC
272
+ ProfileEmbedPolicy = 0xC6FD
273
+ ProfileCopyright = 0xC6FE
274
+ ForwardMatrix1 = 0xC714
275
+ ForwardMatrix2 = 0xC715
276
+ PreviewApplicationName = 0xC716
277
+ PreviewApplicationVersion = 0xC717
278
+ PreviewSettingsName = 0xC718
279
+ PreviewSettingsDigest = 0xC719
280
+ PreviewColorSpace = 0xC71A
281
+ PreviewDateTime = 0xC71B
282
+ RawImageDigest = 0xC71C
283
+ OriginalRawFileDigest = 0xC71D
284
+ SubTileBlockSize = 0xC71E
285
+ RowInterleaveFactor = 0xC71F
286
+ ProfileLookTableDims = 0xC725
287
+ ProfileLookTableData = 0xC726
288
+ OpcodeList1 = 0xC740
289
+ OpcodeList2 = 0xC741
290
+ OpcodeList3 = 0xC74E
291
+ NoiseProfile = 0xC761
292
+ FrameRate = 0xC764
293
+
294
+
295
+ """Maps EXIF tags to tag names."""
296
+ TAGS = {
297
+ **{i.value: i.name for i in Base},
298
+ 0x920C: "SpatialFrequencyResponse",
299
+ 0x9214: "SubjectLocation",
300
+ 0x9215: "ExposureIndex",
301
+ 0x828E: "CFAPattern",
302
+ 0x920B: "FlashEnergy",
303
+ 0x9216: "TIFF/EPStandardID",
304
+ }
305
+
306
+
307
+ class GPS(IntEnum):
308
+ GPSVersionID = 0x00
309
+ GPSLatitudeRef = 0x01
310
+ GPSLatitude = 0x02
311
+ GPSLongitudeRef = 0x03
312
+ GPSLongitude = 0x04
313
+ GPSAltitudeRef = 0x05
314
+ GPSAltitude = 0x06
315
+ GPSTimeStamp = 0x07
316
+ GPSSatellites = 0x08
317
+ GPSStatus = 0x09
318
+ GPSMeasureMode = 0x0A
319
+ GPSDOP = 0x0B
320
+ GPSSpeedRef = 0x0C
321
+ GPSSpeed = 0x0D
322
+ GPSTrackRef = 0x0E
323
+ GPSTrack = 0x0F
324
+ GPSImgDirectionRef = 0x10
325
+ GPSImgDirection = 0x11
326
+ GPSMapDatum = 0x12
327
+ GPSDestLatitudeRef = 0x13
328
+ GPSDestLatitude = 0x14
329
+ GPSDestLongitudeRef = 0x15
330
+ GPSDestLongitude = 0x16
331
+ GPSDestBearingRef = 0x17
332
+ GPSDestBearing = 0x18
333
+ GPSDestDistanceRef = 0x19
334
+ GPSDestDistance = 0x1A
335
+ GPSProcessingMethod = 0x1B
336
+ GPSAreaInformation = 0x1C
337
+ GPSDateStamp = 0x1D
338
+ GPSDifferential = 0x1E
339
+ GPSHPositioningError = 0x1F
340
+
341
+
342
+ """Maps EXIF GPS tags to tag names."""
343
+ GPSTAGS = {i.value: i.name for i in GPS}
344
+
345
+
346
+ class Interop(IntEnum):
347
+ InteropIndex = 0x0001
348
+ InteropVersion = 0x0002
349
+ RelatedImageFileFormat = 0x1000
350
+ RelatedImageWidth = 0x1001
351
+ RelatedImageHeight = 0x1002
352
+
353
+
354
+ class IFD(IntEnum):
355
+ Exif = 0x8769
356
+ GPSInfo = 0x8825
357
+ MakerNote = 0x927C
358
+ Makernote = 0x927C # Deprecated
359
+ Interop = 0xA005
360
+ IFD1 = -1
361
+
362
+
363
+ class LightSource(IntEnum):
364
+ Unknown = 0x00
365
+ Daylight = 0x01
366
+ Fluorescent = 0x02
367
+ Tungsten = 0x03
368
+ Flash = 0x04
369
+ Fine = 0x09
370
+ Cloudy = 0x0A
371
+ Shade = 0x0B
372
+ DaylightFluorescent = 0x0C
373
+ DayWhiteFluorescent = 0x0D
374
+ CoolWhiteFluorescent = 0x0E
375
+ WhiteFluorescent = 0x0F
376
+ StandardLightA = 0x11
377
+ StandardLightB = 0x12
378
+ StandardLightC = 0x13
379
+ D55 = 0x14
380
+ D65 = 0x15
381
+ D75 = 0x16
382
+ D50 = 0x17
383
+ ISO = 0x18
384
+ Other = 0xFF
.venv/lib/python3.11/site-packages/PIL/FitsImagePlugin.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library
3
+ # $Id$
4
+ #
5
+ # FITS file handling
6
+ #
7
+ # Copyright (c) 1998-2003 by Fredrik Lundh
8
+ #
9
+ # See the README file for information on usage and redistribution.
10
+ #
11
+ from __future__ import annotations
12
+
13
+ import gzip
14
+ import math
15
+
16
+ from . import Image, ImageFile
17
+
18
+
19
+ def _accept(prefix: bytes) -> bool:
20
+ return prefix.startswith(b"SIMPLE")
21
+
22
+
23
+ class FitsImageFile(ImageFile.ImageFile):
24
+ format = "FITS"
25
+ format_description = "FITS"
26
+
27
+ def _open(self) -> None:
28
+ assert self.fp is not None
29
+
30
+ headers: dict[bytes, bytes] = {}
31
+ header_in_progress = False
32
+ decoder_name = ""
33
+ while True:
34
+ header = self.fp.read(80)
35
+ if not header:
36
+ msg = "Truncated FITS file"
37
+ raise OSError(msg)
38
+ keyword = header[:8].strip()
39
+ if keyword in (b"SIMPLE", b"XTENSION"):
40
+ header_in_progress = True
41
+ elif headers and not header_in_progress:
42
+ # This is now a data unit
43
+ break
44
+ elif keyword == b"END":
45
+ # Seek to the end of the header unit
46
+ self.fp.seek(math.ceil(self.fp.tell() / 2880) * 2880)
47
+ if not decoder_name:
48
+ decoder_name, offset, args = self._parse_headers(headers)
49
+
50
+ header_in_progress = False
51
+ continue
52
+
53
+ if decoder_name:
54
+ # Keep going to read past the headers
55
+ continue
56
+
57
+ value = header[8:].split(b"/")[0].strip()
58
+ if value.startswith(b"="):
59
+ value = value[1:].strip()
60
+ if not headers and (not _accept(keyword) or value != b"T"):
61
+ msg = "Not a FITS file"
62
+ raise SyntaxError(msg)
63
+ headers[keyword] = value
64
+
65
+ if not decoder_name:
66
+ msg = "No image data"
67
+ raise ValueError(msg)
68
+
69
+ offset += self.fp.tell() - 80
70
+ self.tile = [ImageFile._Tile(decoder_name, (0, 0) + self.size, offset, args)]
71
+
72
+ def _get_size(
73
+ self, headers: dict[bytes, bytes], prefix: bytes
74
+ ) -> tuple[int, int] | None:
75
+ naxis = int(headers[prefix + b"NAXIS"])
76
+ if naxis == 0:
77
+ return None
78
+
79
+ if naxis == 1:
80
+ return 1, int(headers[prefix + b"NAXIS1"])
81
+ else:
82
+ return int(headers[prefix + b"NAXIS1"]), int(headers[prefix + b"NAXIS2"])
83
+
84
+ def _parse_headers(
85
+ self, headers: dict[bytes, bytes]
86
+ ) -> tuple[str, int, tuple[str | int, ...]]:
87
+ prefix = b""
88
+ decoder_name = "raw"
89
+ offset = 0
90
+ if (
91
+ headers.get(b"XTENSION") == b"'BINTABLE'"
92
+ and headers.get(b"ZIMAGE") == b"T"
93
+ and headers[b"ZCMPTYPE"] == b"'GZIP_1 '"
94
+ ):
95
+ no_prefix_size = self._get_size(headers, prefix) or (0, 0)
96
+ number_of_bits = int(headers[b"BITPIX"])
97
+ offset = no_prefix_size[0] * no_prefix_size[1] * (number_of_bits // 8)
98
+
99
+ prefix = b"Z"
100
+ decoder_name = "fits_gzip"
101
+
102
+ size = self._get_size(headers, prefix)
103
+ if not size:
104
+ return "", 0, ()
105
+
106
+ self._size = size
107
+
108
+ number_of_bits = int(headers[prefix + b"BITPIX"])
109
+ if number_of_bits == 8:
110
+ self._mode = "L"
111
+ elif number_of_bits == 16:
112
+ self._mode = "I;16"
113
+ elif number_of_bits == 32:
114
+ self._mode = "I"
115
+ elif number_of_bits in (-32, -64):
116
+ self._mode = "F"
117
+
118
+ args: tuple[str | int, ...]
119
+ if decoder_name == "raw":
120
+ args = (self.mode, 0, -1)
121
+ else:
122
+ args = (number_of_bits,)
123
+ return decoder_name, offset, args
124
+
125
+
126
+ class FitsGzipDecoder(ImageFile.PyDecoder):
127
+ _pulls_fd = True
128
+
129
+ def decode(self, buffer: Image.DecoderInput) -> tuple[int, int]:
130
+ assert self.fd is not None
131
+ with gzip.open(self.fd) as fp:
132
+ value = fp.read(self.state.xsize * self.state.ysize * 4)
133
+
134
+ rows = []
135
+ offset = 0
136
+ number_of_bits = min(self.args[0] // 8, 4)
137
+ for y in range(self.state.ysize):
138
+ row = bytearray()
139
+ for x in range(self.state.xsize):
140
+ row += value[offset + (4 - number_of_bits) : offset + 4]
141
+ offset += 4
142
+ rows.append(row)
143
+ self.set_as_raw(bytes([pixel for row in rows[::-1] for pixel in row]))
144
+ return -1, 0
145
+
146
+
147
+ # --------------------------------------------------------------------
148
+ # Registry
149
+
150
+ Image.register_open(FitsImageFile.format, FitsImageFile, _accept)
151
+ Image.register_decoder("fits_gzip", FitsGzipDecoder)
152
+
153
+ Image.register_extensions(FitsImageFile.format, [".fit", ".fits"])
.venv/lib/python3.11/site-packages/PIL/FliImagePlugin.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # The Python Imaging Library.
3
+ # $Id$
4
+ #
5
+ # FLI/FLC file handling.
6
+ #
7
+ # History:
8
+ # 95-09-01 fl Created
9
+ # 97-01-03 fl Fixed parser, setup decoder tile
10
+ # 98-07-15 fl Renamed offset attribute to avoid name clash
11
+ #
12
+ # Copyright (c) Secret Labs AB 1997-98.
13
+ # Copyright (c) Fredrik Lundh 1995-97.
14
+ #
15
+ # See the README file for information on usage and redistribution.
16
+ #
17
+ from __future__ import annotations
18
+
19
+ import os
20
+
21
+ from . import Image, ImageFile, ImagePalette
22
+ from ._binary import i16le as i16
23
+ from ._binary import i32le as i32
24
+ from ._binary import o8
25
+ from ._util import DeferredError
26
+
27
+ #
28
+ # decoder
29
+
30
+
31
+ def _accept(prefix: bytes) -> bool:
32
+ return (
33
+ len(prefix) >= 16
34
+ and i16(prefix, 4) in [0xAF11, 0xAF12]
35
+ and i16(prefix, 14) in [0, 3] # flags
36
+ )
37
+
38
+
39
+ ##
40
+ # Image plugin for the FLI/FLC animation format. Use the <b>seek</b>
41
+ # method to load individual frames.
42
+
43
+
44
+ class FliImageFile(ImageFile.ImageFile):
45
+ format = "FLI"
46
+ format_description = "Autodesk FLI/FLC Animation"
47
+ _close_exclusive_fp_after_loading = False
48
+
49
+ def _open(self) -> None:
50
+ # HEAD
51
+ assert self.fp is not None
52
+ s = self.fp.read(128)
53
+ if not (
54
+ _accept(s)
55
+ and s[20:22] == b"\x00" * 2
56
+ and s[42:80] == b"\x00" * 38
57
+ and s[88:] == b"\x00" * 40
58
+ ):
59
+ msg = "not an FLI/FLC file"
60
+ raise SyntaxError(msg)
61
+
62
+ # frames
63
+ self.n_frames = i16(s, 6)
64
+ self.is_animated = self.n_frames > 1
65
+
66
+ # image characteristics
67
+ self._mode = "P"
68
+ self._size = i16(s, 8), i16(s, 10)
69
+
70
+ # animation speed
71
+ duration = i32(s, 16)
72
+ magic = i16(s, 4)
73
+ if magic == 0xAF11:
74
+ duration = (duration * 1000) // 70
75
+ self.info["duration"] = duration
76
+
77
+ # look for palette
78
+ palette = [(a, a, a) for a in range(256)]
79
+
80
+ s = self.fp.read(16)
81
+
82
+ self.__offset = 128
83
+
84
+ if i16(s, 4) == 0xF100:
85
+ # prefix chunk; ignore it
86
+ self.fp.seek(self.__offset + i32(s))
87
+ s = self.fp.read(16)
88
+
89
+ if i16(s, 4) == 0xF1FA:
90
+ # look for palette chunk
91
+ number_of_subchunks = i16(s, 6)
92
+ chunk_size: int | None = None
93
+ for _ in range(number_of_subchunks):
94
+ if chunk_size is not None:
95
+ self.fp.seek(chunk_size - 6, os.SEEK_CUR)
96
+ s = self.fp.read(6)
97
+ chunk_type = i16(s, 4)
98
+ if chunk_type in (4, 11):
99
+ self._palette(palette, 2 if chunk_type == 11 else 0)
100
+ break
101
+ chunk_size = i32(s)
102
+ if not chunk_size:
103
+ break
104
+
105
+ self.palette = ImagePalette.raw(
106
+ "RGB", b"".join(o8(r) + o8(g) + o8(b) for (r, g, b) in palette)
107
+ )
108
+
109
+ # set things up to decode first frame
110
+ self.__frame = -1
111
+ self._fp = self.fp
112
+ self.__rewind = self.fp.tell()
113
+ self.seek(0)
114
+
115
+ def _palette(self, palette: list[tuple[int, int, int]], shift: int) -> None:
116
+ # load palette
117
+
118
+ i = 0
119
+ assert self.fp is not None
120
+ for e in range(i16(self.fp.read(2))):
121
+ s = self.fp.read(2)
122
+ i = i + s[0]
123
+ n = s[1]
124
+ if n == 0:
125
+ n = 256
126
+ s = self.fp.read(n * 3)
127
+ for n in range(0, len(s), 3):
128
+ r = s[n] << shift
129
+ g = s[n + 1] << shift
130
+ b = s[n + 2] << shift
131
+ palette[i] = (r, g, b)
132
+ i += 1
133
+
134
+ def seek(self, frame: int) -> None:
135
+ if not self._seek_check(frame):
136
+ return
137
+ if frame < self.__frame:
138
+ self._seek(0)
139
+
140
+ for f in range(self.__frame + 1, frame + 1):
141
+ self._seek(f)
142
+
143
+ def _seek(self, frame: int) -> None:
144
+ if isinstance(self._fp, DeferredError):
145
+ raise self._fp.ex
146
+ if frame == 0:
147
+ self.__frame = -1
148
+ self._fp.seek(self.__rewind)
149
+ self.__offset = 128
150
+ else:
151
+ # ensure that the previous frame was loaded
152
+ self.load()
153
+
154
+ if frame != self.__frame + 1:
155
+ msg = f"cannot seek to frame {frame}"
156
+ raise ValueError(msg)
157
+ self.__frame = frame
158
+
159
+ # move to next frame
160
+ self.fp = self._fp
161
+ self.fp.seek(self.__offset)
162
+
163
+ s = self.fp.read(4)
164
+ if not s:
165
+ msg = "missing frame size"
166
+ raise EOFError(msg)
167
+
168
+ framesize = i32(s)
169
+
170
+ self.decodermaxblock = framesize
171
+ self.tile = [ImageFile._Tile("fli", (0, 0) + self.size, self.__offset)]
172
+
173
+ self.__offset += framesize
174
+
175
+ def tell(self) -> int:
176
+ return self.__frame
177
+
178
+
179
+ #
180
+ # registry
181
+
182
+ Image.register_open(FliImageFile.format, FliImageFile, _accept)
183
+
184
+ Image.register_extensions(FliImageFile.format, [".fli", ".flc"])