diff --git a/.gitattributes b/.gitattributes index a6344aac8c09253b3b630fb776ae94478aa0275b..3f7475bbbc97cb795cba23b0483c195f19e58d00 100644 --- a/.gitattributes +++ b/.gitattributes @@ -33,3 +33,10 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text *.zip filter=lfs diff=lfs merge=lfs -text *.zst filter=lfs diff=lfs merge=lfs -text *tfevents* filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.11/site-packages/PIL/_imaging.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.11/site-packages/PIL/_imagingcms.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.11/site-packages/PIL/_imagingft.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.11/site-packages/PIL/_imagingmath.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.11/site-packages/PIL/_webp.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.11/site-packages/__pycache__/typing_extensions.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.11/site-packages/anndata/_core/__pycache__/merge.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text diff --git a/.venv/.gitignore b/.venv/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..f59ec20aabf5842d237244ece8c81ab184faeac1 --- /dev/null +++ b/.venv/.gitignore @@ -0,0 +1 @@ +* \ No newline at end of file diff --git a/.venv/.lock b/.venv/.lock new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/CACHEDIR.TAG b/.venv/CACHEDIR.TAG new file mode 100644 index 0000000000000000000000000000000000000000..bc1ecb967a482524e7736038de0df6e08f9ee452 --- /dev/null +++ b/.venv/CACHEDIR.TAG @@ -0,0 +1 @@ +Signature: 8a477f597d28d172789f06886806bc55 \ No newline at end of file diff --git a/.venv/bin/activate b/.venv/bin/activate new file mode 100644 index 0000000000000000000000000000000000000000..d8fb68a8408118684809fdf34780107eb523a125 --- /dev/null +++ b/.venv/bin/activate @@ -0,0 +1,130 @@ +# Copyright (c) 2020-202x The virtualenv developers +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +# This file must be used with "source bin/activate" *from bash* +# you cannot run it directly + +if ! [ -z "${SCRIPT_PATH+_}" ] ; then + _OLD_SCRIPT_PATH="$SCRIPT_PATH" +fi + +# Get script path (only used if environment is relocatable). +if [ -n "${BASH_VERSION:+x}" ] ; then + SCRIPT_PATH="${BASH_SOURCE[0]}" + if [ "$SCRIPT_PATH" = "$0" ]; then + # Only bash has a reasonably robust check for source'dness. + echo "You must source this script: \$ source $0" >&2 + exit 33 + fi +elif [ -n "${ZSH_VERSION:+x}" ] ; then + SCRIPT_PATH="${(%):-%x}" +elif [ -n "${KSH_VERSION:+x}" ] ; then + SCRIPT_PATH="${.sh.file}" +fi + +deactivate () { + unset -f pydoc >/dev/null 2>&1 || true + + # reset old environment variables + # ! [ -z ${VAR+_} ] returns true if VAR is declared at all + if ! [ -z "${_OLD_VIRTUAL_PATH:+_}" ] ; then + PATH="$_OLD_VIRTUAL_PATH" + export PATH + unset _OLD_VIRTUAL_PATH + fi + if ! [ -z "${_OLD_VIRTUAL_PYTHONHOME+_}" ] ; then + PYTHONHOME="$_OLD_VIRTUAL_PYTHONHOME" + export PYTHONHOME + unset _OLD_VIRTUAL_PYTHONHOME + fi + + # The hash command must be called to get it to forget past + # commands. Without forgetting past commands the $PATH changes + # we made may not be respected + hash -r 2>/dev/null + + if ! [ -z "${_OLD_VIRTUAL_PS1+_}" ] ; then + PS1="$_OLD_VIRTUAL_PS1" + export PS1 + unset _OLD_VIRTUAL_PS1 + fi + + unset VIRTUAL_ENV + unset VIRTUAL_ENV_PROMPT + if [ ! "${1-}" = "nondestructive" ] ; then + # Self destruct! + unset -f deactivate + fi +} + +# unset irrelevant variables +deactivate nondestructive + +VIRTUAL_ENV='/gpfs/projects/p32222/aTester/state_parse_repro/.venv' +if ([ "$OSTYPE" = "cygwin" ] || [ "$OSTYPE" = "msys" ]) && $(command -v cygpath &> /dev/null) ; then + VIRTUAL_ENV=$(cygpath -u "$VIRTUAL_ENV") +fi +export VIRTUAL_ENV + +# Unset the `SCRIPT_PATH` variable, now that the `VIRTUAL_ENV` variable +# has been set. This is important for relocatable environments. +if ! [ -z "${_OLD_SCRIPT_PATH+_}" ] ; then + SCRIPT_PATH="$_OLD_SCRIPT_PATH" + export SCRIPT_PATH + unset _OLD_SCRIPT_PATH +else + unset SCRIPT_PATH +fi + +_OLD_VIRTUAL_PATH="$PATH" +PATH="$VIRTUAL_ENV/bin:$PATH" +export PATH + +if [ "xstate_parse_repro" != x ] ; then + VIRTUAL_ENV_PROMPT="state_parse_repro" +else + VIRTUAL_ENV_PROMPT=$(basename "$VIRTUAL_ENV") +fi +export VIRTUAL_ENV_PROMPT + +# unset PYTHONHOME if set +if ! [ -z "${PYTHONHOME+_}" ] ; then + _OLD_VIRTUAL_PYTHONHOME="$PYTHONHOME" + unset PYTHONHOME +fi + +if [ -z "${VIRTUAL_ENV_DISABLE_PROMPT-}" ] ; then + _OLD_VIRTUAL_PS1="${PS1-}" + PS1="(${VIRTUAL_ENV_PROMPT}) ${PS1-}" + export PS1 +fi + +# Make sure to unalias pydoc if it's already there +alias pydoc 2>/dev/null >/dev/null && unalias pydoc || true + +pydoc () { + python -m pydoc "$@" +} + +# The hash command must be called to get it to forget past +# commands. Without forgetting past commands the $PATH changes +# we made may not be respected +hash -r 2>/dev/null diff --git a/.venv/bin/activate.bat b/.venv/bin/activate.bat new file mode 100644 index 0000000000000000000000000000000000000000..bdda09e28ea357f724b851b70e8f18547fa62031 --- /dev/null +++ b/.venv/bin/activate.bat @@ -0,0 +1,71 @@ +@REM Copyright (c) 2020-202x The virtualenv developers +@REM +@REM Permission is hereby granted, free of charge, to any person obtaining +@REM a copy of this software and associated documentation files (the +@REM "Software"), to deal in the Software without restriction, including +@REM without limitation the rights to use, copy, modify, merge, publish, +@REM distribute, sublicense, and/or sell copies of the Software, and to +@REM permit persons to whom the Software is furnished to do so, subject to +@REM the following conditions: +@REM +@REM The above copyright notice and this permission notice shall be +@REM included in all copies or substantial portions of the Software. +@REM +@REM THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +@REM EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +@REM MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +@REM NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +@REM LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +@REM OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +@REM WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +@REM This file is UTF-8 encoded, so we need to update the current code page while executing it +@for /f "tokens=2 delims=:." %%a in ('"%SystemRoot%\System32\chcp.com"') do @set _OLD_CODEPAGE=%%a +@if defined _OLD_CODEPAGE ( + @"%SystemRoot%\System32\chcp.com" 65001 > nul +) + +@for %%i in ("/gpfs/projects/p32222/aTester/state_parse_repro/.venv") do @set "VIRTUAL_ENV=%%~fi" + +@set "VIRTUAL_ENV_PROMPT=state_parse_repro" +@if NOT DEFINED VIRTUAL_ENV_PROMPT ( + @for %%d in ("%VIRTUAL_ENV%") do @set "VIRTUAL_ENV_PROMPT=%%~nxd" +) + +@if defined _OLD_VIRTUAL_PROMPT ( + @set "PROMPT=%_OLD_VIRTUAL_PROMPT%" +) else ( + @if not defined PROMPT ( + @set "PROMPT=$P$G" + ) + @if not defined VIRTUAL_ENV_DISABLE_PROMPT ( + @set "_OLD_VIRTUAL_PROMPT=%PROMPT%" + ) +) +@if not defined VIRTUAL_ENV_DISABLE_PROMPT ( + @set "PROMPT=(%VIRTUAL_ENV_PROMPT%) %PROMPT%" +) + +@REM Don't use () to avoid problems with them in %PATH% +@if defined _OLD_VIRTUAL_PYTHONHOME @goto ENDIFVHOME + @set "_OLD_VIRTUAL_PYTHONHOME=%PYTHONHOME%" +:ENDIFVHOME + +@set PYTHONHOME= + +@REM if defined _OLD_VIRTUAL_PATH ( +@if not defined _OLD_VIRTUAL_PATH @goto ENDIFVPATH1 + @set "PATH=%_OLD_VIRTUAL_PATH%" +:ENDIFVPATH1 +@REM ) else ( +@if defined _OLD_VIRTUAL_PATH @goto ENDIFVPATH2 + @set "_OLD_VIRTUAL_PATH=%PATH%" +:ENDIFVPATH2 + +@set "PATH=%VIRTUAL_ENV%\bin;%PATH%" + +:END +@if defined _OLD_CODEPAGE ( + @"%SystemRoot%\System32\chcp.com" %_OLD_CODEPAGE% > nul + @set _OLD_CODEPAGE= +) diff --git a/.venv/bin/activate.csh b/.venv/bin/activate.csh new file mode 100644 index 0000000000000000000000000000000000000000..9f13441237ff44acaadbe909a2fbe25c0f76e3d9 --- /dev/null +++ b/.venv/bin/activate.csh @@ -0,0 +1,76 @@ +# Copyright (c) 2020-202x The virtualenv developers +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +# This file must be used with "source bin/activate.csh" *from csh*. +# You cannot run it directly. +# Created by Davide Di Blasi . + +set newline='\ +' + +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' + +# Unset irrelevant variables. +deactivate nondestructive + +setenv VIRTUAL_ENV '/gpfs/projects/p32222/aTester/state_parse_repro/.venv' + +set _OLD_VIRTUAL_PATH="$PATH:q" +setenv PATH "$VIRTUAL_ENV:q/bin:$PATH:q" + + + +if ('state_parse_repro' != "") then + setenv VIRTUAL_ENV_PROMPT 'state_parse_repro' +else + setenv VIRTUAL_ENV_PROMPT "$VIRTUAL_ENV:t:q" +endif + +if ( $?VIRTUAL_ENV_DISABLE_PROMPT ) then + if ( $VIRTUAL_ENV_DISABLE_PROMPT == "" ) then + set do_prompt = "1" + else + set do_prompt = "0" + endif +else + set do_prompt = "1" +endif + +if ( $do_prompt == "1" ) then + # Could be in a non-interactive environment, + # in which case, $prompt is undefined and we wouldn't + # care about the prompt anyway. + if ( $?prompt ) then + set _OLD_VIRTUAL_PROMPT="$prompt:q" + if ( "$prompt:q" =~ *"$newline:q"* ) then + : + else + set prompt = '('"$VIRTUAL_ENV_PROMPT:q"') '"$prompt:q" + endif + endif +endif + +unset env_name +unset do_prompt + +alias pydoc python -m pydoc + +rehash diff --git a/.venv/bin/activate.fish b/.venv/bin/activate.fish new file mode 100644 index 0000000000000000000000000000000000000000..584d7cc1c19596fd7649aaaef17b9789796eac23 --- /dev/null +++ b/.venv/bin/activate.fish @@ -0,0 +1,124 @@ +# Copyright (c) 2020-202x The virtualenv developers +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +# This file must be used using `source bin/activate.fish` *within a running fish ( http://fishshell.com ) session*. +# Do not run it directly. + +function _bashify_path -d "Converts a fish path to something bash can recognize" + set fishy_path $argv + set bashy_path $fishy_path[1] + for path_part in $fishy_path[2..-1] + set bashy_path "$bashy_path:$path_part" + end + echo $bashy_path +end + +function _fishify_path -d "Converts a bash path to something fish can recognize" + echo $argv | tr ':' '\n' +end + +function deactivate -d 'Exit virtualenv mode and return to the normal environment.' + # reset old environment variables + if test -n "$_OLD_VIRTUAL_PATH" + # https://github.com/fish-shell/fish-shell/issues/436 altered PATH handling + if test (echo $FISH_VERSION | head -c 1) -lt 3 + set -gx PATH (_fishify_path "$_OLD_VIRTUAL_PATH") + else + set -gx PATH $_OLD_VIRTUAL_PATH + end + set -e _OLD_VIRTUAL_PATH + end + + if test -n "$_OLD_VIRTUAL_PYTHONHOME" + set -gx PYTHONHOME "$_OLD_VIRTUAL_PYTHONHOME" + set -e _OLD_VIRTUAL_PYTHONHOME + end + + if test -n "$_OLD_FISH_PROMPT_OVERRIDE" + and functions -q _old_fish_prompt + # Set an empty local `$fish_function_path` to allow the removal of `fish_prompt` using `functions -e`. + set -l fish_function_path + + # Erase virtualenv's `fish_prompt` and restore the original. + functions -e fish_prompt + functions -c _old_fish_prompt fish_prompt + functions -e _old_fish_prompt + set -e _OLD_FISH_PROMPT_OVERRIDE + end + + set -e VIRTUAL_ENV + set -e VIRTUAL_ENV_PROMPT + + if test "$argv[1]" != 'nondestructive' + # Self-destruct! + functions -e pydoc + functions -e deactivate + functions -e _bashify_path + functions -e _fishify_path + end +end + +# Unset irrelevant variables. +deactivate nondestructive + +set -gx VIRTUAL_ENV '/gpfs/projects/p32222/aTester/state_parse_repro/.venv' + +# https://github.com/fish-shell/fish-shell/issues/436 altered PATH handling +if test (echo $FISH_VERSION | head -c 1) -lt 3 + set -gx _OLD_VIRTUAL_PATH (_bashify_path $PATH) +else + set -gx _OLD_VIRTUAL_PATH $PATH +end +set -gx PATH "$VIRTUAL_ENV"'/bin' $PATH + +# Prompt override provided? +# If not, just use the environment name. +if test -n 'state_parse_repro' + set -gx VIRTUAL_ENV_PROMPT 'state_parse_repro' +else + set -gx VIRTUAL_ENV_PROMPT (basename "$VIRTUAL_ENV") +end + +# Unset `$PYTHONHOME` if set. +if set -q PYTHONHOME + set -gx _OLD_VIRTUAL_PYTHONHOME $PYTHONHOME + set -e PYTHONHOME +end + +function pydoc + python -m pydoc $argv +end + +if test -z "$VIRTUAL_ENV_DISABLE_PROMPT" + # Copy the current `fish_prompt` function as `_old_fish_prompt`. + functions -c fish_prompt _old_fish_prompt + + function fish_prompt + # Run the user's prompt first; it might depend on (pipe)status. + set -l prompt (_old_fish_prompt) + + printf '(%s) ' $VIRTUAL_ENV_PROMPT + + string join -- \n $prompt # handle multi-line prompts + end + + set -gx _OLD_FISH_PROMPT_OVERRIDE "$VIRTUAL_ENV" +end diff --git a/.venv/bin/activate.nu b/.venv/bin/activate.nu new file mode 100644 index 0000000000000000000000000000000000000000..4d35939b6ffd61fa6545914f6d382fb898c61b9d --- /dev/null +++ b/.venv/bin/activate.nu @@ -0,0 +1,117 @@ +# Copyright (c) 2020-202x The virtualenv developers +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +# virtualenv activation module +# Activate with `overlay use activate.nu` +# Deactivate with `deactivate`, as usual +# +# To customize the overlay name, you can call `overlay use activate.nu as foo`, +# but then simply `deactivate` won't work because it is just an alias to hide +# the "activate" overlay. You'd need to call `overlay hide foo` manually. + +export-env { + def is-string [x] { + ($x | describe) == 'string' + } + + def has-env [...names] { + $names | each {|n| + $n in $env + } | all {|i| $i == true} + } + + # Emulates a `test -z`, but better as it handles e.g 'false' + def is-env-true [name: string] { + if (has-env $name) { + # Try to parse 'true', '0', '1', and fail if not convertible + let parsed = (do -i { $env | get $name | into bool }) + if ($parsed | describe) == 'bool' { + $parsed + } else { + not ($env | get -i $name | is-empty) + } + } else { + false + } + } + + let virtual_env = '/gpfs/projects/p32222/aTester/state_parse_repro/.venv' + let bin = 'bin' + + let is_windows = ($nu.os-info.family) == 'windows' + let path_name = (if (has-env 'Path') { + 'Path' + } else { + 'PATH' + } + ) + + let venv_path = ([$virtual_env $bin] | path join) + let new_path = ($env | get $path_name | prepend $venv_path) + + # If there is no default prompt, then use the env name instead + let virtual_env_prompt = (if ('state_parse_repro' | is-empty) { + ($virtual_env | path basename) + } else { + 'state_parse_repro' + }) + + let new_env = { + $path_name : $new_path + VIRTUAL_ENV : $virtual_env + VIRTUAL_ENV_PROMPT : $virtual_env_prompt + } + + let new_env = (if (is-env-true 'VIRTUAL_ENV_DISABLE_PROMPT') { + $new_env + } else { + # Creating the new prompt for the session + let virtual_prefix = $'(char lparen)($virtual_env_prompt)(char rparen) ' + + # Back up the old prompt builder + let old_prompt_command = (if (has-env 'PROMPT_COMMAND') { + $env.PROMPT_COMMAND + } else { + '' + }) + + let new_prompt = (if (has-env 'PROMPT_COMMAND') { + if 'closure' in ($old_prompt_command | describe) { + {|| $'($virtual_prefix)(do $old_prompt_command)' } + } else { + {|| $'($virtual_prefix)($old_prompt_command)' } + } + } else { + {|| $'($virtual_prefix)' } + }) + + $new_env | merge { + PROMPT_COMMAND : $new_prompt + VIRTUAL_PREFIX : $virtual_prefix + } + }) + + # Environment variables that will be loaded as the virtual env + load-env $new_env +} + +export alias pydoc = python -m pydoc +export alias deactivate = overlay hide activate diff --git a/.venv/bin/activate.ps1 b/.venv/bin/activate.ps1 new file mode 100644 index 0000000000000000000000000000000000000000..66b808a10794f219fa8578136fcda8b53724e437 --- /dev/null +++ b/.venv/bin/activate.ps1 @@ -0,0 +1,82 @@ +# Copyright (c) 2020-202x The virtualenv developers +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +$script:THIS_PATH = $myinvocation.mycommand.path +$script:BASE_DIR = Split-Path (Resolve-Path "$THIS_PATH/..") -Parent + +function global:deactivate([switch] $NonDestructive) { + if (Test-Path variable:_OLD_VIRTUAL_PATH) { + $env:PATH = $variable:_OLD_VIRTUAL_PATH + Remove-Variable "_OLD_VIRTUAL_PATH" -Scope global + } + + if (Test-Path function:_old_virtual_prompt) { + $function:prompt = $function:_old_virtual_prompt + Remove-Item function:\_old_virtual_prompt + } + + if ($env:VIRTUAL_ENV) { + Remove-Item env:VIRTUAL_ENV -ErrorAction SilentlyContinue + } + + if ($env:VIRTUAL_ENV_PROMPT) { + Remove-Item env:VIRTUAL_ENV_PROMPT -ErrorAction SilentlyContinue + } + + if (!$NonDestructive) { + # Self destruct! + Remove-Item function:deactivate + Remove-Item function:pydoc + } +} + +function global:pydoc { + python -m pydoc $args +} + +# unset irrelevant variables +deactivate -nondestructive + +$VIRTUAL_ENV = $BASE_DIR +$env:VIRTUAL_ENV = $VIRTUAL_ENV + +if ("state_parse_repro" -ne "") { + $env:VIRTUAL_ENV_PROMPT = "state_parse_repro" +} +else { + $env:VIRTUAL_ENV_PROMPT = $( Split-Path $env:VIRTUAL_ENV -Leaf ) +} + +New-Variable -Scope global -Name _OLD_VIRTUAL_PATH -Value $env:PATH + +$env:PATH = "$env:VIRTUAL_ENV/bin:" + $env:PATH +if (!$env:VIRTUAL_ENV_DISABLE_PROMPT) { + function global:_old_virtual_prompt { + "" + } + $function:_old_virtual_prompt = $function:prompt + + function global:prompt { + # Add the custom prefix to the existing prompt + $previous_prompt_value = & $function:_old_virtual_prompt + ("(" + $env:VIRTUAL_ENV_PROMPT + ") " + $previous_prompt_value) + } +} diff --git a/.venv/bin/activate_this.py b/.venv/bin/activate_this.py new file mode 100644 index 0000000000000000000000000000000000000000..0ae3a3686514216be412e3af9e2fa6dd60de112a --- /dev/null +++ b/.venv/bin/activate_this.py @@ -0,0 +1,59 @@ +# Copyright (c) 2020-202x The virtualenv developers +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +""" +Activate virtualenv for current interpreter: + +import runpy +runpy.run_path(this_file) + +This can be used when you must use an existing Python interpreter, not the virtualenv bin/python. +""" # noqa: D415 + +from __future__ import annotations + +import os +import site +import sys + +try: + abs_file = os.path.abspath(__file__) +except NameError as exc: + msg = "You must use import runpy; runpy.run_path(this_file)" + raise AssertionError(msg) from exc + +bin_dir = os.path.dirname(abs_file) +base = bin_dir[: -len("bin") - 1] # strip away the bin part from the __file__, plus the path separator + +# prepend bin to PATH (this file is inside the bin directory) +os.environ["PATH"] = os.pathsep.join([bin_dir, *os.environ.get("PATH", "").split(os.pathsep)]) +os.environ["VIRTUAL_ENV"] = base # virtual env is right above bin directory +os.environ["VIRTUAL_ENV_PROMPT"] = "state_parse_repro" or os.path.basename(base) # noqa: SIM222 + +# add the virtual environments libraries to the host python import mechanism +prev_length = len(sys.path) +for lib in "../lib/python3.11/site-packages".split(os.pathsep): + path = os.path.realpath(os.path.join(bin_dir, lib)) + site.addsitedir(path) +sys.path[:] = sys.path[prev_length:] + sys.path[0:prev_length] + +sys.real_prefix = sys.prefix +sys.prefix = base diff --git a/.venv/bin/deactivate.bat b/.venv/bin/deactivate.bat new file mode 100644 index 0000000000000000000000000000000000000000..07041bc45129994cbb4b338f6fb61aaf502571fb --- /dev/null +++ b/.venv/bin/deactivate.bat @@ -0,0 +1,39 @@ +@REM Copyright (c) 2020-202x The virtualenv developers +@REM +@REM Permission is hereby granted, free of charge, to any person obtaining +@REM a copy of this software and associated documentation files (the +@REM "Software"), to deal in the Software without restriction, including +@REM without limitation the rights to use, copy, modify, merge, publish, +@REM distribute, sublicense, and/or sell copies of the Software, and to +@REM permit persons to whom the Software is furnished to do so, subject to +@REM the following conditions: +@REM +@REM The above copyright notice and this permission notice shall be +@REM included in all copies or substantial portions of the Software. +@REM +@REM THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +@REM EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +@REM MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +@REM NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +@REM LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +@REM OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +@REM WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +@set VIRTUAL_ENV= +@set VIRTUAL_ENV_PROMPT= + +@REM Don't use () to avoid problems with them in %PATH% +@if not defined _OLD_VIRTUAL_PROMPT @goto ENDIFVPROMPT + @set "PROMPT=%_OLD_VIRTUAL_PROMPT%" + @set _OLD_VIRTUAL_PROMPT= +:ENDIFVPROMPT + +@if not defined _OLD_VIRTUAL_PYTHONHOME @goto ENDIFVHOME + @set "PYTHONHOME=%_OLD_VIRTUAL_PYTHONHOME%" + @set _OLD_VIRTUAL_PYTHONHOME= +:ENDIFVHOME + +@if not defined _OLD_VIRTUAL_PATH @goto ENDIFVPATH + @set "PATH=%_OLD_VIRTUAL_PATH%" + @set _OLD_VIRTUAL_PATH= +:ENDIFVPATH \ No newline at end of file diff --git a/.venv/bin/f2py b/.venv/bin/f2py new file mode 100644 index 0000000000000000000000000000000000000000..879bab6583a230f97c33f9fc292d2fdd823601dd --- /dev/null +++ b/.venv/bin/f2py @@ -0,0 +1,10 @@ +#!/gpfs/projects/p32222/aTester/state_parse_repro/.venv/bin/python3 +# -*- coding: utf-8 -*- +import sys +from numpy.f2py.f2py2e import main +if __name__ == "__main__": + if sys.argv[0].endswith("-script.pyw"): + sys.argv[0] = sys.argv[0][:-11] + elif sys.argv[0].endswith(".exe"): + sys.argv[0] = sys.argv[0][:-4] + sys.exit(main()) diff --git a/.venv/bin/fonttools b/.venv/bin/fonttools new file mode 100644 index 0000000000000000000000000000000000000000..0b010c51637fc26a3cfb7833f51775c8fb305216 --- /dev/null +++ b/.venv/bin/fonttools @@ -0,0 +1,10 @@ +#!/gpfs/projects/p32222/aTester/state_parse_repro/.venv/bin/python3 +# -*- coding: utf-8 -*- +import sys +from fontTools.__main__ import main +if __name__ == "__main__": + if sys.argv[0].endswith("-script.pyw"): + sys.argv[0] = sys.argv[0][:-11] + elif sys.argv[0].endswith(".exe"): + sys.argv[0] = sys.argv[0][:-4] + sys.exit(main()) diff --git a/.venv/bin/hf b/.venv/bin/hf new file mode 100644 index 0000000000000000000000000000000000000000..36b5c0af8f1d8cbc9b16f5bfdede08d177f217af --- /dev/null +++ b/.venv/bin/hf @@ -0,0 +1,10 @@ +#!/gpfs/projects/p32222/aTester/state_parse_repro/.venv/bin/python3 +# -*- coding: utf-8 -*- +import sys +from huggingface_hub.cli.hf import main +if __name__ == "__main__": + if sys.argv[0].endswith("-script.pyw"): + sys.argv[0] = sys.argv[0][:-11] + elif sys.argv[0].endswith(".exe"): + sys.argv[0] = sys.argv[0][:-4] + sys.exit(main()) diff --git a/.venv/bin/httpx b/.venv/bin/httpx new file mode 100644 index 0000000000000000000000000000000000000000..1911fde35e20f373911fb63d2db32ba46fd22ec5 --- /dev/null +++ b/.venv/bin/httpx @@ -0,0 +1,10 @@ +#!/gpfs/projects/p32222/aTester/state_parse_repro/.venv/bin/python3 +# -*- coding: utf-8 -*- +import sys +from httpx import main +if __name__ == "__main__": + if sys.argv[0].endswith("-script.pyw"): + sys.argv[0] = sys.argv[0][:-11] + elif sys.argv[0].endswith(".exe"): + sys.argv[0] = sys.argv[0][:-4] + sys.exit(main()) diff --git a/.venv/bin/huggingface-cli b/.venv/bin/huggingface-cli new file mode 100644 index 0000000000000000000000000000000000000000..41e15d45994795d9e92d2ee6c12ad0fcaf6b2b08 --- /dev/null +++ b/.venv/bin/huggingface-cli @@ -0,0 +1,10 @@ +#!/gpfs/projects/p32222/aTester/state_parse_repro/.venv/bin/python3 +# -*- coding: utf-8 -*- +import sys +from huggingface_hub.cli.deprecated_cli import main +if __name__ == "__main__": + if sys.argv[0].endswith("-script.pyw"): + sys.argv[0] = sys.argv[0][:-11] + elif sys.argv[0].endswith(".exe"): + sys.argv[0] = sys.argv[0][:-4] + sys.exit(main()) diff --git a/.venv/bin/idna b/.venv/bin/idna new file mode 100644 index 0000000000000000000000000000000000000000..e6c977348cdaf8aa8cc3f228497d8e00dd23d1b1 --- /dev/null +++ b/.venv/bin/idna @@ -0,0 +1,10 @@ +#!/gpfs/projects/p32222/aTester/state_parse_repro/.venv/bin/python3 +# -*- coding: utf-8 -*- +import sys +from idna.cli import main +if __name__ == "__main__": + if sys.argv[0].endswith("-script.pyw"): + sys.argv[0] = sys.argv[0][:-11] + elif sys.argv[0].endswith(".exe"): + sys.argv[0] = sys.argv[0][:-4] + sys.exit(main()) diff --git a/.venv/bin/natsort b/.venv/bin/natsort new file mode 100644 index 0000000000000000000000000000000000000000..62a0bedd3950ab4c5916b888d6de978b0c5fea1d --- /dev/null +++ b/.venv/bin/natsort @@ -0,0 +1,10 @@ +#!/gpfs/projects/p32222/aTester/state_parse_repro/.venv/bin/python3 +# -*- coding: utf-8 -*- +import sys +from natsort.__main__ import main +if __name__ == "__main__": + if sys.argv[0].endswith("-script.pyw"): + sys.argv[0] = sys.argv[0][:-11] + elif sys.argv[0].endswith(".exe"): + sys.argv[0] = sys.argv[0][:-4] + sys.exit(main()) diff --git a/.venv/bin/numba b/.venv/bin/numba new file mode 100644 index 0000000000000000000000000000000000000000..7e789f2a7ac38b23133e29875e5466ef05382164 --- /dev/null +++ b/.venv/bin/numba @@ -0,0 +1,8 @@ +#!/gpfs/projects/p32222/aTester/state_parse_repro/.venv/bin/python3 +# -*- coding: UTF-8 -*- +from __future__ import print_function, division, absolute_import + +from numba.misc.numba_entry import main + +if __name__ == "__main__": + main() diff --git a/.venv/bin/numpy-config b/.venv/bin/numpy-config new file mode 100644 index 0000000000000000000000000000000000000000..a3363d0041b1d29e969fdce6bf699c7e06a14454 --- /dev/null +++ b/.venv/bin/numpy-config @@ -0,0 +1,10 @@ +#!/gpfs/projects/p32222/aTester/state_parse_repro/.venv/bin/python3 +# -*- coding: utf-8 -*- +import sys +from numpy._configtool import main +if __name__ == "__main__": + if sys.argv[0].endswith("-script.pyw"): + sys.argv[0] = sys.argv[0][:-11] + elif sys.argv[0].endswith(".exe"): + sys.argv[0] = sys.argv[0][:-4] + sys.exit(main()) diff --git a/.venv/bin/pip b/.venv/bin/pip new file mode 100644 index 0000000000000000000000000000000000000000..007ddde362cd97b8b1ee11733ed47676ddcd14bf --- /dev/null +++ b/.venv/bin/pip @@ -0,0 +1,10 @@ +#!/gpfs/projects/p32222/aTester/state_parse_repro/.venv/bin/python3 +# -*- coding: utf-8 -*- +import sys +from pip._internal.cli.main import main +if __name__ == "__main__": + if sys.argv[0].endswith("-script.pyw"): + sys.argv[0] = sys.argv[0][:-11] + elif sys.argv[0].endswith(".exe"): + sys.argv[0] = sys.argv[0][:-4] + sys.exit(main()) diff --git a/.venv/bin/pip3 b/.venv/bin/pip3 new file mode 100644 index 0000000000000000000000000000000000000000..007ddde362cd97b8b1ee11733ed47676ddcd14bf --- /dev/null +++ b/.venv/bin/pip3 @@ -0,0 +1,10 @@ +#!/gpfs/projects/p32222/aTester/state_parse_repro/.venv/bin/python3 +# -*- coding: utf-8 -*- +import sys +from pip._internal.cli.main import main +if __name__ == "__main__": + if sys.argv[0].endswith("-script.pyw"): + sys.argv[0] = sys.argv[0][:-11] + elif sys.argv[0].endswith(".exe"): + sys.argv[0] = sys.argv[0][:-4] + sys.exit(main()) diff --git a/.venv/bin/pip3.11 b/.venv/bin/pip3.11 new file mode 100644 index 0000000000000000000000000000000000000000..007ddde362cd97b8b1ee11733ed47676ddcd14bf --- /dev/null +++ b/.venv/bin/pip3.11 @@ -0,0 +1,10 @@ +#!/gpfs/projects/p32222/aTester/state_parse_repro/.venv/bin/python3 +# -*- coding: utf-8 -*- +import sys +from pip._internal.cli.main import main +if __name__ == "__main__": + if sys.argv[0].endswith("-script.pyw"): + sys.argv[0] = sys.argv[0][:-11] + elif sys.argv[0].endswith(".exe"): + sys.argv[0] = sys.argv[0][:-4] + sys.exit(main()) diff --git a/.venv/bin/pydoc.bat b/.venv/bin/pydoc.bat new file mode 100644 index 0000000000000000000000000000000000000000..daa20590b181e9f5a1f4f642f6c4eaf471cff00f --- /dev/null +++ b/.venv/bin/pydoc.bat @@ -0,0 +1,22 @@ +@REM Copyright (c) 2020-202x The virtualenv developers +@REM +@REM Permission is hereby granted, free of charge, to any person obtaining +@REM a copy of this software and associated documentation files (the +@REM "Software"), to deal in the Software without restriction, including +@REM without limitation the rights to use, copy, modify, merge, publish, +@REM distribute, sublicense, and/or sell copies of the Software, and to +@REM permit persons to whom the Software is furnished to do so, subject to +@REM the following conditions: +@REM +@REM The above copyright notice and this permission notice shall be +@REM included in all copies or substantial portions of the Software. +@REM +@REM THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +@REM EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +@REM MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +@REM NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +@REM LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +@REM OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +@REM WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +python.exe -m pydoc %* \ No newline at end of file diff --git a/.venv/bin/pyftmerge b/.venv/bin/pyftmerge new file mode 100644 index 0000000000000000000000000000000000000000..d8389729e0498d3930a3b7085e3155c49eaef19b --- /dev/null +++ b/.venv/bin/pyftmerge @@ -0,0 +1,10 @@ +#!/gpfs/projects/p32222/aTester/state_parse_repro/.venv/bin/python3 +# -*- coding: utf-8 -*- +import sys +from fontTools.merge import main +if __name__ == "__main__": + if sys.argv[0].endswith("-script.pyw"): + sys.argv[0] = sys.argv[0][:-11] + elif sys.argv[0].endswith(".exe"): + sys.argv[0] = sys.argv[0][:-4] + sys.exit(main()) diff --git a/.venv/bin/pyftsubset b/.venv/bin/pyftsubset new file mode 100644 index 0000000000000000000000000000000000000000..bbf6f5b682b8060388fc8ce65bac1467ecbe2108 --- /dev/null +++ b/.venv/bin/pyftsubset @@ -0,0 +1,10 @@ +#!/gpfs/projects/p32222/aTester/state_parse_repro/.venv/bin/python3 +# -*- coding: utf-8 -*- +import sys +from fontTools.subset import main +if __name__ == "__main__": + if sys.argv[0].endswith("-script.pyw"): + sys.argv[0] = sys.argv[0][:-11] + elif sys.argv[0].endswith(".exe"): + sys.argv[0] = sys.argv[0][:-4] + sys.exit(main()) diff --git a/.venv/bin/python b/.venv/bin/python new file mode 100644 index 0000000000000000000000000000000000000000..1164cdc7c8682e83a75bf62f2831aa595859fbed Binary files /dev/null and b/.venv/bin/python differ diff --git a/.venv/bin/python3 b/.venv/bin/python3 new file mode 100644 index 0000000000000000000000000000000000000000..1164cdc7c8682e83a75bf62f2831aa595859fbed Binary files /dev/null and b/.venv/bin/python3 differ diff --git a/.venv/bin/python3.11 b/.venv/bin/python3.11 new file mode 100644 index 0000000000000000000000000000000000000000..1164cdc7c8682e83a75bf62f2831aa595859fbed Binary files /dev/null and b/.venv/bin/python3.11 differ diff --git a/.venv/bin/scanpy b/.venv/bin/scanpy new file mode 100644 index 0000000000000000000000000000000000000000..f7462a1f7091974cc185b4e9ae3ad02337f5cb01 --- /dev/null +++ b/.venv/bin/scanpy @@ -0,0 +1,10 @@ +#!/gpfs/projects/p32222/aTester/state_parse_repro/.venv/bin/python3 +# -*- coding: utf-8 -*- +import sys +from scanpy.cli import console_main +if __name__ == "__main__": + if sys.argv[0].endswith("-script.pyw"): + sys.argv[0] = sys.argv[0][:-11] + elif sys.argv[0].endswith(".exe"): + sys.argv[0] = sys.argv[0][:-4] + sys.exit(console_main()) diff --git a/.venv/bin/session-info b/.venv/bin/session-info new file mode 100644 index 0000000000000000000000000000000000000000..f09ccc6ad6004d13d739ab478eb2c5c25c36ff51 --- /dev/null +++ b/.venv/bin/session-info @@ -0,0 +1,10 @@ +#!/gpfs/projects/p32222/aTester/state_parse_repro/.venv/bin/python3 +# -*- coding: utf-8 -*- +import sys +from session_info2.cli import main +if __name__ == "__main__": + if sys.argv[0].endswith("-script.pyw"): + sys.argv[0] = sys.argv[0][:-11] + elif sys.argv[0].endswith(".exe"): + sys.argv[0] = sys.argv[0][:-4] + sys.exit(main()) diff --git a/.venv/bin/session-info2 b/.venv/bin/session-info2 new file mode 100644 index 0000000000000000000000000000000000000000..f09ccc6ad6004d13d739ab478eb2c5c25c36ff51 --- /dev/null +++ b/.venv/bin/session-info2 @@ -0,0 +1,10 @@ +#!/gpfs/projects/p32222/aTester/state_parse_repro/.venv/bin/python3 +# -*- coding: utf-8 -*- +import sys +from session_info2.cli import main +if __name__ == "__main__": + if sys.argv[0].endswith("-script.pyw"): + sys.argv[0] = sys.argv[0][:-11] + elif sys.argv[0].endswith(".exe"): + sys.argv[0] = sys.argv[0][:-4] + sys.exit(main()) diff --git a/.venv/bin/tiny-agents b/.venv/bin/tiny-agents new file mode 100644 index 0000000000000000000000000000000000000000..6b9c1df803d4a1305a4befb5960aacc006dc3a09 --- /dev/null +++ b/.venv/bin/tiny-agents @@ -0,0 +1,10 @@ +#!/gpfs/projects/p32222/aTester/state_parse_repro/.venv/bin/python3 +# -*- coding: utf-8 -*- +import sys +from huggingface_hub.inference._mcp.cli import app +if __name__ == "__main__": + if sys.argv[0].endswith("-script.pyw"): + sys.argv[0] = sys.argv[0][:-11] + elif sys.argv[0].endswith(".exe"): + sys.argv[0] = sys.argv[0][:-4] + sys.exit(app()) diff --git a/.venv/bin/tqdm b/.venv/bin/tqdm new file mode 100644 index 0000000000000000000000000000000000000000..d048e2dfa552a2664d45fc8028da14dc8d6796df --- /dev/null +++ b/.venv/bin/tqdm @@ -0,0 +1,10 @@ +#!/gpfs/projects/p32222/aTester/state_parse_repro/.venv/bin/python3 +# -*- coding: utf-8 -*- +import sys +from tqdm.cli import main +if __name__ == "__main__": + if sys.argv[0].endswith("-script.pyw"): + sys.argv[0] = sys.argv[0][:-11] + elif sys.argv[0].endswith(".exe"): + sys.argv[0] = sys.argv[0][:-4] + sys.exit(main()) diff --git a/.venv/bin/ttx b/.venv/bin/ttx new file mode 100644 index 0000000000000000000000000000000000000000..6e4b808148cb9f3789dbc950c0104d8317e71780 --- /dev/null +++ b/.venv/bin/ttx @@ -0,0 +1,10 @@ +#!/gpfs/projects/p32222/aTester/state_parse_repro/.venv/bin/python3 +# -*- coding: utf-8 -*- +import sys +from fontTools.ttx import main +if __name__ == "__main__": + if sys.argv[0].endswith("-script.pyw"): + sys.argv[0] = sys.argv[0][:-11] + elif sys.argv[0].endswith(".exe"): + sys.argv[0] = sys.argv[0][:-4] + sys.exit(main()) diff --git a/.venv/bin/zarr b/.venv/bin/zarr new file mode 100644 index 0000000000000000000000000000000000000000..b59c48c6154247b7f41c3bb03de36c21af13e1e3 --- /dev/null +++ b/.venv/bin/zarr @@ -0,0 +1,10 @@ +#!/gpfs/projects/p32222/aTester/state_parse_repro/.venv/bin/python3 +# -*- coding: utf-8 -*- +import sys +from zarr._cli.cli import app +if __name__ == "__main__": + if sys.argv[0].endswith("-script.pyw"): + sys.argv[0] = sys.argv[0][:-11] + elif sys.argv[0].endswith(".exe"): + sys.argv[0] = sys.argv[0][:-4] + sys.exit(app()) diff --git a/.venv/lib/python3.11/site-packages/PIL/AvifImagePlugin.py b/.venv/lib/python3.11/site-packages/PIL/AvifImagePlugin.py new file mode 100644 index 0000000000000000000000000000000000000000..6e7d0f738b3ee6bb241eede41178c134555adf9f --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/AvifImagePlugin.py @@ -0,0 +1,295 @@ +from __future__ import annotations + +import os +from io import BytesIO +from typing import IO + +from . import ExifTags, Image, ImageFile, ImageSequence + +try: + from . import _avif + + SUPPORTED = True +except ImportError: + SUPPORTED = False + +# Decoder options as module globals, until there is a way to pass parameters +# to Image.open (see https://github.com/python-pillow/Pillow/issues/569) +DECODE_CODEC_CHOICE = "auto" +DEFAULT_MAX_THREADS = 0 + + +def get_codec_version(codec_name: str) -> str | None: + versions = _avif.codec_versions() + for version in versions.split(", "): + if version.split(" [")[0] == codec_name: + return version.split(":")[-1].split(" ")[0] + return None + + +def _accept(prefix: bytes) -> bool | str: + if prefix[4:8] != b"ftyp": + return False + major_brand = prefix[8:12] + if major_brand in ( + # coding brands + b"avif", + b"avis", + # We accept files with AVIF container brands; we can't yet know if + # the ftyp box has the correct compatible brands, but if it doesn't + # then the plugin will raise a SyntaxError which Pillow will catch + # before moving on to the next plugin that accepts the file. + # + # Also, because this file might not actually be an AVIF file, we + # don't raise an error if AVIF support isn't properly compiled. + b"mif1", + b"msf1", + ): + if not SUPPORTED: + return ( + "image file could not be identified because AVIF support not installed" + ) + return True + return False + + +def _get_default_max_threads() -> int: + if DEFAULT_MAX_THREADS: + return DEFAULT_MAX_THREADS + if hasattr(os, "sched_getaffinity"): + return len(os.sched_getaffinity(0)) + else: + return os.cpu_count() or 1 + + +class AvifImageFile(ImageFile.ImageFile): + format = "AVIF" + format_description = "AVIF image" + __frame = -1 + + def _open(self) -> None: + if not SUPPORTED: + msg = "image file could not be opened because AVIF support not installed" + raise SyntaxError(msg) + + if DECODE_CODEC_CHOICE != "auto" and not _avif.decoder_codec_available( + DECODE_CODEC_CHOICE + ): + msg = "Invalid opening codec" + raise ValueError(msg) + + assert self.fp is not None + self._decoder = _avif.AvifDecoder( + self.fp.read(), + DECODE_CODEC_CHOICE, + _get_default_max_threads(), + ) + + # Get info from decoder + self._size, self.n_frames, self._mode, icc, exif, exif_orientation, xmp = ( + self._decoder.get_info() + ) + self.is_animated = self.n_frames > 1 + + if icc: + self.info["icc_profile"] = icc + if xmp: + self.info["xmp"] = xmp + + if exif_orientation != 1 or exif: + exif_data = Image.Exif() + if exif: + exif_data.load(exif) + original_orientation = exif_data.get(ExifTags.Base.Orientation, 1) + else: + original_orientation = 1 + if exif_orientation != original_orientation: + exif_data[ExifTags.Base.Orientation] = exif_orientation + exif = exif_data.tobytes() + if exif: + self.info["exif"] = exif + self.seek(0) + + def seek(self, frame: int) -> None: + if not self._seek_check(frame): + return + + # Set tile + self.__frame = frame + self.tile = [ImageFile._Tile("raw", (0, 0) + self.size, 0, self.mode)] + + def load(self) -> Image.core.PixelAccess | None: + if self.tile: + # We need to load the image data for this frame + data, timescale, pts_in_timescales, duration_in_timescales = ( + self._decoder.get_frame(self.__frame) + ) + self.info["timestamp"] = round(1000 * (pts_in_timescales / timescale)) + self.info["duration"] = round(1000 * (duration_in_timescales / timescale)) + + if self.fp and self._exclusive_fp: + self.fp.close() + self.fp = BytesIO(data) + + return super().load() + + def load_seek(self, pos: int) -> None: + pass + + def tell(self) -> int: + return self.__frame + + +def _save_all(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + _save(im, fp, filename, save_all=True) + + +def _save( + im: Image.Image, fp: IO[bytes], filename: str | bytes, save_all: bool = False +) -> None: + info = im.encoderinfo.copy() + if save_all: + append_images = list(info.get("append_images", [])) + else: + append_images = [] + + grayscale_modes = {"1", "L", "I", "I;16", "I;16L", "I;16B", "I;16N", "F"} + grayscale = all( + frame.mode in grayscale_modes + for ims in [im] + append_images + for frame in ImageSequence.Iterator(ims) + ) + + quality = info.get("quality", 75) + if not isinstance(quality, int) or quality < 0 or quality > 100: + msg = "Invalid quality setting" + raise ValueError(msg) + + duration = info.get("duration", 0) + subsampling = info.get("subsampling", "4:0:0" if grayscale else "4:2:0") + speed = info.get("speed", 6) + max_threads = info.get("max_threads", _get_default_max_threads()) + codec = info.get("codec", "auto") + if codec != "auto" and not _avif.encoder_codec_available(codec): + msg = "Invalid saving codec" + raise ValueError(msg) + range_ = info.get("range", "full") + tile_rows_log2 = info.get("tile_rows", 0) + tile_cols_log2 = info.get("tile_cols", 0) + alpha_premultiplied = bool(info.get("alpha_premultiplied", False)) + autotiling = bool(info.get("autotiling", tile_rows_log2 == tile_cols_log2 == 0)) + + icc_profile = info.get("icc_profile", im.info.get("icc_profile")) + exif_orientation = 1 + if exif := info.get("exif"): + if isinstance(exif, Image.Exif): + exif_data = exif + else: + exif_data = Image.Exif() + exif_data.load(exif) + if ExifTags.Base.Orientation in exif_data: + exif_orientation = exif_data.pop(ExifTags.Base.Orientation) + exif = exif_data.tobytes() if exif_data else b"" + elif isinstance(exif, Image.Exif): + exif = exif_data.tobytes() + + xmp = info.get("xmp") + + if isinstance(xmp, str): + xmp = xmp.encode("utf-8") + + advanced = info.get("advanced") + if advanced is not None: + if isinstance(advanced, dict): + advanced = advanced.items() + try: + advanced = tuple(advanced) + except TypeError: + invalid = True + else: + invalid = any(not isinstance(v, tuple) or len(v) != 2 for v in advanced) + if invalid: + msg = ( + "advanced codec options must be a dict of key-value string " + "pairs or a series of key-value two-tuples" + ) + raise ValueError(msg) + + # Setup the AVIF encoder + enc = _avif.AvifEncoder( + im.size, + subsampling, + quality, + speed, + max_threads, + codec, + range_, + tile_rows_log2, + tile_cols_log2, + alpha_premultiplied, + autotiling, + icc_profile or b"", + exif or b"", + exif_orientation, + xmp or b"", + advanced, + ) + + # Add each frame + frame_idx = 0 + frame_duration = 0 + cur_idx = im.tell() + is_single_frame = not append_images and not getattr(im, "is_animated", False) + try: + for ims in [im] + append_images: + for frame in ImageSequence.Iterator(ims): + # Make sure image mode is supported + rawmode = frame.mode + if ims.mode not in {"L", "RGB", "RGBA"}: + if ims.has_transparency_data: + rawmode = "RGBA" + elif ims.mode in grayscale_modes: + rawmode = "L" + else: + rawmode = "RGB" + frame = frame.convert(rawmode) + + # Update frame duration + if isinstance(duration, (list, tuple)): + frame_duration = duration[frame_idx] + else: + frame_duration = duration + + # Append the frame to the animation encoder + enc.add( + frame.tobytes("raw", rawmode), + frame_duration, + frame.size, + rawmode, + is_single_frame, + ) + + # Update frame index + frame_idx += 1 + + if not save_all: + break + + finally: + im.seek(cur_idx) + + # Get the final output from the encoder + data = enc.finish() + if data is None: + msg = "cannot write file as AVIF (encoder returned None)" + raise OSError(msg) + + fp.write(data) + + +Image.register_open(AvifImageFile.format, AvifImageFile, _accept) +if SUPPORTED: + Image.register_save(AvifImageFile.format, _save) + Image.register_save_all(AvifImageFile.format, _save_all) + Image.register_extensions(AvifImageFile.format, [".avif", ".avifs"]) + Image.register_mime(AvifImageFile.format, "image/avif") diff --git a/.venv/lib/python3.11/site-packages/PIL/BdfFontFile.py b/.venv/lib/python3.11/site-packages/PIL/BdfFontFile.py new file mode 100644 index 0000000000000000000000000000000000000000..098779bfd6e7386555baef361b01e9167dc6c168 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/BdfFontFile.py @@ -0,0 +1,124 @@ +# +# The Python Imaging Library +# $Id$ +# +# bitmap distribution font (bdf) file parser +# +# history: +# 1996-05-16 fl created (as bdf2pil) +# 1997-08-25 fl converted to FontFile driver +# 2001-05-25 fl removed bogus __init__ call +# 2002-11-20 fl robustification (from Kevin Cazabon, Dmitry Vasiliev) +# 2003-04-22 fl more robustification (from Graham Dumpleton) +# +# Copyright (c) 1997-2003 by Secret Labs AB. +# Copyright (c) 1997-2003 by Fredrik Lundh. +# +# See the README file for information on usage and redistribution. +# + +""" +Parse X Bitmap Distribution Format (BDF) +""" + +from __future__ import annotations + +from typing import BinaryIO + +from . import FontFile, Image + + +def bdf_char( + f: BinaryIO, +) -> ( + tuple[ + str, + int, + tuple[tuple[int, int], tuple[int, int, int, int], tuple[int, int, int, int]], + Image.Image, + ] + | None +): + # skip to STARTCHAR + while True: + s = f.readline() + if not s: + return None + if s.startswith(b"STARTCHAR"): + break + id = s[9:].strip().decode("ascii") + + # load symbol properties + props = {} + while True: + s = f.readline() + if not s or s.startswith(b"BITMAP"): + break + i = s.find(b" ") + props[s[:i].decode("ascii")] = s[i + 1 : -1].decode("ascii") + + # load bitmap + bitmap = bytearray() + while True: + s = f.readline() + if not s or s.startswith(b"ENDCHAR"): + break + bitmap += s[:-1] + + # The word BBX + # followed by the width in x (BBw), height in y (BBh), + # and x and y displacement (BBxoff0, BByoff0) + # of the lower left corner from the origin of the character. + width, height, x_disp, y_disp = (int(p) for p in props["BBX"].split()) + Image._decompression_bomb_check((width, height)) + + # The word DWIDTH + # followed by the width in x and y of the character in device pixels. + dwx, dwy = (int(p) for p in props["DWIDTH"].split()) + + bbox = ( + (dwx, dwy), + (x_disp, -y_disp - height, width + x_disp, -y_disp), + (0, 0, width, height), + ) + + try: + im = Image.frombytes("1", (width, height), bitmap, "hex", "1") + except ValueError: + # deal with zero-width characters + im = Image.new("1", (width, height)) + + return id, int(props["ENCODING"]), bbox, im + + +class BdfFontFile(FontFile.FontFile): + """Font file plugin for the X11 BDF format.""" + + def __init__(self, fp: BinaryIO) -> None: + super().__init__() + + s = fp.readline() + if not s.startswith(b"STARTFONT 2.1"): + msg = "not a valid BDF file" + raise SyntaxError(msg) + + props = {} + comments = [] + + while True: + s = fp.readline() + if not s or s.startswith(b"ENDPROPERTIES"): + break + i = s.find(b" ") + props[s[:i].decode("ascii")] = s[i + 1 : -1].decode("ascii") + if s[:i] in [b"COMMENT", b"COPYRIGHT"]: + if s.find(b"LogicalFontDescription") < 0: + comments.append(s[i + 1 : -1].decode("ascii")) + + while True: + c = bdf_char(fp) + if not c: + break + id, ch, (xy, dst, src), im = c + if 0 <= ch < len(self.glyph): + self.glyph[ch] = xy, dst, src, im diff --git a/.venv/lib/python3.11/site-packages/PIL/BlpImagePlugin.py b/.venv/lib/python3.11/site-packages/PIL/BlpImagePlugin.py new file mode 100644 index 0000000000000000000000000000000000000000..b4aaebd7b6cfd8318b67cfda2c7e8a1a19e7d07b --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/BlpImagePlugin.py @@ -0,0 +1,498 @@ +""" +Blizzard Mipmap Format (.blp) +Jerome Leclanche + +The contents of this file are hereby released in the public domain (CC0) +Full text of the CC0 license: + https://creativecommons.org/publicdomain/zero/1.0/ + +BLP1 files, used mostly in Warcraft III, are not fully supported. +All types of BLP2 files used in World of Warcraft are supported. + +The BLP file structure consists of a header, up to 16 mipmaps of the +texture + +Texture sizes must be powers of two, though the two dimensions do +not have to be equal; 512x256 is valid, but 512x200 is not. +The first mipmap (mipmap #0) is the full size image; each subsequent +mipmap halves both dimensions. The final mipmap should be 1x1. + +BLP files come in many different flavours: +* JPEG-compressed (type == 0) - only supported for BLP1. +* RAW images (type == 1, encoding == 1). Each mipmap is stored as an + array of 8-bit values, one per pixel, left to right, top to bottom. + Each value is an index to the palette. +* DXT-compressed (type == 1, encoding == 2): +- DXT1 compression is used if alpha_encoding == 0. + - An additional alpha bit is used if alpha_depth == 1. + - DXT3 compression is used if alpha_encoding == 1. + - DXT5 compression is used if alpha_encoding == 7. +""" + +from __future__ import annotations + +import abc +import os +import struct +from enum import IntEnum +from io import BytesIO +from typing import IO + +from . import Image, ImageFile + + +class Format(IntEnum): + JPEG = 0 + + +class Encoding(IntEnum): + UNCOMPRESSED = 1 + DXT = 2 + UNCOMPRESSED_RAW_BGRA = 3 + + +class AlphaEncoding(IntEnum): + DXT1 = 0 + DXT3 = 1 + DXT5 = 7 + + +def unpack_565(i: int) -> tuple[int, int, int]: + return ((i >> 11) & 0x1F) << 3, ((i >> 5) & 0x3F) << 2, (i & 0x1F) << 3 + + +def decode_dxt1( + data: bytes, alpha: bool = False +) -> tuple[bytearray, bytearray, bytearray, bytearray]: + """ + input: one "row" of data (i.e. will produce 4*width pixels) + """ + + blocks = len(data) // 8 # number of blocks in row + ret = (bytearray(), bytearray(), bytearray(), bytearray()) + + for block_index in range(blocks): + # Decode next 8-byte block. + idx = block_index * 8 + color0, color1, bits = struct.unpack_from("> 2 + + a = 0xFF + if control == 0: + r, g, b = r0, g0, b0 + elif control == 1: + r, g, b = r1, g1, b1 + elif control == 2: + if color0 > color1: + r = (2 * r0 + r1) // 3 + g = (2 * g0 + g1) // 3 + b = (2 * b0 + b1) // 3 + else: + r = (r0 + r1) // 2 + g = (g0 + g1) // 2 + b = (b0 + b1) // 2 + elif control == 3: + if color0 > color1: + r = (2 * r1 + r0) // 3 + g = (2 * g1 + g0) // 3 + b = (2 * b1 + b0) // 3 + else: + r, g, b, a = 0, 0, 0, 0 + + if alpha: + ret[j].extend([r, g, b, a]) + else: + ret[j].extend([r, g, b]) + + return ret + + +def decode_dxt3(data: bytes) -> tuple[bytearray, bytearray, bytearray, bytearray]: + """ + input: one "row" of data (i.e. will produce 4*width pixels) + """ + + blocks = len(data) // 16 # number of blocks in row + ret = (bytearray(), bytearray(), bytearray(), bytearray()) + + for block_index in range(blocks): + idx = block_index * 16 + block = data[idx : idx + 16] + # Decode next 16-byte block. + bits = struct.unpack_from("<8B", block) + color0, color1 = struct.unpack_from(">= 4 + else: + high = True + a &= 0xF + a *= 17 # We get a value between 0 and 15 + + color_code = (code >> 2 * (4 * j + i)) & 0x03 + + if color_code == 0: + r, g, b = r0, g0, b0 + elif color_code == 1: + r, g, b = r1, g1, b1 + elif color_code == 2: + r = (2 * r0 + r1) // 3 + g = (2 * g0 + g1) // 3 + b = (2 * b0 + b1) // 3 + elif color_code == 3: + r = (2 * r1 + r0) // 3 + g = (2 * g1 + g0) // 3 + b = (2 * b1 + b0) // 3 + + ret[j].extend([r, g, b, a]) + + return ret + + +def decode_dxt5(data: bytes) -> tuple[bytearray, bytearray, bytearray, bytearray]: + """ + input: one "row" of data (i.e. will produce 4 * width pixels) + """ + + blocks = len(data) // 16 # number of blocks in row + ret = (bytearray(), bytearray(), bytearray(), bytearray()) + + for block_index in range(blocks): + idx = block_index * 16 + block = data[idx : idx + 16] + # Decode next 16-byte block. + a0, a1 = struct.unpack_from("> alphacode_index) & 0x07 + elif alphacode_index == 15: + alphacode = (alphacode2 >> 15) | ((alphacode1 << 1) & 0x06) + else: # alphacode_index >= 18 and alphacode_index <= 45 + alphacode = (alphacode1 >> (alphacode_index - 16)) & 0x07 + + if alphacode == 0: + a = a0 + elif alphacode == 1: + a = a1 + elif a0 > a1: + a = ((8 - alphacode) * a0 + (alphacode - 1) * a1) // 7 + elif alphacode == 6: + a = 0 + elif alphacode == 7: + a = 255 + else: + a = ((6 - alphacode) * a0 + (alphacode - 1) * a1) // 5 + + color_code = (code >> 2 * (4 * j + i)) & 0x03 + + if color_code == 0: + r, g, b = r0, g0, b0 + elif color_code == 1: + r, g, b = r1, g1, b1 + elif color_code == 2: + r = (2 * r0 + r1) // 3 + g = (2 * g0 + g1) // 3 + b = (2 * b0 + b1) // 3 + elif color_code == 3: + r = (2 * r1 + r0) // 3 + g = (2 * g1 + g0) // 3 + b = (2 * b1 + b0) // 3 + + ret[j].extend([r, g, b, a]) + + return ret + + +class BLPFormatError(NotImplementedError): + pass + + +def _accept(prefix: bytes) -> bool: + return prefix.startswith((b"BLP1", b"BLP2")) + + +class BlpImageFile(ImageFile.ImageFile): + """ + Blizzard Mipmap Format + """ + + format = "BLP" + format_description = "Blizzard Mipmap Format" + + def _open(self) -> None: + assert self.fp is not None + self.magic = self.fp.read(4) + if not _accept(self.magic): + msg = f"Bad BLP magic {repr(self.magic)}" + raise BLPFormatError(msg) + + compression = struct.unpack(" tuple[int, int]: + try: + self._read_header() + self._load() + except struct.error as e: + msg = "Truncated BLP file" + raise OSError(msg) from e + return -1, 0 + + @abc.abstractmethod + def _load(self) -> None: + pass + + def _read_header(self) -> None: + self._offsets = struct.unpack("<16I", self._safe_read(16 * 4)) + self._lengths = struct.unpack("<16I", self._safe_read(16 * 4)) + + def _safe_read(self, length: int) -> bytes: + assert self.fd is not None + return ImageFile._safe_read(self.fd, length) + + def _read_palette(self) -> list[tuple[int, int, int, int]]: + ret = [] + for i in range(256): + try: + b, g, r, a = struct.unpack("<4B", self._safe_read(4)) + except struct.error: + break + ret.append((b, g, r, a)) + return ret + + def _read_bgra( + self, palette: list[tuple[int, int, int, int]], alpha: bool + ) -> bytearray: + data = bytearray() + _data = BytesIO(self._safe_read(self._lengths[0])) + while True: + try: + (offset,) = struct.unpack(" None: + self._compression, self._encoding, alpha = self.args + + if self._compression == Format.JPEG: + self._decode_jpeg_stream() + + elif self._compression == 1: + if self._encoding in (4, 5): + palette = self._read_palette() + data = self._read_bgra(palette, alpha) + self.set_as_raw(data) + else: + msg = f"Unsupported BLP encoding {repr(self._encoding)}" + raise BLPFormatError(msg) + else: + msg = f"Unsupported BLP compression {repr(self._encoding)}" + raise BLPFormatError(msg) + + def _decode_jpeg_stream(self) -> None: + from .JpegImagePlugin import JpegImageFile + + (jpeg_header_size,) = struct.unpack(" None: + self._compression, self._encoding, alpha, self._alpha_encoding = self.args + + palette = self._read_palette() + + assert self.fd is not None + self.fd.seek(self._offsets[0]) + + if self._compression == 1: + # Uncompressed or DirectX compression + + if self._encoding == Encoding.UNCOMPRESSED: + data = self._read_bgra(palette, alpha) + + elif self._encoding == Encoding.DXT: + data = bytearray() + if self._alpha_encoding == AlphaEncoding.DXT1: + linesize = (self.state.xsize + 3) // 4 * 8 + for yb in range((self.state.ysize + 3) // 4): + for d in decode_dxt1(self._safe_read(linesize), alpha): + data += d + + elif self._alpha_encoding == AlphaEncoding.DXT3: + linesize = (self.state.xsize + 3) // 4 * 16 + for yb in range((self.state.ysize + 3) // 4): + for d in decode_dxt3(self._safe_read(linesize)): + data += d + + elif self._alpha_encoding == AlphaEncoding.DXT5: + linesize = (self.state.xsize + 3) // 4 * 16 + for yb in range((self.state.ysize + 3) // 4): + for d in decode_dxt5(self._safe_read(linesize)): + data += d + else: + msg = f"Unsupported alpha encoding {repr(self._alpha_encoding)}" + raise BLPFormatError(msg) + else: + msg = f"Unknown BLP encoding {repr(self._encoding)}" + raise BLPFormatError(msg) + + else: + msg = f"Unknown BLP compression {repr(self._compression)}" + raise BLPFormatError(msg) + + self.set_as_raw(data) + + +class BLPEncoder(ImageFile.PyEncoder): + _pushes_fd = True + + def _write_palette(self) -> bytes: + data = b"" + assert self.im is not None + palette = self.im.getpalette("RGBA", "RGBA") + for i in range(len(palette) // 4): + r, g, b, a = palette[i * 4 : (i + 1) * 4] + data += struct.pack("<4B", b, g, r, a) + while len(data) < 256 * 4: + data += b"\x00" * 4 + return data + + def encode(self, bufsize: int) -> tuple[int, int, bytes]: + palette_data = self._write_palette() + + offset = 20 + 16 * 4 * 2 + len(palette_data) + data = struct.pack("<16I", offset, *((0,) * 15)) + + assert self.im is not None + w, h = self.im.size + data += struct.pack("<16I", w * h, *((0,) * 15)) + + data += palette_data + + for y in range(h): + for x in range(w): + data += struct.pack(" None: + if im.mode != "P": + msg = "Unsupported BLP image mode" + raise ValueError(msg) + + magic = b"BLP1" if im.encoderinfo.get("blp_version") == "BLP1" else b"BLP2" + fp.write(magic) + + assert im.palette is not None + fp.write(struct.pack(" mode, rawmode + 1: ("P", "P;1"), + 4: ("P", "P;4"), + 8: ("P", "P"), + 16: ("RGB", "BGR;15"), + 24: ("RGB", "BGR"), + 32: ("RGB", "BGRX"), +} + +USE_RAW_ALPHA = False + + +def _accept(prefix: bytes) -> bool: + return prefix.startswith(b"BM") + + +def _dib_accept(prefix: bytes) -> bool: + return i32(prefix) in [12, 40, 52, 56, 64, 108, 124] + + +# ============================================================================= +# Image plugin for the Windows BMP format. +# ============================================================================= +class BmpImageFile(ImageFile.ImageFile): + """Image plugin for the Windows Bitmap format (BMP)""" + + # ------------------------------------------------------------- Description + format_description = "Windows Bitmap" + format = "BMP" + + # -------------------------------------------------- BMP Compression values + COMPRESSIONS = {"RAW": 0, "RLE8": 1, "RLE4": 2, "BITFIELDS": 3, "JPEG": 4, "PNG": 5} + for k, v in COMPRESSIONS.items(): + vars()[k] = v + + def _bitmap(self, header: int = 0, offset: int = 0) -> None: + """Read relevant info about the BMP""" + assert self.fp is not None + read, seek = self.fp.read, self.fp.seek + if header: + seek(header) + # read bmp header size @offset 14 (this is part of the header size) + file_info: dict[str, bool | int | tuple[int, ...]] = { + "header_size": i32(read(4)), + "direction": -1, + } + + # -------------------- If requested, read header at a specific position + # read the rest of the bmp header, without its size + assert isinstance(file_info["header_size"], int) + header_data = ImageFile._safe_read(self.fp, file_info["header_size"] - 4) + + # ------------------------------- Windows Bitmap v2, IBM OS/2 Bitmap v1 + # ----- This format has different offsets because of width/height types + # 12: BITMAPCOREHEADER/OS21XBITMAPHEADER + if file_info["header_size"] == 12: + file_info["width"] = i16(header_data, 0) + file_info["height"] = i16(header_data, 2) + file_info["planes"] = i16(header_data, 4) + file_info["bits"] = i16(header_data, 6) + file_info["compression"] = self.COMPRESSIONS["RAW"] + file_info["palette_padding"] = 3 + + # --------------------------------------------- Windows Bitmap v3 to v5 + # 40: BITMAPINFOHEADER + # 52: BITMAPV2HEADER + # 56: BITMAPV3HEADER + # 64: BITMAPCOREHEADER2/OS22XBITMAPHEADER + # 108: BITMAPV4HEADER + # 124: BITMAPV5HEADER + elif file_info["header_size"] in (40, 52, 56, 64, 108, 124): + file_info["y_flip"] = header_data[7] == 0xFF + file_info["direction"] = 1 if file_info["y_flip"] else -1 + file_info["width"] = i32(header_data, 0) + file_info["height"] = ( + i32(header_data, 4) + if not file_info["y_flip"] + else 2**32 - i32(header_data, 4) + ) + file_info["planes"] = i16(header_data, 8) + file_info["bits"] = i16(header_data, 10) + file_info["compression"] = i32(header_data, 12) + # byte size of pixel data + file_info["data_size"] = i32(header_data, 16) + file_info["pixels_per_meter"] = ( + i32(header_data, 20), + i32(header_data, 24), + ) + file_info["colors"] = i32(header_data, 28) + file_info["palette_padding"] = 4 + assert isinstance(file_info["pixels_per_meter"], tuple) + self.info["dpi"] = tuple(x / 39.3701 for x in file_info["pixels_per_meter"]) + if file_info["compression"] == self.COMPRESSIONS["BITFIELDS"]: + masks = ["r_mask", "g_mask", "b_mask"] + if len(header_data) >= 48: + if len(header_data) >= 52: + masks.append("a_mask") + else: + file_info["a_mask"] = 0x0 + for idx, mask in enumerate(masks): + file_info[mask] = i32(header_data, 36 + idx * 4) + else: + # 40 byte headers only have the three components in the + # bitfields masks, ref: + # https://msdn.microsoft.com/en-us/library/windows/desktop/dd183376(v=vs.85).aspx + # See also + # https://github.com/python-pillow/Pillow/issues/1293 + # There is a 4th component in the RGBQuad, in the alpha + # location, but it is listed as a reserved component, + # and it is not generally an alpha channel + file_info["a_mask"] = 0x0 + for mask in masks: + file_info[mask] = i32(read(4)) + assert isinstance(file_info["r_mask"], int) + assert isinstance(file_info["g_mask"], int) + assert isinstance(file_info["b_mask"], int) + assert isinstance(file_info["a_mask"], int) + file_info["rgb_mask"] = ( + file_info["r_mask"], + file_info["g_mask"], + file_info["b_mask"], + ) + file_info["rgba_mask"] = ( + file_info["r_mask"], + file_info["g_mask"], + file_info["b_mask"], + file_info["a_mask"], + ) + else: + msg = f"Unsupported BMP header type ({file_info['header_size']})" + raise OSError(msg) + + # ------------------ Special case : header is reported 40, which + # ---------------------- is shorter than real size for bpp >= 16 + assert isinstance(file_info["width"], int) + assert isinstance(file_info["height"], int) + self._size = file_info["width"], file_info["height"] + + # ------- If color count was not found in the header, compute from bits + assert isinstance(file_info["bits"], int) + if not file_info.get("colors", 0): + file_info["colors"] = 1 << file_info["bits"] + assert isinstance(file_info["palette_padding"], int) + assert isinstance(file_info["colors"], int) + if offset == 14 + file_info["header_size"] and file_info["bits"] <= 8: + offset += file_info["palette_padding"] * file_info["colors"] + + # ---------------------- Check bit depth for unusual unsupported values + self._mode, raw_mode = BIT2MODE.get(file_info["bits"], ("", "")) + if not self.mode: + msg = f"Unsupported BMP pixel depth ({file_info['bits']})" + raise OSError(msg) + + # ---------------- Process BMP with Bitfields compression (not palette) + decoder_name = "raw" + if file_info["compression"] == self.COMPRESSIONS["BITFIELDS"]: + SUPPORTED: dict[int, list[tuple[int, ...]]] = { + 32: [ + (0xFF0000, 0xFF00, 0xFF, 0x0), + (0xFF000000, 0xFF0000, 0xFF00, 0x0), + (0xFF000000, 0xFF00, 0xFF, 0x0), + (0xFF000000, 0xFF0000, 0xFF00, 0xFF), + (0xFF, 0xFF00, 0xFF0000, 0xFF000000), + (0xFF0000, 0xFF00, 0xFF, 0xFF000000), + (0xFF000000, 0xFF00, 0xFF, 0xFF0000), + (0x0, 0x0, 0x0, 0x0), + ], + 24: [(0xFF0000, 0xFF00, 0xFF)], + 16: [(0xF800, 0x7E0, 0x1F), (0x7C00, 0x3E0, 0x1F)], + } + MASK_MODES = { + (32, (0xFF0000, 0xFF00, 0xFF, 0x0)): "BGRX", + (32, (0xFF000000, 0xFF0000, 0xFF00, 0x0)): "XBGR", + (32, (0xFF000000, 0xFF00, 0xFF, 0x0)): "BGXR", + (32, (0xFF000000, 0xFF0000, 0xFF00, 0xFF)): "ABGR", + (32, (0xFF, 0xFF00, 0xFF0000, 0xFF000000)): "RGBA", + (32, (0xFF0000, 0xFF00, 0xFF, 0xFF000000)): "BGRA", + (32, (0xFF000000, 0xFF00, 0xFF, 0xFF0000)): "BGAR", + (32, (0x0, 0x0, 0x0, 0x0)): "BGRA", + (24, (0xFF0000, 0xFF00, 0xFF)): "BGR", + (16, (0xF800, 0x7E0, 0x1F)): "BGR;16", + (16, (0x7C00, 0x3E0, 0x1F)): "BGR;15", + } + if file_info["bits"] in SUPPORTED: + if ( + file_info["bits"] == 32 + and file_info["rgba_mask"] in SUPPORTED[file_info["bits"]] + ): + assert isinstance(file_info["rgba_mask"], tuple) + raw_mode = MASK_MODES[(file_info["bits"], file_info["rgba_mask"])] + self._mode = "RGBA" if "A" in raw_mode else self.mode + elif ( + file_info["bits"] in (24, 16) + and file_info["rgb_mask"] in SUPPORTED[file_info["bits"]] + ): + assert isinstance(file_info["rgb_mask"], tuple) + raw_mode = MASK_MODES[(file_info["bits"], file_info["rgb_mask"])] + else: + msg = "Unsupported BMP bitfields layout" + raise OSError(msg) + else: + msg = "Unsupported BMP bitfields layout" + raise OSError(msg) + elif file_info["compression"] == self.COMPRESSIONS["RAW"]: + if file_info["bits"] == 32 and ( + header == 22 or USE_RAW_ALPHA # 32-bit .cur offset + ): + raw_mode, self._mode = "BGRA", "RGBA" + elif file_info["compression"] in ( + self.COMPRESSIONS["RLE8"], + self.COMPRESSIONS["RLE4"], + ): + decoder_name = "bmp_rle" + else: + msg = f"Unsupported BMP compression ({file_info['compression']})" + raise OSError(msg) + + # --------------- Once the header is processed, process the palette/LUT + if self.mode == "P": # Paletted for 1, 4 and 8 bit images + # ---------------------------------------------------- 1-bit images + if not (0 < file_info["colors"] <= 65536): + msg = f"Unsupported BMP Palette size ({file_info['colors']})" + raise OSError(msg) + else: + padding = file_info["palette_padding"] + palette = read(padding * file_info["colors"]) + grayscale = True + indices = ( + (0, 255) + if file_info["colors"] == 2 + else list(range(file_info["colors"])) + ) + + # ----------------- Check if grayscale and ignore palette if so + for ind, val in enumerate(indices): + rgb = palette[ind * padding : ind * padding + 3] + if rgb != o8(val) * 3: + grayscale = False + + # ------- If all colors are gray, white or black, ditch palette + if grayscale: + self._mode = "1" if file_info["colors"] == 2 else "L" + raw_mode = self.mode + else: + self._mode = "P" + self.palette = ImagePalette.raw( + "BGRX" if padding == 4 else "BGR", palette + ) + + # ---------------------------- Finally set the tile data for the plugin + self.info["compression"] = file_info["compression"] + args: list[Any] = [raw_mode] + if decoder_name == "bmp_rle": + args.append(file_info["compression"] == self.COMPRESSIONS["RLE4"]) + else: + assert isinstance(file_info["width"], int) + args.append(((file_info["width"] * file_info["bits"] + 31) >> 3) & (~3)) + args.append(file_info["direction"]) + self.tile = [ + ImageFile._Tile( + decoder_name, + (0, 0, file_info["width"], file_info["height"]), + offset or self.fp.tell(), + tuple(args), + ) + ] + + def _open(self) -> None: + """Open file, check magic number and read header""" + # read 14 bytes: magic number, filesize, reserved, header final offset + assert self.fp is not None + head_data = self.fp.read(14) + # choke if the file does not have the required magic bytes + if not _accept(head_data): + msg = "Not a BMP file" + raise SyntaxError(msg) + # read the start position of the BMP image data (u32) + offset = i32(head_data, 10) + # load bitmap information (offset=raster info) + self._bitmap(offset=offset) + + +class BmpRleDecoder(ImageFile.PyDecoder): + _pulls_fd = True + + def decode(self, buffer: Image.DecoderInput) -> tuple[int, int]: + assert self.fd is not None + rle4 = self.args[1] + data = bytearray() + x = 0 + dest_length = self.state.xsize * self.state.ysize + while len(data) < dest_length: + pixels = self.fd.read(1) + byte = self.fd.read(1) + if not pixels or not byte: + break + num_pixels = pixels[0] + if num_pixels: + # encoded mode + if x + num_pixels > self.state.xsize: + # Too much data for row + num_pixels = max(0, self.state.xsize - x) + if rle4: + first_pixel = o8(byte[0] >> 4) + second_pixel = o8(byte[0] & 0x0F) + for index in range(num_pixels): + if index % 2 == 0: + data += first_pixel + else: + data += second_pixel + else: + data += byte * num_pixels + x += num_pixels + else: + if byte[0] == 0: + # end of line + while len(data) % self.state.xsize != 0: + data += b"\x00" + x = 0 + elif byte[0] == 1: + # end of bitmap + break + elif byte[0] == 2: + # delta + bytes_read = self.fd.read(2) + if len(bytes_read) < 2: + break + right, up = bytes_read + data += b"\x00" * (right + up * self.state.xsize) + x = len(data) % self.state.xsize + else: + # absolute mode + if rle4: + # 2 pixels per byte + byte_count = byte[0] // 2 + bytes_read = self.fd.read(byte_count) + for byte_read in bytes_read: + data += o8(byte_read >> 4) + data += o8(byte_read & 0x0F) + else: + byte_count = byte[0] + bytes_read = self.fd.read(byte_count) + data += bytes_read + if len(bytes_read) < byte_count: + break + x += byte[0] + + # align to 16-bit word boundary + if self.fd.tell() % 2 != 0: + self.fd.seek(1, os.SEEK_CUR) + rawmode = "L" if self.mode == "L" else "P" + self.set_as_raw(bytes(data), rawmode, (0, self.args[-1])) + return -1, 0 + + +# ============================================================================= +# Image plugin for the DIB format (BMP alias) +# ============================================================================= +class DibImageFile(BmpImageFile): + format = "DIB" + format_description = "Windows Bitmap" + + def _open(self) -> None: + self._bitmap() + + +# +# -------------------------------------------------------------------- +# Write BMP file + + +SAVE = { + "1": ("1", 1, 2), + "L": ("L", 8, 256), + "P": ("P", 8, 256), + "RGB": ("BGR", 24, 0), + "RGBA": ("BGRA", 32, 0), +} + + +def _dib_save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + _save(im, fp, filename, False) + + +def _save( + im: Image.Image, fp: IO[bytes], filename: str | bytes, bitmap_header: bool = True +) -> None: + try: + rawmode, bits, colors = SAVE[im.mode] + except KeyError as e: + msg = f"cannot write mode {im.mode} as BMP" + raise OSError(msg) from e + + info = im.encoderinfo + + dpi = info.get("dpi", (96, 96)) + + # 1 meter == 39.3701 inches + ppm = tuple(int(x * 39.3701 + 0.5) for x in dpi) + + stride = ((im.size[0] * bits + 7) // 8 + 3) & (~3) + header = 40 # or 64 for OS/2 version 2 + image = stride * im.size[1] + + if im.mode == "1": + palette = b"".join(o8(i) * 3 + b"\x00" for i in (0, 255)) + elif im.mode == "L": + palette = b"".join(o8(i) * 3 + b"\x00" for i in range(256)) + elif im.mode == "P": + palette = im.im.getpalette("RGB", "BGRX") + colors = len(palette) // 4 + else: + palette = None + + # bitmap header + if bitmap_header: + offset = 14 + header + colors * 4 + file_size = offset + image + if file_size > 2**32 - 1: + msg = "File size is too large for the BMP format" + raise ValueError(msg) + fp.write( + b"BM" # file type (magic) + + o32(file_size) # file size + + o32(0) # reserved + + o32(offset) # image data offset + ) + + # bitmap info header + fp.write( + o32(header) # info header size + + o32(im.size[0]) # width + + o32(im.size[1]) # height + + o16(1) # planes + + o16(bits) # depth + + o32(0) # compression (0=uncompressed) + + o32(image) # size of bitmap + + o32(ppm[0]) # resolution + + o32(ppm[1]) # resolution + + o32(colors) # colors used + + o32(colors) # colors important + ) + + fp.write(b"\0" * (header - 40)) # padding (for OS/2 format) + + if palette: + fp.write(palette) + + ImageFile._save( + im, fp, [ImageFile._Tile("raw", (0, 0) + im.size, 0, (rawmode, stride, -1))] + ) + + +# +# -------------------------------------------------------------------- +# Registry + + +Image.register_open(BmpImageFile.format, BmpImageFile, _accept) +Image.register_save(BmpImageFile.format, _save) + +Image.register_extension(BmpImageFile.format, ".bmp") + +Image.register_mime(BmpImageFile.format, "image/bmp") + +Image.register_decoder("bmp_rle", BmpRleDecoder) + +Image.register_open(DibImageFile.format, DibImageFile, _dib_accept) +Image.register_save(DibImageFile.format, _dib_save) + +Image.register_extension(DibImageFile.format, ".dib") + +Image.register_mime(DibImageFile.format, "image/bmp") diff --git a/.venv/lib/python3.11/site-packages/PIL/BufrStubImagePlugin.py b/.venv/lib/python3.11/site-packages/PIL/BufrStubImagePlugin.py new file mode 100644 index 0000000000000000000000000000000000000000..d82c4c746c32c40cc0b039d8cac53f3b9b6a1013 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/BufrStubImagePlugin.py @@ -0,0 +1,72 @@ +# +# The Python Imaging Library +# $Id$ +# +# BUFR stub adapter +# +# Copyright (c) 1996-2003 by Fredrik Lundh +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import os +from typing import IO + +from . import Image, ImageFile + +_handler = None + + +def register_handler(handler: ImageFile.StubHandler | None) -> None: + """ + Install application-specific BUFR image handler. + + :param handler: Handler object. + """ + global _handler + _handler = handler + + +# -------------------------------------------------------------------- +# Image adapter + + +def _accept(prefix: bytes) -> bool: + return prefix.startswith((b"BUFR", b"ZCZC")) + + +class BufrStubImageFile(ImageFile.StubImageFile): + format = "BUFR" + format_description = "BUFR" + + def _open(self) -> None: + assert self.fp is not None + if not _accept(self.fp.read(4)): + msg = "Not a BUFR file" + raise SyntaxError(msg) + + self.fp.seek(-4, os.SEEK_CUR) + + # make something up + self._mode = "F" + self._size = 1, 1 + + def _load(self) -> ImageFile.StubHandler | None: + return _handler + + +def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + if _handler is None or not hasattr(_handler, "save"): + msg = "BUFR save handler not installed" + raise OSError(msg) + _handler.save(im, fp, filename) + + +# -------------------------------------------------------------------- +# Registry + +Image.register_open(BufrStubImageFile.format, BufrStubImageFile, _accept) +Image.register_save(BufrStubImageFile.format, _save) + +Image.register_extension(BufrStubImageFile.format, ".bufr") diff --git a/.venv/lib/python3.11/site-packages/PIL/ContainerIO.py b/.venv/lib/python3.11/site-packages/PIL/ContainerIO.py new file mode 100644 index 0000000000000000000000000000000000000000..ec9e66c714fbbfec8c597f6127e5d932b0da521f --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/ContainerIO.py @@ -0,0 +1,173 @@ +# +# The Python Imaging Library. +# $Id$ +# +# a class to read from a container file +# +# History: +# 1995-06-18 fl Created +# 1995-09-07 fl Added readline(), readlines() +# +# Copyright (c) 1997-2001 by Secret Labs AB +# Copyright (c) 1995 by Fredrik Lundh +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import io +from collections.abc import Iterable +from typing import IO, AnyStr, NoReturn + + +class ContainerIO(IO[AnyStr]): + """ + A file object that provides read access to a part of an existing + file (for example a TAR file). + """ + + def __init__(self, file: IO[AnyStr], offset: int, length: int) -> None: + """ + Create file object. + + :param file: Existing file. + :param offset: Start of region, in bytes. + :param length: Size of region, in bytes. + """ + self.fh: IO[AnyStr] = file + self.pos = 0 + self.offset = offset + self.length = length + self.fh.seek(offset) + + ## + # Always false. + + def isatty(self) -> bool: + return False + + def seekable(self) -> bool: + return True + + def seek(self, offset: int, mode: int = io.SEEK_SET) -> int: + """ + Move file pointer. + + :param offset: Offset in bytes. + :param mode: Starting position. Use 0 for beginning of region, 1 + for current offset, and 2 for end of region. You cannot move + the pointer outside the defined region. + :returns: Offset from start of region, in bytes. + """ + if mode == 1: + self.pos = self.pos + offset + elif mode == 2: + self.pos = self.length + offset + else: + self.pos = offset + # clamp + self.pos = max(0, min(self.pos, self.length)) + self.fh.seek(self.offset + self.pos) + return self.pos + + def tell(self) -> int: + """ + Get current file pointer. + + :returns: Offset from start of region, in bytes. + """ + return self.pos + + def readable(self) -> bool: + return True + + def read(self, n: int = -1) -> AnyStr: + """ + Read data. + + :param n: Number of bytes to read. If omitted, zero or negative, + read until end of region. + :returns: An 8-bit string. + """ + if n > 0: + n = min(n, self.length - self.pos) + else: + n = self.length - self.pos + if n <= 0: # EOF + return b"" if "b" in self.fh.mode else "" # type: ignore[return-value] + self.pos = self.pos + n + return self.fh.read(n) + + def readline(self, n: int = -1) -> AnyStr: + """ + Read a line of text. + + :param n: Number of bytes to read. If omitted, zero or negative, + read until end of line. + :returns: An 8-bit string. + """ + s: AnyStr = b"" if "b" in self.fh.mode else "" # type: ignore[assignment] + newline_character = b"\n" if "b" in self.fh.mode else "\n" + while True: + c = self.read(1) + if not c: + break + s = s + c + if c == newline_character or len(s) == n: + break + return s + + def readlines(self, n: int | None = -1) -> list[AnyStr]: + """ + Read multiple lines of text. + + :param n: Number of lines to read. If omitted, zero, negative or None, + read until end of region. + :returns: A list of 8-bit strings. + """ + lines = [] + while True: + s = self.readline() + if not s: + break + lines.append(s) + if len(lines) == n: + break + return lines + + def writable(self) -> bool: + return False + + def write(self, b: AnyStr) -> NoReturn: + raise NotImplementedError() + + def writelines(self, lines: Iterable[AnyStr]) -> NoReturn: + raise NotImplementedError() + + def truncate(self, size: int | None = None) -> int: + raise NotImplementedError() + + def __enter__(self) -> ContainerIO[AnyStr]: + return self + + def __exit__(self, *args: object) -> None: + self.close() + + def __iter__(self) -> ContainerIO[AnyStr]: + return self + + def __next__(self) -> AnyStr: + line = self.readline() + if not line: + msg = "end of region" + raise StopIteration(msg) + return line + + def fileno(self) -> int: + return self.fh.fileno() + + def flush(self) -> None: + self.fh.flush() + + def close(self) -> None: + self.fh.close() diff --git a/.venv/lib/python3.11/site-packages/PIL/CurImagePlugin.py b/.venv/lib/python3.11/site-packages/PIL/CurImagePlugin.py new file mode 100644 index 0000000000000000000000000000000000000000..b20425040f4a3f2ac4e6267a76d250bd34bc62bc --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/CurImagePlugin.py @@ -0,0 +1,103 @@ +# +# The Python Imaging Library. +# $Id$ +# +# Windows Cursor support for PIL +# +# notes: +# uses BmpImagePlugin.py to read the bitmap data. +# +# history: +# 96-05-27 fl Created +# +# Copyright (c) Secret Labs AB 1997. +# Copyright (c) Fredrik Lundh 1996. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +from . import BmpImagePlugin, Image, ImageOps +from ._binary import i16le as i16 +from ._binary import i32le as i32 + +# +# -------------------------------------------------------------------- + + +def _accept(prefix: bytes) -> bool: + return prefix.startswith(b"\0\0\2\0") + + +## +# Image plugin for Windows Cursor files. + + +class CurImageFile(BmpImagePlugin.BmpImageFile): + format = "CUR" + format_description = "Windows Cursor" + + def _open(self) -> None: + assert self.fp is not None + offset = self.fp.tell() + + # check magic + s = self.fp.read(6) + if not _accept(s): + msg = "not a CUR file" + raise SyntaxError(msg) + + # pick the largest cursor in the file + m = b"" + for i in range(i16(s, 4)): + s = self.fp.read(16) + if not m: + m = s + elif s[0] > m[0] and s[1] > m[1]: + m = s + if not m: + msg = "No cursors were found" + raise TypeError(msg) + + # load as bitmap + self._bitmap(i32(m, 12) + offset) + self._masked = self.mode in ("1", "L") + if self._masked: + self._rawmode = self.mode + self._mode = "LA" + + # patch up the bitmap height + self._size = self.width, self.height // 2 + if not self._masked: + self.tile = [self.tile[0]._replace(extents=(0, 0) + self.size)] + + def load_prepare(self) -> None: + if self._masked: + self._mode = self._rawmode + self._size = self.width, self.height * 2 + super().load_prepare() + + def load_end(self) -> None: + if not self._masked: + return + self._mode = "LA" + new_height = self.height // 2 + + and_mask = self.im.crop((0, 0, self.width, new_height)) + xor_mask = self.im.crop((0, new_height, self.width, self.height)) + + self._size = self.width, new_height + self._im = Image.core.fill(self.mode, self.size) + self._im.paste( + xor_mask.convert(self.mode), + (0, 0) + self.size, + ImageOps.invert(Image.Image()._new(and_mask)).im, + ) + + +# +# -------------------------------------------------------------------- + +Image.register_open(CurImageFile.format, CurImageFile, _accept) + +Image.register_extension(CurImageFile.format, ".cur") diff --git a/.venv/lib/python3.11/site-packages/PIL/DcxImagePlugin.py b/.venv/lib/python3.11/site-packages/PIL/DcxImagePlugin.py new file mode 100644 index 0000000000000000000000000000000000000000..d3f456ddcc4aabac81d53bfb3972b398bb2f86b1 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/DcxImagePlugin.py @@ -0,0 +1,84 @@ +# +# The Python Imaging Library. +# $Id$ +# +# DCX file handling +# +# DCX is a container file format defined by Intel, commonly used +# for fax applications. Each DCX file consists of a directory +# (a list of file offsets) followed by a set of (usually 1-bit) +# PCX files. +# +# History: +# 1995-09-09 fl Created +# 1996-03-20 fl Properly derived from PcxImageFile. +# 1998-07-15 fl Renamed offset attribute to avoid name clash +# 2002-07-30 fl Fixed file handling +# +# Copyright (c) 1997-98 by Secret Labs AB. +# Copyright (c) 1995-96 by Fredrik Lundh. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +from . import Image +from ._binary import i32le as i32 +from ._util import DeferredError +from .PcxImagePlugin import PcxImageFile + +MAGIC = 0x3ADE68B1 # QUIZ: what's this value, then? + + +def _accept(prefix: bytes) -> bool: + return len(prefix) >= 4 and i32(prefix) == MAGIC + + +## +# Image plugin for the Intel DCX format. + + +class DcxImageFile(PcxImageFile): + format = "DCX" + format_description = "Intel DCX" + _close_exclusive_fp_after_loading = False + + def _open(self) -> None: + # Header + assert self.fp is not None + s = self.fp.read(4) + if not _accept(s): + msg = "not a DCX file" + raise SyntaxError(msg) + + # Component directory + self._offset = [] + for i in range(1024): + offset = i32(self.fp.read(4)) + if not offset: + break + self._offset.append(offset) + + self._fp = self.fp + self.frame = -1 + self.n_frames = len(self._offset) + self.is_animated = self.n_frames > 1 + self.seek(0) + + def seek(self, frame: int) -> None: + if not self._seek_check(frame): + return + if isinstance(self._fp, DeferredError): + raise self._fp.ex + self.frame = frame + self.fp = self._fp + self.fp.seek(self._offset[frame]) + PcxImageFile._open(self) + + def tell(self) -> int: + return self.frame + + +Image.register_open(DcxImageFile.format, DcxImageFile, _accept) + +Image.register_extension(DcxImageFile.format, ".dcx") diff --git a/.venv/lib/python3.11/site-packages/PIL/DdsImagePlugin.py b/.venv/lib/python3.11/site-packages/PIL/DdsImagePlugin.py new file mode 100644 index 0000000000000000000000000000000000000000..2ca9f3abb270cba58eeed461102cd48a7a07c8ca --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/DdsImagePlugin.py @@ -0,0 +1,632 @@ +""" +A Pillow plugin for .dds files (S3TC-compressed aka DXTC) +Jerome Leclanche + +Documentation: +https://web.archive.org/web/20170802060935/http://oss.sgi.com/projects/ogl-sample/registry/EXT/texture_compression_s3tc.txt + +The contents of this file are hereby released in the public domain (CC0) +Full text of the CC0 license: +https://creativecommons.org/publicdomain/zero/1.0/ +""" + +from __future__ import annotations + +import struct +import sys +from enum import IntEnum, IntFlag +from typing import IO + +from . import Image, ImageFile, ImagePalette +from ._binary import i32le as i32 +from ._binary import o8 +from ._binary import o32le as o32 + +# Magic ("DDS ") +DDS_MAGIC = 0x20534444 + + +# DDS flags +class DDSD(IntFlag): + CAPS = 0x1 + HEIGHT = 0x2 + WIDTH = 0x4 + PITCH = 0x8 + PIXELFORMAT = 0x1000 + MIPMAPCOUNT = 0x20000 + LINEARSIZE = 0x80000 + DEPTH = 0x800000 + + +# DDS caps +class DDSCAPS(IntFlag): + COMPLEX = 0x8 + TEXTURE = 0x1000 + MIPMAP = 0x400000 + + +class DDSCAPS2(IntFlag): + CUBEMAP = 0x200 + CUBEMAP_POSITIVEX = 0x400 + CUBEMAP_NEGATIVEX = 0x800 + CUBEMAP_POSITIVEY = 0x1000 + CUBEMAP_NEGATIVEY = 0x2000 + CUBEMAP_POSITIVEZ = 0x4000 + CUBEMAP_NEGATIVEZ = 0x8000 + VOLUME = 0x200000 + + +# Pixel Format +class DDPF(IntFlag): + ALPHAPIXELS = 0x1 + ALPHA = 0x2 + FOURCC = 0x4 + PALETTEINDEXED8 = 0x20 + RGB = 0x40 + LUMINANCE = 0x20000 + + +# dxgiformat.h +class DXGI_FORMAT(IntEnum): + UNKNOWN = 0 + R32G32B32A32_TYPELESS = 1 + R32G32B32A32_FLOAT = 2 + R32G32B32A32_UINT = 3 + R32G32B32A32_SINT = 4 + R32G32B32_TYPELESS = 5 + R32G32B32_FLOAT = 6 + R32G32B32_UINT = 7 + R32G32B32_SINT = 8 + R16G16B16A16_TYPELESS = 9 + R16G16B16A16_FLOAT = 10 + R16G16B16A16_UNORM = 11 + R16G16B16A16_UINT = 12 + R16G16B16A16_SNORM = 13 + R16G16B16A16_SINT = 14 + R32G32_TYPELESS = 15 + R32G32_FLOAT = 16 + R32G32_UINT = 17 + R32G32_SINT = 18 + R32G8X24_TYPELESS = 19 + D32_FLOAT_S8X24_UINT = 20 + R32_FLOAT_X8X24_TYPELESS = 21 + X32_TYPELESS_G8X24_UINT = 22 + R10G10B10A2_TYPELESS = 23 + R10G10B10A2_UNORM = 24 + R10G10B10A2_UINT = 25 + R11G11B10_FLOAT = 26 + R8G8B8A8_TYPELESS = 27 + R8G8B8A8_UNORM = 28 + R8G8B8A8_UNORM_SRGB = 29 + R8G8B8A8_UINT = 30 + R8G8B8A8_SNORM = 31 + R8G8B8A8_SINT = 32 + R16G16_TYPELESS = 33 + R16G16_FLOAT = 34 + R16G16_UNORM = 35 + R16G16_UINT = 36 + R16G16_SNORM = 37 + R16G16_SINT = 38 + R32_TYPELESS = 39 + D32_FLOAT = 40 + R32_FLOAT = 41 + R32_UINT = 42 + R32_SINT = 43 + R24G8_TYPELESS = 44 + D24_UNORM_S8_UINT = 45 + R24_UNORM_X8_TYPELESS = 46 + X24_TYPELESS_G8_UINT = 47 + R8G8_TYPELESS = 48 + R8G8_UNORM = 49 + R8G8_UINT = 50 + R8G8_SNORM = 51 + R8G8_SINT = 52 + R16_TYPELESS = 53 + R16_FLOAT = 54 + D16_UNORM = 55 + R16_UNORM = 56 + R16_UINT = 57 + R16_SNORM = 58 + R16_SINT = 59 + R8_TYPELESS = 60 + R8_UNORM = 61 + R8_UINT = 62 + R8_SNORM = 63 + R8_SINT = 64 + A8_UNORM = 65 + R1_UNORM = 66 + R9G9B9E5_SHAREDEXP = 67 + R8G8_B8G8_UNORM = 68 + G8R8_G8B8_UNORM = 69 + BC1_TYPELESS = 70 + BC1_UNORM = 71 + BC1_UNORM_SRGB = 72 + BC2_TYPELESS = 73 + BC2_UNORM = 74 + BC2_UNORM_SRGB = 75 + BC3_TYPELESS = 76 + BC3_UNORM = 77 + BC3_UNORM_SRGB = 78 + BC4_TYPELESS = 79 + BC4_UNORM = 80 + BC4_SNORM = 81 + BC5_TYPELESS = 82 + BC5_UNORM = 83 + BC5_SNORM = 84 + B5G6R5_UNORM = 85 + B5G5R5A1_UNORM = 86 + B8G8R8A8_UNORM = 87 + B8G8R8X8_UNORM = 88 + R10G10B10_XR_BIAS_A2_UNORM = 89 + B8G8R8A8_TYPELESS = 90 + B8G8R8A8_UNORM_SRGB = 91 + B8G8R8X8_TYPELESS = 92 + B8G8R8X8_UNORM_SRGB = 93 + BC6H_TYPELESS = 94 + BC6H_UF16 = 95 + BC6H_SF16 = 96 + BC7_TYPELESS = 97 + BC7_UNORM = 98 + BC7_UNORM_SRGB = 99 + AYUV = 100 + Y410 = 101 + Y416 = 102 + NV12 = 103 + P010 = 104 + P016 = 105 + OPAQUE_420 = 106 + YUY2 = 107 + Y210 = 108 + Y216 = 109 + NV11 = 110 + AI44 = 111 + IA44 = 112 + P8 = 113 + A8P8 = 114 + B4G4R4A4_UNORM = 115 + P208 = 130 + V208 = 131 + V408 = 132 + SAMPLER_FEEDBACK_MIN_MIP_OPAQUE = 189 + SAMPLER_FEEDBACK_MIP_REGION_USED_OPAQUE = 190 + + +class D3DFMT(IntEnum): + UNKNOWN = 0 + R8G8B8 = 20 + A8R8G8B8 = 21 + X8R8G8B8 = 22 + R5G6B5 = 23 + X1R5G5B5 = 24 + A1R5G5B5 = 25 + A4R4G4B4 = 26 + R3G3B2 = 27 + A8 = 28 + A8R3G3B2 = 29 + X4R4G4B4 = 30 + A2B10G10R10 = 31 + A8B8G8R8 = 32 + X8B8G8R8 = 33 + G16R16 = 34 + A2R10G10B10 = 35 + A16B16G16R16 = 36 + A8P8 = 40 + P8 = 41 + L8 = 50 + A8L8 = 51 + A4L4 = 52 + V8U8 = 60 + L6V5U5 = 61 + X8L8V8U8 = 62 + Q8W8V8U8 = 63 + V16U16 = 64 + A2W10V10U10 = 67 + D16_LOCKABLE = 70 + D32 = 71 + D15S1 = 73 + D24S8 = 75 + D24X8 = 77 + D24X4S4 = 79 + D16 = 80 + D32F_LOCKABLE = 82 + D24FS8 = 83 + D32_LOCKABLE = 84 + S8_LOCKABLE = 85 + L16 = 81 + VERTEXDATA = 100 + INDEX16 = 101 + INDEX32 = 102 + Q16W16V16U16 = 110 + R16F = 111 + G16R16F = 112 + A16B16G16R16F = 113 + R32F = 114 + G32R32F = 115 + A32B32G32R32F = 116 + CxV8U8 = 117 + A1 = 118 + A2B10G10R10_XR_BIAS = 119 + BINARYBUFFER = 199 + + UYVY = i32(b"UYVY") + R8G8_B8G8 = i32(b"RGBG") + YUY2 = i32(b"YUY2") + G8R8_G8B8 = i32(b"GRGB") + DXT1 = i32(b"DXT1") + DXT2 = i32(b"DXT2") + DXT3 = i32(b"DXT3") + DXT4 = i32(b"DXT4") + DXT5 = i32(b"DXT5") + DX10 = i32(b"DX10") + BC4S = i32(b"BC4S") + BC4U = i32(b"BC4U") + BC5S = i32(b"BC5S") + BC5U = i32(b"BC5U") + ATI1 = i32(b"ATI1") + ATI2 = i32(b"ATI2") + MULTI2_ARGB8 = i32(b"MET1") + + +# Backward compatibility layer +module = sys.modules[__name__] +for item in DDSD: + assert item.name is not None + setattr(module, f"DDSD_{item.name}", item.value) +for item1 in DDSCAPS: + assert item1.name is not None + setattr(module, f"DDSCAPS_{item1.name}", item1.value) +for item2 in DDSCAPS2: + assert item2.name is not None + setattr(module, f"DDSCAPS2_{item2.name}", item2.value) +for item3 in DDPF: + assert item3.name is not None + setattr(module, f"DDPF_{item3.name}", item3.value) + +DDS_FOURCC = DDPF.FOURCC +DDS_RGB = DDPF.RGB +DDS_RGBA = DDPF.RGB | DDPF.ALPHAPIXELS +DDS_LUMINANCE = DDPF.LUMINANCE +DDS_LUMINANCEA = DDPF.LUMINANCE | DDPF.ALPHAPIXELS +DDS_ALPHA = DDPF.ALPHA +DDS_PAL8 = DDPF.PALETTEINDEXED8 + +DDS_HEADER_FLAGS_TEXTURE = DDSD.CAPS | DDSD.HEIGHT | DDSD.WIDTH | DDSD.PIXELFORMAT +DDS_HEADER_FLAGS_MIPMAP = DDSD.MIPMAPCOUNT +DDS_HEADER_FLAGS_VOLUME = DDSD.DEPTH +DDS_HEADER_FLAGS_PITCH = DDSD.PITCH +DDS_HEADER_FLAGS_LINEARSIZE = DDSD.LINEARSIZE + +DDS_HEIGHT = DDSD.HEIGHT +DDS_WIDTH = DDSD.WIDTH + +DDS_SURFACE_FLAGS_TEXTURE = DDSCAPS.TEXTURE +DDS_SURFACE_FLAGS_MIPMAP = DDSCAPS.COMPLEX | DDSCAPS.MIPMAP +DDS_SURFACE_FLAGS_CUBEMAP = DDSCAPS.COMPLEX + +DDS_CUBEMAP_POSITIVEX = DDSCAPS2.CUBEMAP | DDSCAPS2.CUBEMAP_POSITIVEX +DDS_CUBEMAP_NEGATIVEX = DDSCAPS2.CUBEMAP | DDSCAPS2.CUBEMAP_NEGATIVEX +DDS_CUBEMAP_POSITIVEY = DDSCAPS2.CUBEMAP | DDSCAPS2.CUBEMAP_POSITIVEY +DDS_CUBEMAP_NEGATIVEY = DDSCAPS2.CUBEMAP | DDSCAPS2.CUBEMAP_NEGATIVEY +DDS_CUBEMAP_POSITIVEZ = DDSCAPS2.CUBEMAP | DDSCAPS2.CUBEMAP_POSITIVEZ +DDS_CUBEMAP_NEGATIVEZ = DDSCAPS2.CUBEMAP | DDSCAPS2.CUBEMAP_NEGATIVEZ + +DXT1_FOURCC = D3DFMT.DXT1 +DXT3_FOURCC = D3DFMT.DXT3 +DXT5_FOURCC = D3DFMT.DXT5 + +DXGI_FORMAT_R8G8B8A8_TYPELESS = DXGI_FORMAT.R8G8B8A8_TYPELESS +DXGI_FORMAT_R8G8B8A8_UNORM = DXGI_FORMAT.R8G8B8A8_UNORM +DXGI_FORMAT_R8G8B8A8_UNORM_SRGB = DXGI_FORMAT.R8G8B8A8_UNORM_SRGB +DXGI_FORMAT_BC5_TYPELESS = DXGI_FORMAT.BC5_TYPELESS +DXGI_FORMAT_BC5_UNORM = DXGI_FORMAT.BC5_UNORM +DXGI_FORMAT_BC5_SNORM = DXGI_FORMAT.BC5_SNORM +DXGI_FORMAT_BC6H_UF16 = DXGI_FORMAT.BC6H_UF16 +DXGI_FORMAT_BC6H_SF16 = DXGI_FORMAT.BC6H_SF16 +DXGI_FORMAT_BC7_TYPELESS = DXGI_FORMAT.BC7_TYPELESS +DXGI_FORMAT_BC7_UNORM = DXGI_FORMAT.BC7_UNORM +DXGI_FORMAT_BC7_UNORM_SRGB = DXGI_FORMAT.BC7_UNORM_SRGB + + +class DdsImageFile(ImageFile.ImageFile): + format = "DDS" + format_description = "DirectDraw Surface" + + def _open(self) -> None: + assert self.fp is not None + if not _accept(self.fp.read(4)): + msg = "not a DDS file" + raise SyntaxError(msg) + (header_size,) = struct.unpack(" None: + pass + + +class DdsRgbDecoder(ImageFile.PyDecoder): + _pulls_fd = True + + def decode(self, buffer: Image.DecoderInput) -> tuple[int, int]: + bitcount, masks = self.args + + data = bytearray() + bytecount = bitcount // 8 + if not bytecount: + self.set_as_raw(data) + return -1, 0 + + # Some masks will be padded with zeros, e.g. R 0b11 G 0b1100 + # Calculate how many zeros each mask is padded with + mask_offsets = [] + # And the maximum value of each channel without the padding + mask_totals = [] + for mask in masks: + offset = 0 + if mask != 0: + while mask >> (offset + 1) << (offset + 1) == mask: + offset += 1 + mask_offsets.append(offset) + mask_totals.append(mask >> offset) + + assert self.fd is not None + dest_length = self.state.xsize * self.state.ysize * len(masks) + while len(data) < dest_length: + bytes_read = self.fd.read(bytecount) + if len(bytes_read) < bytecount: + break + value = int.from_bytes(bytes_read, "little") + for i, mask in enumerate(masks): + masked_value = value & mask + # Remove the zero padding, and scale it to 8 bits + data += o8( + int(((masked_value >> mask_offsets[i]) / mask_totals[i]) * 255) + if mask_totals[i] + else 0 + ) + self.set_as_raw(data) + return -1, 0 + + +def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + if im.mode not in ("RGB", "RGBA", "L", "LA"): + msg = f"cannot write mode {im.mode} as DDS" + raise OSError(msg) + + flags = DDSD.CAPS | DDSD.HEIGHT | DDSD.WIDTH | DDSD.PIXELFORMAT + bitcount = len(im.getbands()) * 8 + pixel_format = im.encoderinfo.get("pixel_format") + args: tuple[int] | str + if pixel_format: + codec_name = "bcn" + flags |= DDSD.LINEARSIZE + pitch = (im.width + 3) * 4 + rgba_mask = [0, 0, 0, 0] + pixel_flags = DDPF.FOURCC + if pixel_format == "DXT1": + fourcc = D3DFMT.DXT1 + args = (1,) + elif pixel_format == "DXT3": + fourcc = D3DFMT.DXT3 + args = (2,) + elif pixel_format == "DXT5": + fourcc = D3DFMT.DXT5 + args = (3,) + else: + fourcc = D3DFMT.DX10 + if pixel_format == "BC2": + args = (2,) + dxgi_format = DXGI_FORMAT.BC2_TYPELESS + elif pixel_format == "BC3": + args = (3,) + dxgi_format = DXGI_FORMAT.BC3_TYPELESS + elif pixel_format == "BC5": + args = (5,) + dxgi_format = DXGI_FORMAT.BC5_TYPELESS + if im.mode != "RGB": + msg = "only RGB mode can be written as BC5" + raise OSError(msg) + else: + msg = f"cannot write pixel format {pixel_format}" + raise OSError(msg) + else: + codec_name = "raw" + flags |= DDSD.PITCH + pitch = (im.width * bitcount + 7) // 8 + + alpha = im.mode[-1] == "A" + if im.mode[0] == "L": + pixel_flags = DDPF.LUMINANCE + args = im.mode + if alpha: + rgba_mask = [0x000000FF, 0x000000FF, 0x000000FF] + else: + rgba_mask = [0xFF000000, 0xFF000000, 0xFF000000] + else: + pixel_flags = DDPF.RGB + args = im.mode[::-1] + rgba_mask = [0x00FF0000, 0x0000FF00, 0x000000FF] + + if alpha: + r, g, b, a = im.split() + im = Image.merge("RGBA", (a, r, g, b)) + if alpha: + pixel_flags |= DDPF.ALPHAPIXELS + rgba_mask.append(0xFF000000 if alpha else 0) + + fourcc = D3DFMT.UNKNOWN + fp.write( + o32(DDS_MAGIC) + + struct.pack( + "<7I", + 124, # header size + flags, # flags + im.height, + im.width, + pitch, + 0, # depth + 0, # mipmaps + ) + + struct.pack("11I", *((0,) * 11)) # reserved + # pfsize, pfflags, fourcc, bitcount + + struct.pack("<4I", 32, pixel_flags, fourcc, bitcount) + + struct.pack("<4I", *rgba_mask) # dwRGBABitMask + + struct.pack("<5I", DDSCAPS.TEXTURE, 0, 0, 0, 0) + ) + if fourcc == D3DFMT.DX10: + fp.write( + # dxgi_format, 2D resource, misc, array size, straight alpha + struct.pack("<5I", dxgi_format, 3, 0, 0, 1) + ) + ImageFile._save(im, fp, [ImageFile._Tile(codec_name, (0, 0) + im.size, 0, args)]) + + +def _accept(prefix: bytes) -> bool: + return prefix.startswith(b"DDS ") + + +Image.register_open(DdsImageFile.format, DdsImageFile, _accept) +Image.register_decoder("dds_rgb", DdsRgbDecoder) +Image.register_save(DdsImageFile.format, _save) +Image.register_extension(DdsImageFile.format, ".dds") diff --git a/.venv/lib/python3.11/site-packages/PIL/EpsImagePlugin.py b/.venv/lib/python3.11/site-packages/PIL/EpsImagePlugin.py new file mode 100644 index 0000000000000000000000000000000000000000..363ba19e13084f62d8d3d0e563a1ae48ae3cd0c8 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/EpsImagePlugin.py @@ -0,0 +1,484 @@ +# +# The Python Imaging Library. +# $Id$ +# +# EPS file handling +# +# History: +# 1995-09-01 fl Created (0.1) +# 1996-05-18 fl Don't choke on "atend" fields, Ghostscript interface (0.2) +# 1996-08-22 fl Don't choke on floating point BoundingBox values +# 1996-08-23 fl Handle files from Macintosh (0.3) +# 2001-02-17 fl Use 're' instead of 'regex' (Python 2.1) (0.4) +# 2003-09-07 fl Check gs.close status (from Federico Di Gregorio) (0.5) +# 2014-05-07 e Handling of EPS with binary preview and fixed resolution +# resizing +# +# Copyright (c) 1997-2003 by Secret Labs AB. +# Copyright (c) 1995-2003 by Fredrik Lundh +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import io +import os +import re +import subprocess +import sys +import tempfile +from typing import IO + +from . import Image, ImageFile +from ._binary import i32le as i32 + +# -------------------------------------------------------------------- + + +split = re.compile(r"^%%([^:]*):[ \t]*(.*)[ \t]*$") +field = re.compile(r"^%[%!\w]([^:]*)[ \t]*$") + +gs_binary: str | bool | None = None +gs_windows_binary = None + + +def has_ghostscript() -> bool: + global gs_binary, gs_windows_binary + if gs_binary is None: + if sys.platform.startswith("win"): + if gs_windows_binary is None: + import shutil + + for binary in ("gswin32c", "gswin64c", "gs"): + if shutil.which(binary) is not None: + gs_windows_binary = binary + break + else: + gs_windows_binary = False + gs_binary = gs_windows_binary + else: + try: + subprocess.check_call(["gs", "--version"], stdout=subprocess.DEVNULL) + gs_binary = "gs" + except OSError: + gs_binary = False + return gs_binary is not False + + +def Ghostscript( + tile: list[ImageFile._Tile], + size: tuple[int, int], + fp: IO[bytes], + scale: int = 1, + transparency: bool = False, +) -> Image.core.ImagingCore: + """Render an image using Ghostscript""" + global gs_binary + if not has_ghostscript(): + msg = "Unable to locate Ghostscript on paths" + raise OSError(msg) + assert isinstance(gs_binary, str) + + # Unpack decoder tile + args = tile[0].args + assert isinstance(args, tuple) + length, bbox = args + + # Hack to support hi-res rendering + scale = int(scale) or 1 + width = size[0] * scale + height = size[1] * scale + # resolution is dependent on bbox and size + res_x = 72.0 * width / (bbox[2] - bbox[0]) + res_y = 72.0 * height / (bbox[3] - bbox[1]) + + out_fd, outfile = tempfile.mkstemp() + os.close(out_fd) + + infile_temp = None + if hasattr(fp, "name") and os.path.exists(fp.name): + infile = fp.name + else: + in_fd, infile_temp = tempfile.mkstemp() + os.close(in_fd) + infile = infile_temp + + # Ignore length and offset! + # Ghostscript can read it + # Copy whole file to read in Ghostscript + with open(infile_temp, "wb") as f: + # fetch length of fp + fp.seek(0, io.SEEK_END) + fsize = fp.tell() + # ensure start position + # go back + fp.seek(0) + lengthfile = fsize + while lengthfile > 0: + s = fp.read(min(lengthfile, 100 * 1024)) + if not s: + break + lengthfile -= len(s) + f.write(s) + + if transparency: + # "RGBA" + device = "pngalpha" + else: + # "pnmraw" automatically chooses between + # PBM ("1"), PGM ("L"), and PPM ("RGB"). + device = "pnmraw" + + # Build Ghostscript command + command = [ + gs_binary, + "-q", # quiet mode + f"-g{width:d}x{height:d}", # set output geometry (pixels) + f"-r{res_x:f}x{res_y:f}", # set input DPI (dots per inch) + "-dBATCH", # exit after processing + "-dNOPAUSE", # don't pause between pages + "-dSAFER", # safe mode + f"-sDEVICE={device}", + f"-sOutputFile={outfile}", # output file + # adjust for image origin + "-c", + f"{-bbox[0]} {-bbox[1]} translate", + "-f", + infile, # input file + # showpage (see https://bugs.ghostscript.com/show_bug.cgi?id=698272) + "-c", + "showpage", + ] + + # push data through Ghostscript + try: + startupinfo = None + if sys.platform.startswith("win"): + startupinfo = subprocess.STARTUPINFO() + startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW + subprocess.check_call(command, startupinfo=startupinfo) + with Image.open(outfile) as out_im: + out_im.load() + return out_im.im.copy() + finally: + try: + os.unlink(outfile) + if infile_temp: + os.unlink(infile_temp) + except OSError: + pass + + +def _accept(prefix: bytes) -> bool: + return prefix.startswith(b"%!PS") or ( + len(prefix) >= 4 and i32(prefix) == 0xC6D3D0C5 + ) + + +## +# Image plugin for Encapsulated PostScript. This plugin supports only +# a few variants of this format. + + +class EpsImageFile(ImageFile.ImageFile): + """EPS File Parser for the Python Imaging Library""" + + format = "EPS" + format_description = "Encapsulated Postscript" + + mode_map = {1: "L", 2: "LAB", 3: "RGB", 4: "CMYK"} + + def _open(self) -> None: + assert self.fp is not None + length, offset = self._find_offset(self.fp) + + # go to offset - start of "%!PS" + self.fp.seek(offset) + + self._mode = "RGB" + + # When reading header comments, the first comment is used. + # When reading trailer comments, the last comment is used. + bounding_box: list[int] | None = None + imagedata_size: tuple[int, int] | None = None + + byte_arr = bytearray(255) + bytes_mv = memoryview(byte_arr) + bytes_read = 0 + reading_header_comments = True + reading_trailer_comments = False + trailer_reached = False + + def check_required_header_comments() -> None: + """ + The EPS specification requires that some headers exist. + This should be checked when the header comments formally end, + when image data starts, or when the file ends, whichever comes first. + """ + if "PS-Adobe" not in self.info: + msg = 'EPS header missing "%!PS-Adobe" comment' + raise SyntaxError(msg) + if "BoundingBox" not in self.info: + msg = 'EPS header missing "%%BoundingBox" comment' + raise SyntaxError(msg) + + def read_comment(s: str) -> bool: + nonlocal bounding_box, reading_trailer_comments + try: + m = split.match(s) + except re.error as e: + msg = "not an EPS file" + raise SyntaxError(msg) from e + + if not m: + return False + + k, v = m.group(1, 2) + self.info[k] = v + if k == "BoundingBox": + if v == "(atend)": + reading_trailer_comments = True + elif not bounding_box or (trailer_reached and reading_trailer_comments): + try: + # Note: The DSC spec says that BoundingBox + # fields should be integers, but some drivers + # put floating point values there anyway. + bounding_box = [int(float(i)) for i in v.split()] + except Exception: + pass + return True + + while True: + byte = self.fp.read(1) + if byte == b"": + # if we didn't read a byte we must be at the end of the file + if bytes_read == 0: + if reading_header_comments: + check_required_header_comments() + break + elif byte in b"\r\n": + # if we read a line ending character, ignore it and parse what + # we have already read. if we haven't read any other characters, + # continue reading + if bytes_read == 0: + continue + else: + # ASCII/hexadecimal lines in an EPS file must not exceed + # 255 characters, not including line ending characters + if bytes_read >= 255: + # only enforce this for lines starting with a "%", + # otherwise assume it's binary data + if byte_arr[0] == ord("%"): + msg = "not an EPS file" + raise SyntaxError(msg) + else: + if reading_header_comments: + check_required_header_comments() + reading_header_comments = False + # reset bytes_read so we can keep reading + # data until the end of the line + bytes_read = 0 + byte_arr[bytes_read] = byte[0] + bytes_read += 1 + continue + + if reading_header_comments: + # Load EPS header + + # if this line doesn't start with a "%", + # or does start with "%%EndComments", + # then we've reached the end of the header/comments + if byte_arr[0] != ord("%") or bytes_mv[:13] == b"%%EndComments": + check_required_header_comments() + reading_header_comments = False + continue + + s = str(bytes_mv[:bytes_read], "latin-1") + if not read_comment(s): + m = field.match(s) + if m: + k = m.group(1) + if k.startswith("PS-Adobe"): + self.info["PS-Adobe"] = k[9:] + else: + self.info[k] = "" + elif s[0] == "%": + # handle non-DSC PostScript comments that some + # tools mistakenly put in the Comments section + pass + else: + msg = "bad EPS header" + raise OSError(msg) + elif bytes_mv[:11] == b"%ImageData:": + # Check for an "ImageData" descriptor + # https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#50577413_pgfId-1035096 + + # If we've already read an "ImageData" descriptor, + # don't read another one. + if imagedata_size: + bytes_read = 0 + continue + + # Values: + # columns + # rows + # bit depth (1 or 8) + # mode (1: L, 2: LAB, 3: RGB, 4: CMYK) + # number of padding channels + # block size (number of bytes per row per channel) + # binary/ascii (1: binary, 2: ascii) + # data start identifier (the image data follows after a single line + # consisting only of this quoted value) + image_data_values = byte_arr[11:bytes_read].split(None, 7) + columns, rows, bit_depth, mode_id = ( + int(value) for value in image_data_values[:4] + ) + + if bit_depth == 1: + self._mode = "1" + elif bit_depth == 8: + try: + self._mode = self.mode_map[mode_id] + except ValueError: + break + else: + break + + # Parse the columns and rows after checking the bit depth and mode + # in case the bit depth and/or mode are invalid. + imagedata_size = columns, rows + elif bytes_mv[:5] == b"%%EOF": + break + elif trailer_reached and reading_trailer_comments: + # Load EPS trailer + s = str(bytes_mv[:bytes_read], "latin-1") + read_comment(s) + elif bytes_mv[:9] == b"%%Trailer": + trailer_reached = True + elif bytes_mv[:14] == b"%%BeginBinary:": + bytecount = int(byte_arr[14:bytes_read]) + if bytecount < 0: + msg = "BeginBinary bytecount cannot be negative" + raise ValueError(msg) + self.fp.seek(bytecount, os.SEEK_CUR) + bytes_read = 0 + + # A "BoundingBox" is always required, + # even if an "ImageData" descriptor size exists. + if not bounding_box: + msg = "cannot determine EPS bounding box" + raise OSError(msg) + + # An "ImageData" size takes precedence over the "BoundingBox". + self._size = imagedata_size or ( + bounding_box[2] - bounding_box[0], + bounding_box[3] - bounding_box[1], + ) + + self.tile = [ + ImageFile._Tile("eps", (0, 0) + self.size, offset, (length, bounding_box)) + ] + + def _find_offset(self, fp: IO[bytes]) -> tuple[int, int]: + s = fp.read(4) + + if s == b"%!PS": + # for HEAD without binary preview + fp.seek(0, io.SEEK_END) + length = fp.tell() + offset = 0 + elif i32(s) == 0xC6D3D0C5: + # FIX for: Some EPS file not handled correctly / issue #302 + # EPS can contain binary data + # or start directly with latin coding + # more info see: + # https://web.archive.org/web/20160528181353/http://partners.adobe.com/public/developer/en/ps/5002.EPSF_Spec.pdf + s = fp.read(8) + offset = i32(s) + length = i32(s, 4) + else: + msg = "not an EPS file" + raise SyntaxError(msg) + + return length, offset + + def load( + self, scale: int = 1, transparency: bool = False + ) -> Image.core.PixelAccess | None: + # Load EPS via Ghostscript + if self.tile: + assert self.fp is not None + self.im = Ghostscript(self.tile, self.size, self.fp, scale, transparency) + self._mode = self.im.mode + self._size = self.im.size + self.tile = [] + return Image.Image.load(self) + + def load_seek(self, pos: int) -> None: + # we can't incrementally load, so force ImageFile.parser to + # use our custom load method by defining this method. + pass + + +# -------------------------------------------------------------------- + + +def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes, eps: int = 1) -> None: + """EPS Writer for the Python Imaging Library.""" + + # make sure image data is available + im.load() + + # determine PostScript image mode + if im.mode == "L": + operator = (8, 1, b"image") + elif im.mode == "RGB": + operator = (8, 3, b"false 3 colorimage") + elif im.mode == "CMYK": + operator = (8, 4, b"false 4 colorimage") + else: + msg = "image mode is not supported" + raise ValueError(msg) + + if eps: + # write EPS header + fp.write(b"%!PS-Adobe-3.0 EPSF-3.0\n") + fp.write(b"%%Creator: PIL 0.1 EpsEncode\n") + # fp.write("%%CreationDate: %s"...) + fp.write(b"%%%%BoundingBox: 0 0 %d %d\n" % im.size) + fp.write(b"%%Pages: 1\n") + fp.write(b"%%EndComments\n") + fp.write(b"%%Page: 1 1\n") + fp.write(b"%%ImageData: %d %d " % im.size) + fp.write(b'%d %d 0 1 1 "%s"\n' % operator) + + # image header + fp.write(b"gsave\n") + fp.write(b"10 dict begin\n") + fp.write(b"/buf %d string def\n" % (im.size[0] * operator[1])) + fp.write(b"%d %d scale\n" % im.size) + fp.write(b"%d %d 8\n" % im.size) # <= bits + fp.write(b"[%d 0 0 -%d 0 %d]\n" % (im.size[0], im.size[1], im.size[1])) + fp.write(b"{ currentfile buf readhexstring pop } bind\n") + fp.write(operator[2] + b"\n") + if hasattr(fp, "flush"): + fp.flush() + + ImageFile._save(im, fp, [ImageFile._Tile("eps", (0, 0) + im.size)]) + + fp.write(b"\n%%%%EndBinary\n") + fp.write(b"grestore end\n") + if hasattr(fp, "flush"): + fp.flush() + + +# -------------------------------------------------------------------- + + +Image.register_open(EpsImageFile.format, EpsImageFile, _accept) + +Image.register_save(EpsImageFile.format, _save) + +Image.register_extensions(EpsImageFile.format, [".ps", ".eps"]) + +Image.register_mime(EpsImageFile.format, "application/postscript") diff --git a/.venv/lib/python3.11/site-packages/PIL/ExifTags.py b/.venv/lib/python3.11/site-packages/PIL/ExifTags.py new file mode 100644 index 0000000000000000000000000000000000000000..a9522e761b06e5cf64f5679e545192132f7e492c --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/ExifTags.py @@ -0,0 +1,384 @@ +# +# The Python Imaging Library. +# $Id$ +# +# EXIF tags +# +# Copyright (c) 2003 by Secret Labs AB +# +# See the README file for information on usage and redistribution. +# + +""" +This module provides constants and clear-text names for various +well-known EXIF tags. +""" + +from __future__ import annotations + +from enum import IntEnum + + +class Base(IntEnum): + # possibly incomplete + InteropIndex = 0x0001 + ProcessingSoftware = 0x000B + NewSubfileType = 0x00FE + SubfileType = 0x00FF + ImageWidth = 0x0100 + ImageLength = 0x0101 + BitsPerSample = 0x0102 + Compression = 0x0103 + PhotometricInterpretation = 0x0106 + Thresholding = 0x0107 + CellWidth = 0x0108 + CellLength = 0x0109 + FillOrder = 0x010A + DocumentName = 0x010D + ImageDescription = 0x010E + Make = 0x010F + Model = 0x0110 + StripOffsets = 0x0111 + Orientation = 0x0112 + SamplesPerPixel = 0x0115 + RowsPerStrip = 0x0116 + StripByteCounts = 0x0117 + MinSampleValue = 0x0118 + MaxSampleValue = 0x0119 + XResolution = 0x011A + YResolution = 0x011B + PlanarConfiguration = 0x011C + PageName = 0x011D + FreeOffsets = 0x0120 + FreeByteCounts = 0x0121 + GrayResponseUnit = 0x0122 + GrayResponseCurve = 0x0123 + T4Options = 0x0124 + T6Options = 0x0125 + ResolutionUnit = 0x0128 + PageNumber = 0x0129 + TransferFunction = 0x012D + Software = 0x0131 + DateTime = 0x0132 + Artist = 0x013B + HostComputer = 0x013C + Predictor = 0x013D + WhitePoint = 0x013E + PrimaryChromaticities = 0x013F + ColorMap = 0x0140 + HalftoneHints = 0x0141 + TileWidth = 0x0142 + TileLength = 0x0143 + TileOffsets = 0x0144 + TileByteCounts = 0x0145 + SubIFDs = 0x014A + InkSet = 0x014C + InkNames = 0x014D + NumberOfInks = 0x014E + DotRange = 0x0150 + TargetPrinter = 0x0151 + ExtraSamples = 0x0152 + SampleFormat = 0x0153 + SMinSampleValue = 0x0154 + SMaxSampleValue = 0x0155 + TransferRange = 0x0156 + ClipPath = 0x0157 + XClipPathUnits = 0x0158 + YClipPathUnits = 0x0159 + Indexed = 0x015A + JPEGTables = 0x015B + OPIProxy = 0x015F + JPEGProc = 0x0200 + JpegIFOffset = 0x0201 + JpegIFByteCount = 0x0202 + JpegRestartInterval = 0x0203 + JpegLosslessPredictors = 0x0205 + JpegPointTransforms = 0x0206 + JpegQTables = 0x0207 + JpegDCTables = 0x0208 + JpegACTables = 0x0209 + YCbCrCoefficients = 0x0211 + YCbCrSubSampling = 0x0212 + YCbCrPositioning = 0x0213 + ReferenceBlackWhite = 0x0214 + XMLPacket = 0x02BC + RelatedImageFileFormat = 0x1000 + RelatedImageWidth = 0x1001 + RelatedImageLength = 0x1002 + Rating = 0x4746 + RatingPercent = 0x4749 + ImageID = 0x800D + CFARepeatPatternDim = 0x828D + BatteryLevel = 0x828F + Copyright = 0x8298 + ExposureTime = 0x829A + FNumber = 0x829D + IPTCNAA = 0x83BB + ImageResources = 0x8649 + ExifOffset = 0x8769 + InterColorProfile = 0x8773 + ExposureProgram = 0x8822 + SpectralSensitivity = 0x8824 + GPSInfo = 0x8825 + ISOSpeedRatings = 0x8827 + OECF = 0x8828 + Interlace = 0x8829 + TimeZoneOffset = 0x882A + SelfTimerMode = 0x882B + SensitivityType = 0x8830 + StandardOutputSensitivity = 0x8831 + RecommendedExposureIndex = 0x8832 + ISOSpeed = 0x8833 + ISOSpeedLatitudeyyy = 0x8834 + ISOSpeedLatitudezzz = 0x8835 + ExifVersion = 0x9000 + DateTimeOriginal = 0x9003 + DateTimeDigitized = 0x9004 + OffsetTime = 0x9010 + OffsetTimeOriginal = 0x9011 + OffsetTimeDigitized = 0x9012 + ComponentsConfiguration = 0x9101 + CompressedBitsPerPixel = 0x9102 + ShutterSpeedValue = 0x9201 + ApertureValue = 0x9202 + BrightnessValue = 0x9203 + ExposureBiasValue = 0x9204 + MaxApertureValue = 0x9205 + SubjectDistance = 0x9206 + MeteringMode = 0x9207 + LightSource = 0x9208 + Flash = 0x9209 + FocalLength = 0x920A + Noise = 0x920D + ImageNumber = 0x9211 + SecurityClassification = 0x9212 + ImageHistory = 0x9213 + TIFFEPStandardID = 0x9216 + MakerNote = 0x927C + UserComment = 0x9286 + SubsecTime = 0x9290 + SubsecTimeOriginal = 0x9291 + SubsecTimeDigitized = 0x9292 + AmbientTemperature = 0x9400 + Humidity = 0x9401 + Pressure = 0x9402 + WaterDepth = 0x9403 + Acceleration = 0x9404 + CameraElevationAngle = 0x9405 + XPTitle = 0x9C9B + XPComment = 0x9C9C + XPAuthor = 0x9C9D + XPKeywords = 0x9C9E + XPSubject = 0x9C9F + FlashPixVersion = 0xA000 + ColorSpace = 0xA001 + ExifImageWidth = 0xA002 + ExifImageHeight = 0xA003 + RelatedSoundFile = 0xA004 + ExifInteroperabilityOffset = 0xA005 + FlashEnergy = 0xA20B + SpatialFrequencyResponse = 0xA20C + FocalPlaneXResolution = 0xA20E + FocalPlaneYResolution = 0xA20F + FocalPlaneResolutionUnit = 0xA210 + SubjectLocation = 0xA214 + ExposureIndex = 0xA215 + SensingMethod = 0xA217 + FileSource = 0xA300 + SceneType = 0xA301 + CFAPattern = 0xA302 + CustomRendered = 0xA401 + ExposureMode = 0xA402 + WhiteBalance = 0xA403 + DigitalZoomRatio = 0xA404 + FocalLengthIn35mmFilm = 0xA405 + SceneCaptureType = 0xA406 + GainControl = 0xA407 + Contrast = 0xA408 + Saturation = 0xA409 + Sharpness = 0xA40A + DeviceSettingDescription = 0xA40B + SubjectDistanceRange = 0xA40C + ImageUniqueID = 0xA420 + CameraOwnerName = 0xA430 + BodySerialNumber = 0xA431 + LensSpecification = 0xA432 + LensMake = 0xA433 + LensModel = 0xA434 + LensSerialNumber = 0xA435 + CompositeImage = 0xA460 + CompositeImageCount = 0xA461 + CompositeImageExposureTimes = 0xA462 + Gamma = 0xA500 + PrintImageMatching = 0xC4A5 + DNGVersion = 0xC612 + DNGBackwardVersion = 0xC613 + UniqueCameraModel = 0xC614 + LocalizedCameraModel = 0xC615 + CFAPlaneColor = 0xC616 + CFALayout = 0xC617 + LinearizationTable = 0xC618 + BlackLevelRepeatDim = 0xC619 + BlackLevel = 0xC61A + BlackLevelDeltaH = 0xC61B + BlackLevelDeltaV = 0xC61C + WhiteLevel = 0xC61D + DefaultScale = 0xC61E + DefaultCropOrigin = 0xC61F + DefaultCropSize = 0xC620 + ColorMatrix1 = 0xC621 + ColorMatrix2 = 0xC622 + CameraCalibration1 = 0xC623 + CameraCalibration2 = 0xC624 + ReductionMatrix1 = 0xC625 + ReductionMatrix2 = 0xC626 + AnalogBalance = 0xC627 + AsShotNeutral = 0xC628 + AsShotWhiteXY = 0xC629 + BaselineExposure = 0xC62A + BaselineNoise = 0xC62B + BaselineSharpness = 0xC62C + BayerGreenSplit = 0xC62D + LinearResponseLimit = 0xC62E + CameraSerialNumber = 0xC62F + LensInfo = 0xC630 + ChromaBlurRadius = 0xC631 + AntiAliasStrength = 0xC632 + ShadowScale = 0xC633 + DNGPrivateData = 0xC634 + MakerNoteSafety = 0xC635 + CalibrationIlluminant1 = 0xC65A + CalibrationIlluminant2 = 0xC65B + BestQualityScale = 0xC65C + RawDataUniqueID = 0xC65D + OriginalRawFileName = 0xC68B + OriginalRawFileData = 0xC68C + ActiveArea = 0xC68D + MaskedAreas = 0xC68E + AsShotICCProfile = 0xC68F + AsShotPreProfileMatrix = 0xC690 + CurrentICCProfile = 0xC691 + CurrentPreProfileMatrix = 0xC692 + ColorimetricReference = 0xC6BF + CameraCalibrationSignature = 0xC6F3 + ProfileCalibrationSignature = 0xC6F4 + AsShotProfileName = 0xC6F6 + NoiseReductionApplied = 0xC6F7 + ProfileName = 0xC6F8 + ProfileHueSatMapDims = 0xC6F9 + ProfileHueSatMapData1 = 0xC6FA + ProfileHueSatMapData2 = 0xC6FB + ProfileToneCurve = 0xC6FC + ProfileEmbedPolicy = 0xC6FD + ProfileCopyright = 0xC6FE + ForwardMatrix1 = 0xC714 + ForwardMatrix2 = 0xC715 + PreviewApplicationName = 0xC716 + PreviewApplicationVersion = 0xC717 + PreviewSettingsName = 0xC718 + PreviewSettingsDigest = 0xC719 + PreviewColorSpace = 0xC71A + PreviewDateTime = 0xC71B + RawImageDigest = 0xC71C + OriginalRawFileDigest = 0xC71D + SubTileBlockSize = 0xC71E + RowInterleaveFactor = 0xC71F + ProfileLookTableDims = 0xC725 + ProfileLookTableData = 0xC726 + OpcodeList1 = 0xC740 + OpcodeList2 = 0xC741 + OpcodeList3 = 0xC74E + NoiseProfile = 0xC761 + FrameRate = 0xC764 + + +"""Maps EXIF tags to tag names.""" +TAGS = { + **{i.value: i.name for i in Base}, + 0x920C: "SpatialFrequencyResponse", + 0x9214: "SubjectLocation", + 0x9215: "ExposureIndex", + 0x828E: "CFAPattern", + 0x920B: "FlashEnergy", + 0x9216: "TIFF/EPStandardID", +} + + +class GPS(IntEnum): + GPSVersionID = 0x00 + GPSLatitudeRef = 0x01 + GPSLatitude = 0x02 + GPSLongitudeRef = 0x03 + GPSLongitude = 0x04 + GPSAltitudeRef = 0x05 + GPSAltitude = 0x06 + GPSTimeStamp = 0x07 + GPSSatellites = 0x08 + GPSStatus = 0x09 + GPSMeasureMode = 0x0A + GPSDOP = 0x0B + GPSSpeedRef = 0x0C + GPSSpeed = 0x0D + GPSTrackRef = 0x0E + GPSTrack = 0x0F + GPSImgDirectionRef = 0x10 + GPSImgDirection = 0x11 + GPSMapDatum = 0x12 + GPSDestLatitudeRef = 0x13 + GPSDestLatitude = 0x14 + GPSDestLongitudeRef = 0x15 + GPSDestLongitude = 0x16 + GPSDestBearingRef = 0x17 + GPSDestBearing = 0x18 + GPSDestDistanceRef = 0x19 + GPSDestDistance = 0x1A + GPSProcessingMethod = 0x1B + GPSAreaInformation = 0x1C + GPSDateStamp = 0x1D + GPSDifferential = 0x1E + GPSHPositioningError = 0x1F + + +"""Maps EXIF GPS tags to tag names.""" +GPSTAGS = {i.value: i.name for i in GPS} + + +class Interop(IntEnum): + InteropIndex = 0x0001 + InteropVersion = 0x0002 + RelatedImageFileFormat = 0x1000 + RelatedImageWidth = 0x1001 + RelatedImageHeight = 0x1002 + + +class IFD(IntEnum): + Exif = 0x8769 + GPSInfo = 0x8825 + MakerNote = 0x927C + Makernote = 0x927C # Deprecated + Interop = 0xA005 + IFD1 = -1 + + +class LightSource(IntEnum): + Unknown = 0x00 + Daylight = 0x01 + Fluorescent = 0x02 + Tungsten = 0x03 + Flash = 0x04 + Fine = 0x09 + Cloudy = 0x0A + Shade = 0x0B + DaylightFluorescent = 0x0C + DayWhiteFluorescent = 0x0D + CoolWhiteFluorescent = 0x0E + WhiteFluorescent = 0x0F + StandardLightA = 0x11 + StandardLightB = 0x12 + StandardLightC = 0x13 + D55 = 0x14 + D65 = 0x15 + D75 = 0x16 + D50 = 0x17 + ISO = 0x18 + Other = 0xFF diff --git a/.venv/lib/python3.11/site-packages/PIL/FitsImagePlugin.py b/.venv/lib/python3.11/site-packages/PIL/FitsImagePlugin.py new file mode 100644 index 0000000000000000000000000000000000000000..dca61c2e21b29011c39de8d695fc4b0283ae9c52 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/FitsImagePlugin.py @@ -0,0 +1,153 @@ +# +# The Python Imaging Library +# $Id$ +# +# FITS file handling +# +# Copyright (c) 1998-2003 by Fredrik Lundh +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import gzip +import math + +from . import Image, ImageFile + + +def _accept(prefix: bytes) -> bool: + return prefix.startswith(b"SIMPLE") + + +class FitsImageFile(ImageFile.ImageFile): + format = "FITS" + format_description = "FITS" + + def _open(self) -> None: + assert self.fp is not None + + headers: dict[bytes, bytes] = {} + header_in_progress = False + decoder_name = "" + while True: + header = self.fp.read(80) + if not header: + msg = "Truncated FITS file" + raise OSError(msg) + keyword = header[:8].strip() + if keyword in (b"SIMPLE", b"XTENSION"): + header_in_progress = True + elif headers and not header_in_progress: + # This is now a data unit + break + elif keyword == b"END": + # Seek to the end of the header unit + self.fp.seek(math.ceil(self.fp.tell() / 2880) * 2880) + if not decoder_name: + decoder_name, offset, args = self._parse_headers(headers) + + header_in_progress = False + continue + + if decoder_name: + # Keep going to read past the headers + continue + + value = header[8:].split(b"/")[0].strip() + if value.startswith(b"="): + value = value[1:].strip() + if not headers and (not _accept(keyword) or value != b"T"): + msg = "Not a FITS file" + raise SyntaxError(msg) + headers[keyword] = value + + if not decoder_name: + msg = "No image data" + raise ValueError(msg) + + offset += self.fp.tell() - 80 + self.tile = [ImageFile._Tile(decoder_name, (0, 0) + self.size, offset, args)] + + def _get_size( + self, headers: dict[bytes, bytes], prefix: bytes + ) -> tuple[int, int] | None: + naxis = int(headers[prefix + b"NAXIS"]) + if naxis == 0: + return None + + if naxis == 1: + return 1, int(headers[prefix + b"NAXIS1"]) + else: + return int(headers[prefix + b"NAXIS1"]), int(headers[prefix + b"NAXIS2"]) + + def _parse_headers( + self, headers: dict[bytes, bytes] + ) -> tuple[str, int, tuple[str | int, ...]]: + prefix = b"" + decoder_name = "raw" + offset = 0 + if ( + headers.get(b"XTENSION") == b"'BINTABLE'" + and headers.get(b"ZIMAGE") == b"T" + and headers[b"ZCMPTYPE"] == b"'GZIP_1 '" + ): + no_prefix_size = self._get_size(headers, prefix) or (0, 0) + number_of_bits = int(headers[b"BITPIX"]) + offset = no_prefix_size[0] * no_prefix_size[1] * (number_of_bits // 8) + + prefix = b"Z" + decoder_name = "fits_gzip" + + size = self._get_size(headers, prefix) + if not size: + return "", 0, () + + self._size = size + + number_of_bits = int(headers[prefix + b"BITPIX"]) + if number_of_bits == 8: + self._mode = "L" + elif number_of_bits == 16: + self._mode = "I;16" + elif number_of_bits == 32: + self._mode = "I" + elif number_of_bits in (-32, -64): + self._mode = "F" + + args: tuple[str | int, ...] + if decoder_name == "raw": + args = (self.mode, 0, -1) + else: + args = (number_of_bits,) + return decoder_name, offset, args + + +class FitsGzipDecoder(ImageFile.PyDecoder): + _pulls_fd = True + + def decode(self, buffer: Image.DecoderInput) -> tuple[int, int]: + assert self.fd is not None + with gzip.open(self.fd) as fp: + value = fp.read(self.state.xsize * self.state.ysize * 4) + + rows = [] + offset = 0 + number_of_bits = min(self.args[0] // 8, 4) + for y in range(self.state.ysize): + row = bytearray() + for x in range(self.state.xsize): + row += value[offset + (4 - number_of_bits) : offset + 4] + offset += 4 + rows.append(row) + self.set_as_raw(bytes([pixel for row in rows[::-1] for pixel in row])) + return -1, 0 + + +# -------------------------------------------------------------------- +# Registry + +Image.register_open(FitsImageFile.format, FitsImageFile, _accept) +Image.register_decoder("fits_gzip", FitsGzipDecoder) + +Image.register_extensions(FitsImageFile.format, [".fit", ".fits"]) diff --git a/.venv/lib/python3.11/site-packages/PIL/FliImagePlugin.py b/.venv/lib/python3.11/site-packages/PIL/FliImagePlugin.py new file mode 100644 index 0000000000000000000000000000000000000000..da1e8e95cf3263bb2e22ba45d6d2934fc4f2b54f --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/FliImagePlugin.py @@ -0,0 +1,184 @@ +# +# The Python Imaging Library. +# $Id$ +# +# FLI/FLC file handling. +# +# History: +# 95-09-01 fl Created +# 97-01-03 fl Fixed parser, setup decoder tile +# 98-07-15 fl Renamed offset attribute to avoid name clash +# +# Copyright (c) Secret Labs AB 1997-98. +# Copyright (c) Fredrik Lundh 1995-97. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import os + +from . import Image, ImageFile, ImagePalette +from ._binary import i16le as i16 +from ._binary import i32le as i32 +from ._binary import o8 +from ._util import DeferredError + +# +# decoder + + +def _accept(prefix: bytes) -> bool: + return ( + len(prefix) >= 16 + and i16(prefix, 4) in [0xAF11, 0xAF12] + and i16(prefix, 14) in [0, 3] # flags + ) + + +## +# Image plugin for the FLI/FLC animation format. Use the seek +# method to load individual frames. + + +class FliImageFile(ImageFile.ImageFile): + format = "FLI" + format_description = "Autodesk FLI/FLC Animation" + _close_exclusive_fp_after_loading = False + + def _open(self) -> None: + # HEAD + assert self.fp is not None + s = self.fp.read(128) + if not ( + _accept(s) + and s[20:22] == b"\x00" * 2 + and s[42:80] == b"\x00" * 38 + and s[88:] == b"\x00" * 40 + ): + msg = "not an FLI/FLC file" + raise SyntaxError(msg) + + # frames + self.n_frames = i16(s, 6) + self.is_animated = self.n_frames > 1 + + # image characteristics + self._mode = "P" + self._size = i16(s, 8), i16(s, 10) + + # animation speed + duration = i32(s, 16) + magic = i16(s, 4) + if magic == 0xAF11: + duration = (duration * 1000) // 70 + self.info["duration"] = duration + + # look for palette + palette = [(a, a, a) for a in range(256)] + + s = self.fp.read(16) + + self.__offset = 128 + + if i16(s, 4) == 0xF100: + # prefix chunk; ignore it + self.fp.seek(self.__offset + i32(s)) + s = self.fp.read(16) + + if i16(s, 4) == 0xF1FA: + # look for palette chunk + number_of_subchunks = i16(s, 6) + chunk_size: int | None = None + for _ in range(number_of_subchunks): + if chunk_size is not None: + self.fp.seek(chunk_size - 6, os.SEEK_CUR) + s = self.fp.read(6) + chunk_type = i16(s, 4) + if chunk_type in (4, 11): + self._palette(palette, 2 if chunk_type == 11 else 0) + break + chunk_size = i32(s) + if not chunk_size: + break + + self.palette = ImagePalette.raw( + "RGB", b"".join(o8(r) + o8(g) + o8(b) for (r, g, b) in palette) + ) + + # set things up to decode first frame + self.__frame = -1 + self._fp = self.fp + self.__rewind = self.fp.tell() + self.seek(0) + + def _palette(self, palette: list[tuple[int, int, int]], shift: int) -> None: + # load palette + + i = 0 + assert self.fp is not None + for e in range(i16(self.fp.read(2))): + s = self.fp.read(2) + i = i + s[0] + n = s[1] + if n == 0: + n = 256 + s = self.fp.read(n * 3) + for n in range(0, len(s), 3): + r = s[n] << shift + g = s[n + 1] << shift + b = s[n + 2] << shift + palette[i] = (r, g, b) + i += 1 + + def seek(self, frame: int) -> None: + if not self._seek_check(frame): + return + if frame < self.__frame: + self._seek(0) + + for f in range(self.__frame + 1, frame + 1): + self._seek(f) + + def _seek(self, frame: int) -> None: + if isinstance(self._fp, DeferredError): + raise self._fp.ex + if frame == 0: + self.__frame = -1 + self._fp.seek(self.__rewind) + self.__offset = 128 + else: + # ensure that the previous frame was loaded + self.load() + + if frame != self.__frame + 1: + msg = f"cannot seek to frame {frame}" + raise ValueError(msg) + self.__frame = frame + + # move to next frame + self.fp = self._fp + self.fp.seek(self.__offset) + + s = self.fp.read(4) + if not s: + msg = "missing frame size" + raise EOFError(msg) + + framesize = i32(s) + + self.decodermaxblock = framesize + self.tile = [ImageFile._Tile("fli", (0, 0) + self.size, self.__offset)] + + self.__offset += framesize + + def tell(self) -> int: + return self.__frame + + +# +# registry + +Image.register_open(FliImageFile.format, FliImageFile, _accept) + +Image.register_extensions(FliImageFile.format, [".fli", ".flc"]) diff --git a/.venv/lib/python3.11/site-packages/PIL/FontFile.py b/.venv/lib/python3.11/site-packages/PIL/FontFile.py new file mode 100644 index 0000000000000000000000000000000000000000..c3be4ae3dddfecb1826ddba6ca5c020c49e0bba5 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/FontFile.py @@ -0,0 +1,160 @@ +# +# The Python Imaging Library +# $Id$ +# +# base class for raster font file parsers +# +# history: +# 1997-06-05 fl created +# 1997-08-19 fl restrict image width +# +# Copyright (c) 1997-1998 by Secret Labs AB +# Copyright (c) 1997-1998 by Fredrik Lundh +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import os +from typing import BinaryIO + +from . import Image, ImageFont, _binary + +WIDTH = 800 + + +def puti16( + fp: BinaryIO, values: tuple[int, int, int, int, int, int, int, int, int, int] +) -> None: + """Write network order (big-endian) 16-bit sequence""" + for v in values: + if v < 0: + v += 65536 + fp.write(_binary.o16be(v)) + + +class FontFile: + """Base class for raster font file handlers.""" + + bitmap: Image.Image | None = None + + def __init__(self) -> None: + self.info: dict[bytes, bytes | int] = {} + self.glyph: list[ + tuple[ + tuple[int, int], + tuple[int, int, int, int], + tuple[int, int, int, int], + Image.Image, + ] + | None + ] = [None] * 256 + + def __getitem__(self, ix: int) -> ( + tuple[ + tuple[int, int], + tuple[int, int, int, int], + tuple[int, int, int, int], + Image.Image, + ] + | None + ): + return self.glyph[ix] + + def compile(self) -> None: + """Create metrics and bitmap""" + + if self.bitmap: + return + + # create bitmap large enough to hold all data + h = w = maxwidth = 0 + lines = 1 + for glyph in self.glyph: + if glyph: + d, dst, src, im = glyph + h = max(h, src[3] - src[1]) + w += src[2] - src[0] + if w > WIDTH: + lines += 1 + w = src[2] - src[0] + maxwidth = max(maxwidth, w) + + xsize = maxwidth + ysize = lines * h + + if xsize == 0 and ysize == 0: + return + + self.ysize = h + + # paste glyphs into bitmap + Image._decompression_bomb_check((xsize, ysize)) + self.bitmap = Image.new("1", (xsize, ysize)) + self.metrics: list[ + tuple[tuple[int, int], tuple[int, int, int, int], tuple[int, int, int, int]] + | None + ] = [None] * 256 + x = y = 0 + for i in range(256): + glyph = self[i] + if glyph: + d, dst, src, im = glyph + xx = src[2] - src[0] + x0, y0 = x, y + x = x + xx + if x > WIDTH: + x, y = 0, y + h + x0, y0 = x, y + x = xx + s = src[0] + x0, src[1] + y0, src[2] + x0, src[3] + y0 + self.bitmap.paste(im.crop(src), s) + self.metrics[i] = d, dst, s + + def _encode_metrics(self) -> bytes: + values: list[int] = [] + for i in range(256): + m = self.metrics[i] + if m: + values.extend(m[0] + m[1] + m[2]) + else: + values.extend((0,) * 10) + + data = bytearray() + for v in values: + if v < 0: + v += 65536 + data += _binary.o16be(v) + return bytes(data) + + def save(self, filename: str) -> None: + """Save font""" + + self.compile() + + # font data + if not self.bitmap: + msg = "No bitmap created" + raise ValueError(msg) + self.bitmap.save(os.path.splitext(filename)[0] + ".pbm", "PNG") + + # font metrics + with open(os.path.splitext(filename)[0] + ".pil", "wb") as fp: + fp.write(b"PILfont\n") + fp.write(f";;;;;;{self.ysize};\n".encode("ascii")) # HACK!!! + fp.write(b"DATA\n") + fp.write(self._encode_metrics()) + + def to_imagefont(self) -> ImageFont.ImageFont: + """Convert to ImageFont""" + + self.compile() + + # font data + if not self.bitmap: + msg = "No bitmap created" + raise ValueError(msg) + + imagefont = ImageFont.ImageFont() + imagefont._load(self.bitmap, self._encode_metrics()) + return imagefont diff --git a/.venv/lib/python3.11/site-packages/PIL/FpxImagePlugin.py b/.venv/lib/python3.11/site-packages/PIL/FpxImagePlugin.py new file mode 100644 index 0000000000000000000000000000000000000000..f7eafe4d5e764762df6d9c6cc4e6df39112a9e87 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/FpxImagePlugin.py @@ -0,0 +1,262 @@ +# +# THIS IS WORK IN PROGRESS +# +# The Python Imaging Library. +# $Id$ +# +# FlashPix support for PIL +# +# History: +# 97-01-25 fl Created (reads uncompressed RGB images only) +# +# Copyright (c) Secret Labs AB 1997. +# Copyright (c) Fredrik Lundh 1997. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import olefile + +from . import Image, ImageFile +from ._binary import i32le as i32 + +# we map from colour field tuples to (mode, rawmode) descriptors +MODES = { + # opacity + (0x00007FFE,): ("A", "L"), + # monochrome + (0x00010000,): ("L", "L"), + (0x00018000, 0x00017FFE): ("RGBA", "LA"), + # photo YCC + (0x00020000, 0x00020001, 0x00020002): ("RGB", "YCC;P"), + (0x00028000, 0x00028001, 0x00028002, 0x00027FFE): ("RGBA", "YCCA;P"), + # standard RGB (NIFRGB) + (0x00030000, 0x00030001, 0x00030002): ("RGB", "RGB"), + (0x00038000, 0x00038001, 0x00038002, 0x00037FFE): ("RGBA", "RGBA"), +} + + +# +# -------------------------------------------------------------------- + + +def _accept(prefix: bytes) -> bool: + return prefix.startswith(olefile.MAGIC) + + +## +# Image plugin for the FlashPix images. + + +class FpxImageFile(ImageFile.ImageFile): + format = "FPX" + format_description = "FlashPix" + + def _open(self) -> None: + # + # read the OLE directory and see if this is a likely + # to be a FlashPix file + + assert self.fp is not None + try: + self.ole = olefile.OleFileIO(self.fp) + except OSError as e: + msg = "not an FPX file; invalid OLE file" + raise SyntaxError(msg) from e + + root = self.ole.root + if not root or root.clsid != "56616700-C154-11CE-8553-00AA00A1F95B": + msg = "not an FPX file; bad root CLSID" + raise SyntaxError(msg) + + self._open_index(1) + + def _open_index(self, index: int = 1) -> None: + # + # get the Image Contents Property Set + + prop = self.ole.getproperties( + [f"Data Object Store {index:06d}", "\005Image Contents"] + ) + + # size (highest resolution) + + assert isinstance(prop[0x1000002], int) + assert isinstance(prop[0x1000003], int) + self._size = prop[0x1000002], prop[0x1000003] + + size = max(self.size) + i = 1 + while size > 64: + size = size // 2 + i += 1 + self.maxid = i - 1 + + # mode. instead of using a single field for this, flashpix + # requires you to specify the mode for each channel in each + # resolution subimage, and leaves it to the decoder to make + # sure that they all match. for now, we'll cheat and assume + # that this is always the case. + + id = self.maxid << 16 + + s = prop[0x2000002 | id] + + if not isinstance(s, bytes) or (bands := i32(s, 4)) > 4: + msg = "Invalid number of bands" + raise OSError(msg) + + # note: for now, we ignore the "uncalibrated" flag + colors = tuple(i32(s, 8 + i * 4) & 0x7FFFFFFF for i in range(bands)) + + self._mode, self.rawmode = MODES[colors] + + # load JPEG tables, if any + self.jpeg = {} + for i in range(256): + id = 0x3000001 | (i << 16) + if id in prop: + self.jpeg[i] = prop[id] + + self._open_subimage(1, self.maxid) + + def _open_subimage(self, index: int = 1, subimage: int = 0) -> None: + # + # setup tile descriptors for a given subimage + + stream = [ + f"Data Object Store {index:06d}", + f"Resolution {subimage:04d}", + "Subimage 0000 Header", + ] + + fp = self.ole.openstream(stream) + + # skip prefix + fp.read(28) + + # header stream + s = fp.read(36) + + size = i32(s, 4), i32(s, 8) + # tilecount = i32(s, 12) + xtile, ytile = i32(s, 16), i32(s, 20) + if xtile != 64 or ytile != 64: + msg = "Tile must be 64 pixels by 64 pixels" + raise ValueError(msg) + + # channels = i32(s, 24) + offset = i32(s, 28) + length = i32(s, 32) + + if size != self.size: + msg = "subimage mismatch" + raise OSError(msg) + + # get tile descriptors + fp.seek(28 + offset) + s = fp.read(i32(s, 12) * length) + + x = y = 0 + xsize, ysize = size + self.tile = [] + + for i in range(0, len(s), length): + x1 = min(xsize, x + xtile) + y1 = min(ysize, y + ytile) + + compression = i32(s, i + 8) + + if compression == 0: + self.tile.append( + ImageFile._Tile( + "raw", + (x, y, x1, y1), + i32(s, i) + 28, + self.rawmode, + ) + ) + + elif compression == 1: + # FIXME: the fill decoder is not implemented + self.tile.append( + ImageFile._Tile( + "fill", + (x, y, x1, y1), + i32(s, i) + 28, + (self.rawmode, s[12:16]), + ) + ) + + elif compression == 2: + internal_color_conversion = s[14] + jpeg_tables = s[15] + rawmode = self.rawmode + + if internal_color_conversion: + # The image is stored as usual (usually YCbCr). + if rawmode == "RGBA": + # For "RGBA", data is stored as YCbCrA based on + # negative RGB. The following trick works around + # this problem : + jpegmode, rawmode = "YCbCrK", "CMYK" + else: + jpegmode = None # let the decoder decide + + else: + # The image is stored as defined by rawmode + jpegmode = rawmode + + self.tile.append( + ImageFile._Tile( + "jpeg", + (x, y, x1, y1), + i32(s, i) + 28, + (rawmode, jpegmode), + ) + ) + + # FIXME: jpeg tables are tile dependent; the prefix + # data must be placed in the tile descriptor itself! + + if jpeg_tables: + self.tile_prefix = self.jpeg[jpeg_tables] + + else: + msg = "unknown/invalid compression" + raise OSError(msg) + + x += xtile + if x >= xsize: + x, y = 0, y + ytile + if y >= ysize: + break # isn't really required + + assert self.fp is not None + self.stream = stream + self._fp = self.fp + self.fp = None + + def load(self) -> Image.core.PixelAccess | None: + if not self.fp: + self.fp = self.ole.openstream(self.stream[:2] + ["Subimage 0000 Data"]) + + return ImageFile.ImageFile.load(self) + + def close(self) -> None: + self.ole.close() + super().close() + + def __exit__(self, *args: object) -> None: + self.ole.close() + super().__exit__() + + +# +# -------------------------------------------------------------------- + + +Image.register_open(FpxImageFile.format, FpxImageFile, _accept) + +Image.register_extension(FpxImageFile.format, ".fpx") diff --git a/.venv/lib/python3.11/site-packages/PIL/FtexImagePlugin.py b/.venv/lib/python3.11/site-packages/PIL/FtexImagePlugin.py new file mode 100644 index 0000000000000000000000000000000000000000..e4d836cbdb27cc891f2cf62659eabcfaa37ffb70 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/FtexImagePlugin.py @@ -0,0 +1,115 @@ +""" +A Pillow loader for .ftc and .ftu files (FTEX) +Jerome Leclanche + +The contents of this file are hereby released in the public domain (CC0) +Full text of the CC0 license: + https://creativecommons.org/publicdomain/zero/1.0/ + +Independence War 2: Edge Of Chaos - Texture File Format - 16 October 2001 + +The textures used for 3D objects in Independence War 2: Edge Of Chaos are in a +packed custom format called FTEX. This file format uses file extensions FTC +and FTU. +* FTC files are compressed textures (using standard texture compression). +* FTU files are not compressed. +Texture File Format +The FTC and FTU texture files both use the same format. This +has the following structure: +{header} +{format_directory} +{data} +Where: +{header} = { + u32:magic, + u32:version, + u32:width, + u32:height, + u32:mipmap_count, + u32:format_count +} + +* The "magic" number is "FTEX". +* "width" and "height" are the dimensions of the texture. +* "mipmap_count" is the number of mipmaps in the texture. +* "format_count" is the number of texture formats (different versions of the +same texture) in this file. + +{format_directory} = format_count * { u32:format, u32:where } + +The format value is 0 for DXT1 compressed textures and 1 for 24-bit RGB +uncompressed textures. +The texture data for a format starts at the position "where" in the file. + +Each set of texture data in the file has the following structure: +{data} = format_count * { u32:mipmap_size, mipmap_size * { u8 } } +* "mipmap_size" is the number of bytes in that mip level. For compressed +textures this is the size of the texture data compressed with DXT1. For 24 bit +uncompressed textures, this is 3 * width * height. Following this are the image +bytes for that mipmap level. + +Note: All data is stored in little-Endian (Intel) byte order. +""" + +from __future__ import annotations + +import struct +from enum import IntEnum +from io import BytesIO + +from . import Image, ImageFile + +MAGIC = b"FTEX" + + +class Format(IntEnum): + DXT1 = 0 + UNCOMPRESSED = 1 + + +class FtexImageFile(ImageFile.ImageFile): + format = "FTEX" + format_description = "Texture File Format (IW2:EOC)" + + def _open(self) -> None: + assert self.fp is not None + if not _accept(self.fp.read(4)): + msg = "not an FTEX file" + raise SyntaxError(msg) + struct.unpack(" None: + pass + + +def _accept(prefix: bytes) -> bool: + return prefix.startswith(MAGIC) + + +Image.register_open(FtexImageFile.format, FtexImageFile, _accept) +Image.register_extensions(FtexImageFile.format, [".ftc", ".ftu"]) diff --git a/.venv/lib/python3.11/site-packages/PIL/GbrImagePlugin.py b/.venv/lib/python3.11/site-packages/PIL/GbrImagePlugin.py new file mode 100644 index 0000000000000000000000000000000000000000..ec666c81c2c6aab6d243747e844e13a0cc1d296f --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/GbrImagePlugin.py @@ -0,0 +1,103 @@ +# +# The Python Imaging Library +# +# load a GIMP brush file +# +# History: +# 96-03-14 fl Created +# 16-01-08 es Version 2 +# +# Copyright (c) Secret Labs AB 1997. +# Copyright (c) Fredrik Lundh 1996. +# Copyright (c) Eric Soroos 2016. +# +# See the README file for information on usage and redistribution. +# +# +# See https://github.com/GNOME/gimp/blob/mainline/devel-docs/gbr.txt for +# format documentation. +# +# This code Interprets version 1 and 2 .gbr files. +# Version 1 files are obsolete, and should not be used for new +# brushes. +# Version 2 files are saved by GIMP v2.8 (at least) +# Version 3 files have a format specifier of 18 for 16bit floats in +# the color depth field. This is currently unsupported by Pillow. +from __future__ import annotations + +from . import Image, ImageFile +from ._binary import i32be as i32 + + +def _accept(prefix: bytes) -> bool: + return len(prefix) >= 8 and i32(prefix, 0) >= 20 and i32(prefix, 4) in (1, 2) + + +## +# Image plugin for the GIMP brush format. + + +class GbrImageFile(ImageFile.ImageFile): + format = "GBR" + format_description = "GIMP brush file" + + def _open(self) -> None: + assert self.fp is not None + header_size = i32(self.fp.read(4)) + if header_size < 20: + msg = "not a GIMP brush" + raise SyntaxError(msg) + version = i32(self.fp.read(4)) + if version not in (1, 2): + msg = f"Unsupported GIMP brush version: {version}" + raise SyntaxError(msg) + + width = i32(self.fp.read(4)) + height = i32(self.fp.read(4)) + color_depth = i32(self.fp.read(4)) + if width == 0 or height == 0: + msg = "not a GIMP brush" + raise SyntaxError(msg) + if color_depth not in (1, 4): + msg = f"Unsupported GIMP brush color depth: {color_depth}" + raise SyntaxError(msg) + + if version == 1: + comment_length = header_size - 20 + else: + comment_length = header_size - 28 + magic_number = self.fp.read(4) + if magic_number != b"GIMP": + msg = "not a GIMP brush, bad magic number" + raise SyntaxError(msg) + self.info["spacing"] = i32(self.fp.read(4)) + + self.info["comment"] = self.fp.read(comment_length)[:-1] + + if color_depth == 1: + self._mode = "L" + else: + self._mode = "RGBA" + + self._size = width, height + + # Image might not be small + Image._decompression_bomb_check(self.size) + + # Data is an uncompressed block of w * h * bytes/pixel + self._data_size = width * height * color_depth + + def load(self) -> Image.core.PixelAccess | None: + if self._im is None: + assert self.fp is not None + self.im = Image.core.new(self.mode, self.size) + self.frombytes(self.fp.read(self._data_size)) + return Image.Image.load(self) + + +# +# registry + + +Image.register_open(GbrImageFile.format, GbrImageFile, _accept) +Image.register_extension(GbrImageFile.format, ".gbr") diff --git a/.venv/lib/python3.11/site-packages/PIL/GdImageFile.py b/.venv/lib/python3.11/site-packages/PIL/GdImageFile.py new file mode 100644 index 0000000000000000000000000000000000000000..4ff96f1fa049dc44be39aa3cff656645a28db620 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/GdImageFile.py @@ -0,0 +1,104 @@ +# +# The Python Imaging Library. +# $Id$ +# +# GD file handling +# +# History: +# 1996-04-12 fl Created +# +# Copyright (c) 1997 by Secret Labs AB. +# Copyright (c) 1996 by Fredrik Lundh. +# +# See the README file for information on usage and redistribution. +# + + +""" +.. note:: + This format cannot be automatically recognized, so the + class is not registered for use with :py:func:`PIL.Image.open()`. To open a + gd file, use the :py:func:`PIL.GdImageFile.open()` function instead. + +.. warning:: + THE GD FORMAT IS NOT DESIGNED FOR DATA INTERCHANGE. This + implementation is provided for convenience and demonstrational + purposes only. +""" + +from __future__ import annotations + +from typing import IO + +from . import Image, ImageFile, ImagePalette, UnidentifiedImageError +from ._binary import i16be as i16 +from ._binary import i32be as i32 +from ._typing import StrOrBytesPath + + +class GdImageFile(ImageFile.ImageFile): + """ + Image plugin for the GD uncompressed format. Note that this format + is not supported by the standard :py:func:`PIL.Image.open()` function. To use + this plugin, you have to import the :py:mod:`PIL.GdImageFile` module and + use the :py:func:`PIL.GdImageFile.open()` function. + """ + + format = "GD" + format_description = "GD uncompressed images" + + def _open(self) -> None: + # Header + assert self.fp is not None + + s = self.fp.read(1037) + + if i16(s) not in [65534, 65535]: + msg = "Not a valid GD 2.x .gd file" + raise SyntaxError(msg) + + self._mode = "P" + self._size = i16(s, 2), i16(s, 4) + Image._decompression_bomb_check(self.size) + + true_color = s[6] + true_color_offset = 2 if true_color else 0 + + # transparency index + tindex = i32(s, 7 + true_color_offset) + if tindex < 256: + self.info["transparency"] = tindex + + self.palette = ImagePalette.raw( + "RGBX", s[7 + true_color_offset + 6 : 7 + true_color_offset + 6 + 256 * 4] + ) + + self.tile = [ + ImageFile._Tile( + "raw", + (0, 0) + self.size, + 7 + true_color_offset + 6 + 256 * 4, + "L", + ) + ] + + +def open(fp: StrOrBytesPath | IO[bytes], mode: str = "r") -> GdImageFile: + """ + Load texture from a GD image file. + + :param fp: GD file name, or an opened file handle. + :param mode: Optional mode. In this version, if the mode argument + is given, it must be "r". + :returns: An image instance. + :raises OSError: If the image could not be read. + """ + if mode != "r": + msg = "bad mode" + raise ValueError(msg) + + try: + return GdImageFile(fp) + except SyntaxError as e: + msg = "cannot identify this image file" + raise UnidentifiedImageError(msg) from e diff --git a/.venv/lib/python3.11/site-packages/PIL/GifImagePlugin.py b/.venv/lib/python3.11/site-packages/PIL/GifImagePlugin.py new file mode 100644 index 0000000000000000000000000000000000000000..b8db5d8328407bdc68013fed062f37808560db53 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/GifImagePlugin.py @@ -0,0 +1,1223 @@ +# +# The Python Imaging Library. +# $Id$ +# +# GIF file handling +# +# History: +# 1995-09-01 fl Created +# 1996-12-14 fl Added interlace support +# 1996-12-30 fl Added animation support +# 1997-01-05 fl Added write support, fixed local colour map bug +# 1997-02-23 fl Make sure to load raster data in getdata() +# 1997-07-05 fl Support external decoder (0.4) +# 1998-07-09 fl Handle all modes when saving (0.5) +# 1998-07-15 fl Renamed offset attribute to avoid name clash +# 2001-04-16 fl Added rewind support (seek to frame 0) (0.6) +# 2001-04-17 fl Added palette optimization (0.7) +# 2002-06-06 fl Added transparency support for save (0.8) +# 2004-02-24 fl Disable interlacing for small images +# +# Copyright (c) 1997-2004 by Secret Labs AB +# Copyright (c) 1995-2004 by Fredrik Lundh +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import itertools +import math +import os +import subprocess +from enum import IntEnum +from functools import cached_property +from typing import Any, NamedTuple, cast + +from . import ( + Image, + ImageChops, + ImageFile, + ImageMath, + ImageOps, + ImagePalette, + ImageSequence, +) +from ._binary import i16le as i16 +from ._binary import o8 +from ._binary import o16le as o16 +from ._util import DeferredError + +TYPE_CHECKING = False +if TYPE_CHECKING: + from typing import IO, Literal + + from . import _imaging + from ._typing import Buffer + + +class LoadingStrategy(IntEnum): + """.. versionadded:: 9.1.0""" + + RGB_AFTER_FIRST = 0 + RGB_AFTER_DIFFERENT_PALETTE_ONLY = 1 + RGB_ALWAYS = 2 + + +#: .. versionadded:: 9.1.0 +LOADING_STRATEGY = LoadingStrategy.RGB_AFTER_FIRST + +# -------------------------------------------------------------------- +# Identify/read GIF files + + +def _accept(prefix: bytes) -> bool: + return prefix.startswith((b"GIF87a", b"GIF89a")) + + +## +# Image plugin for GIF images. This plugin supports both GIF87 and +# GIF89 images. + + +class GifImageFile(ImageFile.ImageFile): + format = "GIF" + format_description = "Compuserve GIF" + _close_exclusive_fp_after_loading = False + + global_palette = None + + def data(self) -> bytes | None: + assert self.fp is not None + s = self.fp.read(1) + if s and s[0]: + return self.fp.read(s[0]) + return None + + def _is_palette_needed(self, p: bytes) -> bool: + for i in range(0, len(p), 3): + if not (i // 3 == p[i] == p[i + 1] == p[i + 2]): + return True + return False + + def _open(self) -> None: + # Screen + assert self.fp is not None + s = self.fp.read(13) + if not _accept(s): + msg = "not a GIF file" + raise SyntaxError(msg) + + self.info["version"] = s[:6] + self._size = i16(s, 6), i16(s, 8) + flags = s[10] + bits = (flags & 7) + 1 + + if flags & 128: + # get global palette + self.info["background"] = s[11] + # check if palette contains colour indices + p = self.fp.read(3 << bits) + if self._is_palette_needed(p): + palette = ImagePalette.raw("RGB", p) + self.global_palette = self.palette = palette + + self._fp = self.fp # FIXME: hack + self.__rewind = self.fp.tell() + self._n_frames: int | None = None + self._seek(0) # get ready to read first frame + + @property + def n_frames(self) -> int: + if self._n_frames is None: + current = self.tell() + try: + while True: + self._seek(self.tell() + 1, False) + except EOFError: + self._n_frames = self.tell() + 1 + self.seek(current) + return self._n_frames + + @cached_property + def is_animated(self) -> bool: + if self._n_frames is not None: + return self._n_frames != 1 + + current = self.tell() + if current: + return True + + try: + self._seek(1, False) + is_animated = True + except EOFError: + is_animated = False + + self.seek(current) + return is_animated + + def seek(self, frame: int) -> None: + if not self._seek_check(frame): + return + if frame < self.__frame: + self._im = None + self._seek(0) + + last_frame = self.__frame + try: + for f in range(self.__frame + 1, frame + 1): + self._seek(f) + except EOFError as e: + self.seek(last_frame) + msg = "no more images in GIF file" + raise EOFError(msg) from e + + def _seek(self, frame: int, update_image: bool = True) -> None: + if isinstance(self._fp, DeferredError): + raise self._fp.ex + if frame == 0: + # rewind + self.__offset = 0 + self.dispose: _imaging.ImagingCore | None = None + self.__frame = -1 + self._fp.seek(self.__rewind) + self.disposal_method = 0 + if "comment" in self.info: + del self.info["comment"] + else: + # ensure that the previous frame was loaded + if self.tile and update_image: + self.load() + + if frame != self.__frame + 1: + msg = f"cannot seek to frame {frame}" + raise ValueError(msg) + + self.fp = self._fp + if self.__offset: + # backup to last frame + self.fp.seek(self.__offset) + while self.data(): + pass + self.__offset = 0 + + s = self.fp.read(1) + if not s or s == b";": + msg = "no more images in GIF file" + raise EOFError(msg) + + palette: ImagePalette.ImagePalette | Literal[False] | None = None + + info: dict[str, Any] = {} + frame_transparency = None + interlace = None + frame_dispose_extent = None + while True: + if not s: + s = self.fp.read(1) + if not s or s == b";": + break + + elif s == b"!": + # + # extensions + # + s = self.fp.read(1) + block = self.data() + if s[0] == 249 and block is not None: + # + # graphic control extension + # + flags = block[0] + if flags & 1: + frame_transparency = block[3] + info["duration"] = i16(block, 1) * 10 + + # disposal method - find the value of bits 4 - 6 + dispose_bits = 0b00011100 & flags + dispose_bits = dispose_bits >> 2 + if dispose_bits: + # only set the dispose if it is not + # unspecified. I'm not sure if this is + # correct, but it seems to prevent the last + # frame from looking odd for some animations + self.disposal_method = dispose_bits + elif s[0] == 254: + # + # comment extension + # + comment = b"" + + # Read this comment block + while block: + comment += block + block = self.data() + + if "comment" in info: + # If multiple comment blocks in frame, separate with \n + info["comment"] += b"\n" + comment + else: + info["comment"] = comment + s = b"" + continue + elif s[0] == 255 and frame == 0 and block is not None: + # + # application extension + # + info["extension"] = block, self.fp.tell() + if block.startswith(b"NETSCAPE2.0"): + block = self.data() + if block and len(block) >= 3 and block[0] == 1: + self.info["loop"] = i16(block, 1) + while self.data(): + pass + + elif s == b",": + # + # local image + # + s = self.fp.read(9) + + # extent + x0, y0 = i16(s, 0), i16(s, 2) + x1, y1 = x0 + i16(s, 4), y0 + i16(s, 6) + if (x1 > self.size[0] or y1 > self.size[1]) and update_image: + self._size = max(x1, self.size[0]), max(y1, self.size[1]) + Image._decompression_bomb_check(self._size) + frame_dispose_extent = x0, y0, x1, y1 + flags = s[8] + + interlace = (flags & 64) != 0 + + if flags & 128: + bits = (flags & 7) + 1 + p = self.fp.read(3 << bits) + if self._is_palette_needed(p): + palette = ImagePalette.raw("RGB", p) + else: + palette = False + + # image data + bits = self.fp.read(1)[0] + self.__offset = self.fp.tell() + break + s = b"" + + if interlace is None: + msg = "image not found in GIF frame" + raise EOFError(msg) + + self.__frame = frame + if not update_image: + return + + self.tile = [] + + if self.dispose: + self.im.paste(self.dispose, self.dispose_extent) + + self._frame_palette = palette if palette is not None else self.global_palette + self._frame_transparency = frame_transparency + if frame == 0: + if self._frame_palette: + if LOADING_STRATEGY == LoadingStrategy.RGB_ALWAYS: + self._mode = "RGBA" if frame_transparency is not None else "RGB" + else: + self._mode = "P" + else: + self._mode = "L" + + if palette: + self.palette = palette + elif self.global_palette: + from copy import copy + + self.palette = copy(self.global_palette) + else: + self.palette = None + else: + if self.mode == "P": + if ( + LOADING_STRATEGY != LoadingStrategy.RGB_AFTER_DIFFERENT_PALETTE_ONLY + or palette + ): + if "transparency" in self.info: + self.im.putpalettealpha(self.info["transparency"], 0) + self.im = self.im.convert("RGBA", Image.Dither.FLOYDSTEINBERG) + self._mode = "RGBA" + del self.info["transparency"] + else: + self._mode = "RGB" + self.im = self.im.convert("RGB", Image.Dither.FLOYDSTEINBERG) + + def _rgb(color: int) -> tuple[int, int, int]: + if self._frame_palette: + if color * 3 + 3 > len(self._frame_palette.palette): + color = 0 + return cast( + tuple[int, int, int], + tuple(self._frame_palette.palette[color * 3 : color * 3 + 3]), + ) + else: + return (color, color, color) + + self.dispose = None + self.dispose_extent: tuple[int, int, int, int] | None = frame_dispose_extent + if self.dispose_extent and self.disposal_method >= 2: + try: + if self.disposal_method == 2: + # replace with background colour + + # only dispose the extent in this frame + x0, y0, x1, y1 = self.dispose_extent + dispose_size = (x1 - x0, y1 - y0) + + Image._decompression_bomb_check(dispose_size) + + # by convention, attempt to use transparency first + dispose_mode = "P" + color = self.info.get("transparency", frame_transparency) + if color is not None: + if self.mode in ("RGB", "RGBA"): + dispose_mode = "RGBA" + color = _rgb(color) + (0,) + else: + color = self.info.get("background", 0) + if self.mode in ("RGB", "RGBA"): + dispose_mode = "RGB" + color = _rgb(color) + self.dispose = Image.core.fill(dispose_mode, dispose_size, color) + else: + # replace with previous contents + if self._im is not None: + # only dispose the extent in this frame + self.dispose = self._crop(self.im, self.dispose_extent) + elif frame_transparency is not None: + x0, y0, x1, y1 = self.dispose_extent + dispose_size = (x1 - x0, y1 - y0) + + Image._decompression_bomb_check(dispose_size) + dispose_mode = "P" + color = frame_transparency + if self.mode in ("RGB", "RGBA"): + dispose_mode = "RGBA" + color = _rgb(frame_transparency) + (0,) + self.dispose = Image.core.fill( + dispose_mode, dispose_size, color + ) + except AttributeError: + pass + + if interlace is not None: + transparency = -1 + if frame_transparency is not None: + if frame == 0: + if LOADING_STRATEGY != LoadingStrategy.RGB_ALWAYS: + self.info["transparency"] = frame_transparency + elif self.mode not in ("RGB", "RGBA"): + transparency = frame_transparency + self.tile = [ + ImageFile._Tile( + "gif", + (x0, y0, x1, y1), + self.__offset, + (bits, interlace, transparency), + ) + ] + + if info.get("comment"): + self.info["comment"] = info["comment"] + for k in ["duration", "extension"]: + if k in info: + self.info[k] = info[k] + elif k in self.info: + del self.info[k] + + def load_prepare(self) -> None: + temp_mode = "P" if self._frame_palette else "L" + self._prev_im = None + if self.__frame == 0: + if self._frame_transparency is not None: + self.im = Image.core.fill( + temp_mode, self.size, self._frame_transparency + ) + elif self.mode in ("RGB", "RGBA"): + self._prev_im = self.im + if self._frame_palette: + self.im = Image.core.fill("P", self.size, self._frame_transparency or 0) + self.im.putpalette("RGB", *self._frame_palette.getdata()) + else: + self._im = None + if not self._prev_im and self._im is not None and self.size != self.im.size: + expanded_im = Image.core.fill(self.im.mode, self.size) + if self._frame_palette: + expanded_im.putpalette("RGB", *self._frame_palette.getdata()) + expanded_im.paste(self.im, (0, 0) + self.im.size) + + self.im = expanded_im + self._mode = temp_mode + self._frame_palette = None + + super().load_prepare() + + def load_end(self) -> None: + if self.__frame == 0: + if self.mode == "P" and LOADING_STRATEGY == LoadingStrategy.RGB_ALWAYS: + if self._frame_transparency is not None: + self.im.putpalettealpha(self._frame_transparency, 0) + self._mode = "RGBA" + else: + self._mode = "RGB" + self.im = self.im.convert(self.mode, Image.Dither.FLOYDSTEINBERG) + return + if not self._prev_im: + return + if self.size != self._prev_im.size: + if self._frame_transparency is not None: + expanded_im = Image.core.fill("RGBA", self.size) + else: + expanded_im = Image.core.fill("P", self.size) + expanded_im.putpalette("RGB", "RGB", self.im.getpalette()) + expanded_im = expanded_im.convert("RGB") + expanded_im.paste(self._prev_im, (0, 0) + self._prev_im.size) + + self._prev_im = expanded_im + assert self._prev_im is not None + if self._frame_transparency is not None: + if self.mode == "L": + frame_im = self.im.convert_transparent("LA", self._frame_transparency) + else: + self.im.putpalettealpha(self._frame_transparency, 0) + frame_im = self.im.convert("RGBA") + else: + frame_im = self.im.convert("RGB") + + assert self.dispose_extent is not None + frame_im = self._crop(frame_im, self.dispose_extent) + + self.im = self._prev_im + self._mode = self.im.mode + if frame_im.mode in ("LA", "RGBA"): + self.im.paste(frame_im, self.dispose_extent, frame_im) + else: + self.im.paste(frame_im, self.dispose_extent) + + def tell(self) -> int: + return self.__frame + + +# -------------------------------------------------------------------- +# Write GIF files + + +RAWMODE = {"1": "L", "L": "L", "P": "P"} + + +def _normalize_mode(im: Image.Image) -> Image.Image: + """ + Takes an image (or frame), returns an image in a mode that is appropriate + for saving in a Gif. + + It may return the original image, or it may return an image converted to + palette or 'L' mode. + + :param im: Image object + :returns: Image object + """ + if im.mode in RAWMODE: + im.load() + return im + if Image.getmodebase(im.mode) == "RGB": + im = im.convert("P", palette=Image.Palette.ADAPTIVE) + assert im.palette is not None + if im.palette.mode == "RGBA": + for rgba in im.palette.colors: + if rgba[3] == 0: + im.info["transparency"] = im.palette.colors[rgba] + break + return im + return im.convert("L") + + +_Palette = bytes | bytearray | list[int] | ImagePalette.ImagePalette + + +def _normalize_palette( + im: Image.Image, palette: _Palette | None, info: dict[str, Any] +) -> Image.Image: + """ + Normalizes the palette for image. + - Sets the palette to the incoming palette, if provided. + - Ensures that there's a palette for L mode images + - Optimizes the palette if necessary/desired. + + :param im: Image object + :param palette: bytes object containing the source palette, or .... + :param info: encoderinfo + :returns: Image object + """ + source_palette = None + if palette: + # a bytes palette + if isinstance(palette, (bytes, bytearray, list)): + source_palette = bytearray(palette[:768]) + if isinstance(palette, ImagePalette.ImagePalette): + source_palette = bytearray(palette.palette) + + if im.mode == "P": + if not source_palette: + im_palette = im.getpalette(None) + assert im_palette is not None + source_palette = bytearray(im_palette) + else: # L-mode + if not source_palette: + source_palette = bytearray(i // 3 for i in range(768)) + im.palette = ImagePalette.ImagePalette("RGB", palette=source_palette) + assert source_palette is not None + + if palette: + used_palette_colors: list[int | None] = [] + assert im.palette is not None + for i in range(0, len(source_palette), 3): + source_color = tuple(source_palette[i : i + 3]) + index = im.palette.colors.get(source_color) + if index in used_palette_colors: + index = None + used_palette_colors.append(index) + for i, index in enumerate(used_palette_colors): + if index is None: + for j in range(len(used_palette_colors)): + if j not in used_palette_colors: + used_palette_colors[i] = j + break + dest_map: list[int] = [] + for index in used_palette_colors: + assert index is not None + dest_map.append(index) + im = im.remap_palette(dest_map) + else: + optimized_palette_colors = _get_optimize(im, info) + if optimized_palette_colors is not None: + im = im.remap_palette(optimized_palette_colors, source_palette) + if "transparency" in info: + try: + info["transparency"] = optimized_palette_colors.index( + info["transparency"] + ) + except ValueError: + del info["transparency"] + return im + + assert im.palette is not None + im.palette.palette = source_palette + return im + + +def _write_single_frame( + im: Image.Image, + fp: IO[bytes], + palette: _Palette | None, +) -> None: + im_out = _normalize_mode(im) + for k, v in im_out.info.items(): + if isinstance(k, str): + im.encoderinfo.setdefault(k, v) + im_out = _normalize_palette(im_out, palette, im.encoderinfo) + + for s in _get_global_header(im_out, im.encoderinfo): + fp.write(s) + + # local image header + flags = 0 + if get_interlace(im): + flags = flags | 64 + _write_local_header(fp, im, (0, 0), flags) + + im_out.encoderconfig = (8, get_interlace(im)) + ImageFile._save( + im_out, fp, [ImageFile._Tile("gif", (0, 0) + im.size, 0, RAWMODE[im_out.mode])] + ) + + fp.write(b"\0") # end of image data + + +def _getbbox( + base_im: Image.Image, im_frame: Image.Image +) -> tuple[Image.Image, tuple[int, int, int, int] | None]: + palette_bytes = [ + bytes(im.palette.palette) if im.palette else b"" for im in (base_im, im_frame) + ] + if palette_bytes[0] != palette_bytes[1]: + im_frame = im_frame.convert("RGBA") + base_im = base_im.convert("RGBA") + delta = ImageChops.subtract_modulo(im_frame, base_im) + return delta, delta.getbbox(alpha_only=False) + + +class _Frame(NamedTuple): + im: Image.Image + bbox: tuple[int, int, int, int] | None + encoderinfo: dict[str, Any] + + +def _write_multiple_frames( + im: Image.Image, fp: IO[bytes], palette: _Palette | None +) -> bool: + duration = im.encoderinfo.get("duration") + disposal = im.encoderinfo.get("disposal", im.info.get("disposal")) + + im_frames: list[_Frame] = [] + previous_im: Image.Image | None = None + frame_count = 0 + background_im = None + for imSequence in itertools.chain([im], im.encoderinfo.get("append_images", [])): + for im_frame in ImageSequence.Iterator(imSequence): + # a copy is required here since seek can still mutate the image + im_frame = _normalize_mode(im_frame.copy()) + if frame_count == 0: + for k, v in im_frame.info.items(): + if k == "transparency": + continue + if isinstance(k, str): + im.encoderinfo.setdefault(k, v) + + encoderinfo = im.encoderinfo.copy() + if "transparency" in im_frame.info: + encoderinfo.setdefault("transparency", im_frame.info["transparency"]) + im_frame = _normalize_palette(im_frame, palette, encoderinfo) + if isinstance(duration, (list, tuple)): + encoderinfo["duration"] = duration[frame_count] + elif duration is None and "duration" in im_frame.info: + encoderinfo["duration"] = im_frame.info["duration"] + if isinstance(disposal, (list, tuple)): + encoderinfo["disposal"] = disposal[frame_count] + frame_count += 1 + + diff_frame = None + if im_frames and previous_im: + # delta frame + delta, bbox = _getbbox(previous_im, im_frame) + if not bbox: + # This frame is identical to the previous frame + if encoderinfo.get("duration"): + im_frames[-1].encoderinfo["duration"] += encoderinfo["duration"] + continue + if im_frames[-1].encoderinfo.get("disposal") == 2: + # To appear correctly in viewers using a convention, + # only consider transparency, and not background color + color = im.encoderinfo.get( + "transparency", im.info.get("transparency") + ) + if color is not None: + if background_im is None: + background = _get_background(im_frame, color) + background_im = Image.new("P", im_frame.size, background) + first_palette = im_frames[0].im.palette + assert first_palette is not None + background_im.putpalette(first_palette, first_palette.mode) + bbox = _getbbox(background_im, im_frame)[1] + else: + bbox = (0, 0) + im_frame.size + elif encoderinfo.get("optimize") and im_frame.mode != "1": + if "transparency" not in encoderinfo: + assert im_frame.palette is not None + try: + encoderinfo["transparency"] = ( + im_frame.palette._new_color_index(im_frame) + ) + except ValueError: + pass + if "transparency" in encoderinfo: + # When the delta is zero, fill the image with transparency + diff_frame = im_frame.copy() + fill = Image.new("P", delta.size, encoderinfo["transparency"]) + if delta.mode == "RGBA": + r, g, b, a = delta.split() + mask = ImageMath.lambda_eval( + lambda args: args["convert"]( + args["max"]( + args["max"]( + args["max"](args["r"], args["g"]), args["b"] + ), + args["a"], + ) + * 255, + "1", + ), + r=r, + g=g, + b=b, + a=a, + ) + else: + if delta.mode == "P": + # Convert to L without considering palette + delta_l = Image.new("L", delta.size) + delta_l.putdata(delta.get_flattened_data()) + delta = delta_l + mask = ImageMath.lambda_eval( + lambda args: args["convert"](args["im"] * 255, "1"), + im=delta, + ) + diff_frame.paste(fill, mask=ImageOps.invert(mask)) + else: + bbox = None + previous_im = im_frame + im_frames.append(_Frame(diff_frame or im_frame, bbox, encoderinfo)) + + if len(im_frames) == 1: + if "duration" in im.encoderinfo: + # Since multiple frames will not be written, use the combined duration + im.encoderinfo["duration"] = im_frames[0].encoderinfo["duration"] + return False + + for frame_data in im_frames: + im_frame = frame_data.im + if not frame_data.bbox: + # global header + for s in _get_global_header(im_frame, frame_data.encoderinfo): + fp.write(s) + offset = (0, 0) + else: + # compress difference + if not palette: + frame_data.encoderinfo["include_color_table"] = True + + if frame_data.bbox != (0, 0) + im_frame.size: + im_frame = im_frame.crop(frame_data.bbox) + offset = frame_data.bbox[:2] + _write_frame_data(fp, im_frame, offset, frame_data.encoderinfo) + return True + + +def _save_all(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + _save(im, fp, filename, save_all=True) + + +def _save( + im: Image.Image, fp: IO[bytes], filename: str | bytes, save_all: bool = False +) -> None: + # header + if "palette" in im.encoderinfo or "palette" in im.info: + palette = im.encoderinfo.get("palette", im.info.get("palette")) + else: + palette = None + im.encoderinfo.setdefault("optimize", True) + + if not save_all or not _write_multiple_frames(im, fp, palette): + _write_single_frame(im, fp, palette) + + fp.write(b";") # end of file + + if hasattr(fp, "flush"): + fp.flush() + + +def get_interlace(im: Image.Image) -> int: + interlace = im.encoderinfo.get("interlace", 1) + + # workaround for @PIL153 + if min(im.size) < 16: + interlace = 0 + + return interlace + + +def _write_local_header( + fp: IO[bytes], im: Image.Image, offset: tuple[int, int], flags: int +) -> None: + try: + transparency = im.encoderinfo["transparency"] + except KeyError: + transparency = None + + if "duration" in im.encoderinfo: + duration = int(im.encoderinfo["duration"] / 10) + else: + duration = 0 + + disposal = int(im.encoderinfo.get("disposal", 0)) + + if transparency is not None or duration != 0 or disposal: + packed_flag = 1 if transparency is not None else 0 + packed_flag |= disposal << 2 + + fp.write( + b"!" + + o8(249) # extension intro + + o8(4) # length + + o8(packed_flag) # packed fields + + o16(duration) # duration + + o8(transparency or 0) # transparency index + + o8(0) + ) + + include_color_table = im.encoderinfo.get("include_color_table") + if include_color_table: + palette_bytes = _get_palette_bytes(im) + color_table_size = _get_color_table_size(palette_bytes) + if color_table_size: + flags = flags | 128 # local color table flag + flags = flags | color_table_size + + fp.write( + b"," + + o16(offset[0]) # offset + + o16(offset[1]) + + o16(im.size[0]) # size + + o16(im.size[1]) + + o8(flags) # flags + ) + if include_color_table and color_table_size: + fp.write(_get_header_palette(palette_bytes)) + fp.write(o8(8)) # bits + + +def _save_netpbm(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + # Unused by default. + # To use, uncomment the register_save call at the end of the file. + # + # If you need real GIF compression and/or RGB quantization, you + # can use the external NETPBM/PBMPLUS utilities. See comments + # below for information on how to enable this. + tempfile = im._dump() + + try: + with open(filename, "wb") as f: + if im.mode != "RGB": + subprocess.check_call( + ["ppmtogif", tempfile], stdout=f, stderr=subprocess.DEVNULL + ) + else: + # Pipe ppmquant output into ppmtogif + # "ppmquant 256 %s | ppmtogif > %s" % (tempfile, filename) + quant_cmd = ["ppmquant", "256", tempfile] + togif_cmd = ["ppmtogif"] + quant_proc = subprocess.Popen( + quant_cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL + ) + togif_proc = subprocess.Popen( + togif_cmd, + stdin=quant_proc.stdout, + stdout=f, + stderr=subprocess.DEVNULL, + ) + + # Allow ppmquant to receive SIGPIPE if ppmtogif exits + assert quant_proc.stdout is not None + quant_proc.stdout.close() + + retcode = quant_proc.wait() + if retcode: + raise subprocess.CalledProcessError(retcode, quant_cmd) + + retcode = togif_proc.wait() + if retcode: + raise subprocess.CalledProcessError(retcode, togif_cmd) + finally: + try: + os.unlink(tempfile) + except OSError: + pass + + +# Force optimization so that we can test performance against +# cases where it took lots of memory and time previously. +_FORCE_OPTIMIZE = False + + +def _get_optimize(im: Image.Image, info: dict[str, Any]) -> list[int] | None: + """ + Palette optimization is a potentially expensive operation. + + This function determines if the palette should be optimized using + some heuristics, then returns the list of palette entries in use. + + :param im: Image object + :param info: encoderinfo + :returns: list of indexes of palette entries in use, or None + """ + if ( + im.mode in ("P", "L") + and info + and info.get("optimize") + and im.width != 0 + and im.height != 0 + ): + # Potentially expensive operation. + + # The palette saves 3 bytes per color not used, but palette + # lengths are restricted to 3*(2**N) bytes. Max saving would + # be 768 -> 6 bytes if we went all the way down to 2 colors. + # * If we're over 128 colors, we can't save any space. + # * If there aren't any holes, it's not worth collapsing. + # * If we have a 'large' image, the palette is in the noise. + + # create the new palette if not every color is used + optimise = _FORCE_OPTIMIZE or im.mode == "L" + if optimise or im.width * im.height < 512 * 512: + # check which colors are used + used_palette_colors = [] + for i, count in enumerate(im.histogram()): + if count: + used_palette_colors.append(i) + + if optimise or max(used_palette_colors) >= len(used_palette_colors): + return used_palette_colors + + assert im.palette is not None + num_palette_colors = len(im.palette.palette) // Image.getmodebands( + im.palette.mode + ) + current_palette_size = 1 << (num_palette_colors - 1).bit_length() + if ( + # check that the palette would become smaller when saved + len(used_palette_colors) <= current_palette_size // 2 + # check that the palette is not already the smallest possible size + and current_palette_size > 2 + ): + return used_palette_colors + return None + + +def _get_color_table_size(palette_bytes: bytes) -> int: + # calculate the palette size for the header + if not palette_bytes: + return 0 + elif len(palette_bytes) < 9: + return 1 + else: + return math.ceil(math.log(len(palette_bytes) // 3, 2)) - 1 + + +def _get_header_palette(palette_bytes: bytes) -> bytes: + """ + Returns the palette, null padded to the next power of 2 (*3) bytes + suitable for direct inclusion in the GIF header + + :param palette_bytes: Unpadded palette bytes, in RGBRGB form + :returns: Null padded palette + """ + color_table_size = _get_color_table_size(palette_bytes) + + # add the missing amount of bytes + # the palette has to be 2< 0: + palette_bytes += o8(0) * 3 * actual_target_size_diff + return palette_bytes + + +def _get_palette_bytes(im: Image.Image) -> bytes: + """ + Gets the palette for inclusion in the gif header + + :param im: Image object + :returns: Bytes, len<=768 suitable for inclusion in gif header + """ + if not im.palette: + return b"" + + palette = bytes(im.palette.palette) + if im.palette.mode == "RGBA": + palette = b"".join(palette[i * 4 : i * 4 + 3] for i in range(len(palette) // 3)) + return palette + + +def _get_background( + im: Image.Image, + info_background: int | tuple[int, int, int] | tuple[int, int, int, int] | None, +) -> int: + background = 0 + if info_background: + if isinstance(info_background, tuple): + # WebPImagePlugin stores an RGBA value in info["background"] + # So it must be converted to the same format as GifImagePlugin's + # info["background"] - a global color table index + assert im.palette is not None + try: + background = im.palette.getcolor(info_background, im) + except ValueError as e: + if str(e) not in ( + # If all 256 colors are in use, + # then there is no need for the background color + "cannot allocate more than 256 colors", + # Ignore non-opaque WebP background + "cannot add non-opaque RGBA color to RGB palette", + ): + raise + else: + background = info_background + return background + + +def _get_global_header(im: Image.Image, info: dict[str, Any]) -> list[bytes]: + """Return a list of strings representing a GIF header""" + + # Header Block + # https://www.matthewflickinger.com/lab/whatsinagif/bits_and_bytes.asp + + version = b"87a" + if im.info.get("version") == b"89a" or ( + info + and ( + "transparency" in info + or info.get("loop") is not None + or info.get("duration") + or info.get("comment") + ) + ): + version = b"89a" + + background = _get_background(im, info.get("background")) + + palette_bytes = _get_palette_bytes(im) + color_table_size = _get_color_table_size(palette_bytes) + + header = [ + b"GIF" # signature + + version # version + + o16(im.size[0]) # canvas width + + o16(im.size[1]), # canvas height + # Logical Screen Descriptor + # size of global color table + global color table flag + o8(color_table_size + 128), # packed fields + # background + reserved/aspect + o8(background) + o8(0), + # Global Color Table + _get_header_palette(palette_bytes), + ] + if info.get("loop") is not None: + header.append( + b"!" + + o8(255) # extension intro + + o8(11) + + b"NETSCAPE2.0" + + o8(3) + + o8(1) + + o16(info["loop"]) # number of loops + + o8(0) + ) + if info.get("comment"): + comment_block = b"!" + o8(254) # extension intro + + comment = info["comment"] + if isinstance(comment, str): + comment = comment.encode() + for i in range(0, len(comment), 255): + subblock = comment[i : i + 255] + comment_block += o8(len(subblock)) + subblock + + comment_block += o8(0) + header.append(comment_block) + return header + + +def _write_frame_data( + fp: IO[bytes], + im_frame: Image.Image, + offset: tuple[int, int], + params: dict[str, Any], +) -> None: + try: + im_frame.encoderinfo = params + + # local image header + _write_local_header(fp, im_frame, offset, 0) + + ImageFile._save( + im_frame, + fp, + [ImageFile._Tile("gif", (0, 0) + im_frame.size, 0, RAWMODE[im_frame.mode])], + ) + + fp.write(b"\0") # end of image data + finally: + del im_frame.encoderinfo + + +# -------------------------------------------------------------------- +# Legacy GIF utilities + + +def getheader( + im: Image.Image, palette: _Palette | None = None, info: dict[str, Any] | None = None +) -> tuple[list[bytes], list[int] | None]: + """ + Legacy Method to get Gif data from image. + + Warning:: May modify image data. + + :param im: Image object + :param palette: bytes object containing the source palette, or .... + :param info: encoderinfo + :returns: tuple of(list of header items, optimized palette) + + """ + if info is None: + info = {} + + used_palette_colors = _get_optimize(im, info) + + if "background" not in info and "background" in im.info: + info["background"] = im.info["background"] + + im_mod = _normalize_palette(im, palette, info) + im.palette = im_mod.palette + im.im = im_mod.im + header = _get_global_header(im, info) + + return header, used_palette_colors + + +def getdata( + im: Image.Image, offset: tuple[int, int] = (0, 0), **params: Any +) -> list[bytes]: + """ + Legacy Method + + Return a list of strings representing this image. + The first string is a local image header, the rest contains + encoded image data. + + To specify duration, add the time in milliseconds, + e.g. ``getdata(im_frame, duration=1000)`` + + :param im: Image object + :param offset: Tuple of (x, y) pixels. Defaults to (0, 0) + :param \\**params: e.g. duration or other encoder info parameters + :returns: List of bytes containing GIF encoded frame data + + """ + from io import BytesIO + + class Collector(BytesIO): + data = [] + + def write(self, data: Buffer) -> int: + self.data.append(data) + return len(data) + + im.load() # make sure raster data is available + + fp = Collector() + + _write_frame_data(fp, im, offset, params) + + return fp.data + + +# -------------------------------------------------------------------- +# Registry + +Image.register_open(GifImageFile.format, GifImageFile, _accept) +Image.register_save(GifImageFile.format, _save) +Image.register_save_all(GifImageFile.format, _save_all) +Image.register_extension(GifImageFile.format, ".gif") +Image.register_mime(GifImageFile.format, "image/gif") + +# +# Uncomment the following line if you wish to use NETPBM/PBMPLUS +# instead of the built-in "uncompressed" GIF encoder + +# Image.register_save(GifImageFile.format, _save_netpbm) diff --git a/.venv/lib/python3.11/site-packages/PIL/GimpGradientFile.py b/.venv/lib/python3.11/site-packages/PIL/GimpGradientFile.py new file mode 100644 index 0000000000000000000000000000000000000000..fb9587218822683ed2e962dbbdb3786b5920df8e --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/GimpGradientFile.py @@ -0,0 +1,154 @@ +# +# Python Imaging Library +# $Id$ +# +# stuff to read (and render) GIMP gradient files +# +# History: +# 97-08-23 fl Created +# +# Copyright (c) Secret Labs AB 1997. +# Copyright (c) Fredrik Lundh 1997. +# +# See the README file for information on usage and redistribution. +# + +""" +Stuff to translate curve segments to palette values (derived from +the corresponding code in GIMP, written by Federico Mena Quintero. +See the GIMP distribution for more information.) +""" + +from __future__ import annotations + +from math import log, pi, sin, sqrt + +from ._binary import o8 + +TYPE_CHECKING = False +if TYPE_CHECKING: + from collections.abc import Callable + from typing import IO + +EPSILON = 1e-10 +"""""" # Enable auto-doc for data member + + +def linear(middle: float, pos: float) -> float: + if pos <= middle: + if middle < EPSILON: + return 0.0 + else: + return 0.5 * pos / middle + else: + pos = pos - middle + middle = 1.0 - middle + if middle < EPSILON: + return 1.0 + else: + return 0.5 + 0.5 * pos / middle + + +def curved(middle: float, pos: float) -> float: + return pos ** (log(0.5) / log(max(middle, EPSILON))) + + +def sine(middle: float, pos: float) -> float: + return (sin((-pi / 2.0) + pi * linear(middle, pos)) + 1.0) / 2.0 + + +def sphere_increasing(middle: float, pos: float) -> float: + return sqrt(1.0 - (linear(middle, pos) - 1.0) ** 2) + + +def sphere_decreasing(middle: float, pos: float) -> float: + return 1.0 - sqrt(1.0 - linear(middle, pos) ** 2) + + +SEGMENTS = [linear, curved, sine, sphere_increasing, sphere_decreasing] +"""""" # Enable auto-doc for data member + + +class GradientFile: + gradient: ( + list[ + tuple[ + float, + float, + float, + list[float], + list[float], + Callable[[float, float], float], + ] + ] + | None + ) = None + + def getpalette(self, entries: int = 256) -> tuple[bytes, str]: + assert self.gradient is not None + palette = [] + + ix = 0 + x0, x1, xm, rgb0, rgb1, segment = self.gradient[ix] + + for i in range(entries): + x = i / (entries - 1) + + while x1 < x: + ix += 1 + x0, x1, xm, rgb0, rgb1, segment = self.gradient[ix] + + w = x1 - x0 + + if w < EPSILON: + scale = segment(0.5, 0.5) + else: + scale = segment((xm - x0) / w, (x - x0) / w) + + # expand to RGBA + r = o8(int(255 * ((rgb1[0] - rgb0[0]) * scale + rgb0[0]) + 0.5)) + g = o8(int(255 * ((rgb1[1] - rgb0[1]) * scale + rgb0[1]) + 0.5)) + b = o8(int(255 * ((rgb1[2] - rgb0[2]) * scale + rgb0[2]) + 0.5)) + a = o8(int(255 * ((rgb1[3] - rgb0[3]) * scale + rgb0[3]) + 0.5)) + + # add to palette + palette.append(r + g + b + a) + + return b"".join(palette), "RGBA" + + +class GimpGradientFile(GradientFile): + """File handler for GIMP's gradient format.""" + + def __init__(self, fp: IO[bytes]) -> None: + if not fp.readline().startswith(b"GIMP Gradient"): + msg = "not a GIMP gradient file" + raise SyntaxError(msg) + + line = fp.readline() + + # GIMP 1.2 gradient files don't contain a name, but GIMP 1.3 files do + if line.startswith(b"Name: "): + line = fp.readline().strip() + + count = int(line) + + self.gradient = [] + + for i in range(count): + s = fp.readline().split() + w = [float(x) for x in s[:11]] + + x0, x1 = w[0], w[2] + xm = w[1] + rgb0 = w[3:7] + rgb1 = w[7:11] + + segment = SEGMENTS[int(s[11])] + cspace = int(s[12]) + + if cspace != 0: + msg = "cannot handle HSV colour space" + raise OSError(msg) + + self.gradient.append((x0, x1, xm, rgb0, rgb1, segment)) diff --git a/.venv/lib/python3.11/site-packages/PIL/GimpPaletteFile.py b/.venv/lib/python3.11/site-packages/PIL/GimpPaletteFile.py new file mode 100644 index 0000000000000000000000000000000000000000..016257d3dd29e83ed8d68f89363965dc39b93811 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/GimpPaletteFile.py @@ -0,0 +1,75 @@ +# +# Python Imaging Library +# $Id$ +# +# stuff to read GIMP palette files +# +# History: +# 1997-08-23 fl Created +# 2004-09-07 fl Support GIMP 2.0 palette files. +# +# Copyright (c) Secret Labs AB 1997-2004. All rights reserved. +# Copyright (c) Fredrik Lundh 1997-2004. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import re +from io import BytesIO + +TYPE_CHECKING = False +if TYPE_CHECKING: + from typing import IO + + +class GimpPaletteFile: + """File handler for GIMP's palette format.""" + + rawmode = "RGB" + + def _read(self, fp: IO[bytes], limit: bool = True) -> None: + if not fp.readline().startswith(b"GIMP Palette"): + msg = "not a GIMP palette file" + raise SyntaxError(msg) + + palette: list[int] = [] + i = 0 + while True: + if limit and i == 256 + 3: + break + + i += 1 + s = fp.readline() + if not s: + break + + # skip fields and comment lines + if re.match(rb"\w+:|#", s): + continue + if limit and len(s) > 100: + msg = "bad palette file" + raise SyntaxError(msg) + + v = s.split(maxsplit=3) + if len(v) < 3: + msg = "bad palette entry" + raise ValueError(msg) + + palette += (int(v[i]) for i in range(3)) + if limit and len(palette) == 768: + break + + self.palette = bytes(palette) + + def __init__(self, fp: IO[bytes]) -> None: + self._read(fp) + + @classmethod + def frombytes(cls, data: bytes) -> GimpPaletteFile: + self = cls.__new__(cls) + self._read(BytesIO(data), False) + return self + + def getpalette(self) -> tuple[bytes, str]: + return self.palette, self.rawmode diff --git a/.venv/lib/python3.11/site-packages/PIL/GribStubImagePlugin.py b/.venv/lib/python3.11/site-packages/PIL/GribStubImagePlugin.py new file mode 100644 index 0000000000000000000000000000000000000000..3784ef2f1345c4175f7a8ef759c9b276d96334ef --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/GribStubImagePlugin.py @@ -0,0 +1,72 @@ +# +# The Python Imaging Library +# $Id$ +# +# GRIB stub adapter +# +# Copyright (c) 1996-2003 by Fredrik Lundh +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import os +from typing import IO + +from . import Image, ImageFile + +_handler = None + + +def register_handler(handler: ImageFile.StubHandler | None) -> None: + """ + Install application-specific GRIB image handler. + + :param handler: Handler object. + """ + global _handler + _handler = handler + + +# -------------------------------------------------------------------- +# Image adapter + + +def _accept(prefix: bytes) -> bool: + return len(prefix) >= 8 and prefix.startswith(b"GRIB") and prefix[7] == 1 + + +class GribStubImageFile(ImageFile.StubImageFile): + format = "GRIB" + format_description = "GRIB" + + def _open(self) -> None: + assert self.fp is not None + if not _accept(self.fp.read(8)): + msg = "Not a GRIB file" + raise SyntaxError(msg) + + self.fp.seek(-8, os.SEEK_CUR) + + # make something up + self._mode = "F" + self._size = 1, 1 + + def _load(self) -> ImageFile.StubHandler | None: + return _handler + + +def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + if _handler is None or not hasattr(_handler, "save"): + msg = "GRIB save handler not installed" + raise OSError(msg) + _handler.save(im, fp, filename) + + +# -------------------------------------------------------------------- +# Registry + +Image.register_open(GribStubImageFile.format, GribStubImageFile, _accept) +Image.register_save(GribStubImageFile.format, _save) + +Image.register_extension(GribStubImageFile.format, ".grib") diff --git a/.venv/lib/python3.11/site-packages/PIL/Hdf5StubImagePlugin.py b/.venv/lib/python3.11/site-packages/PIL/Hdf5StubImagePlugin.py new file mode 100644 index 0000000000000000000000000000000000000000..1a56660f7bd5be7a970fca4678a04f4e19f976e8 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/Hdf5StubImagePlugin.py @@ -0,0 +1,72 @@ +# +# The Python Imaging Library +# $Id$ +# +# HDF5 stub adapter +# +# Copyright (c) 2000-2003 by Fredrik Lundh +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import os +from typing import IO + +from . import Image, ImageFile + +_handler = None + + +def register_handler(handler: ImageFile.StubHandler | None) -> None: + """ + Install application-specific HDF5 image handler. + + :param handler: Handler object. + """ + global _handler + _handler = handler + + +# -------------------------------------------------------------------- +# Image adapter + + +def _accept(prefix: bytes) -> bool: + return prefix.startswith(b"\x89HDF\r\n\x1a\n") + + +class HDF5StubImageFile(ImageFile.StubImageFile): + format = "HDF5" + format_description = "HDF5" + + def _open(self) -> None: + assert self.fp is not None + if not _accept(self.fp.read(8)): + msg = "Not an HDF file" + raise SyntaxError(msg) + + self.fp.seek(-8, os.SEEK_CUR) + + # make something up + self._mode = "F" + self._size = 1, 1 + + def _load(self) -> ImageFile.StubHandler | None: + return _handler + + +def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + if _handler is None or not hasattr(_handler, "save"): + msg = "HDF5 save handler not installed" + raise OSError(msg) + _handler.save(im, fp, filename) + + +# -------------------------------------------------------------------- +# Registry + +Image.register_open(HDF5StubImageFile.format, HDF5StubImageFile, _accept) +Image.register_save(HDF5StubImageFile.format, _save) + +Image.register_extensions(HDF5StubImageFile.format, [".h5", ".hdf"]) diff --git a/.venv/lib/python3.11/site-packages/PIL/IcnsImagePlugin.py b/.venv/lib/python3.11/site-packages/PIL/IcnsImagePlugin.py new file mode 100644 index 0000000000000000000000000000000000000000..cb7a74c2e3bfe09fe46fbcb81fd08d5f3bb3d6a5 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/IcnsImagePlugin.py @@ -0,0 +1,401 @@ +# +# The Python Imaging Library. +# $Id$ +# +# macOS icns file decoder, based on icns.py by Bob Ippolito. +# +# history: +# 2004-10-09 fl Turned into a PIL plugin; removed 2.3 dependencies. +# 2020-04-04 Allow saving on all operating systems. +# +# Copyright (c) 2004 by Bob Ippolito. +# Copyright (c) 2004 by Secret Labs. +# Copyright (c) 2004 by Fredrik Lundh. +# Copyright (c) 2014 by Alastair Houghton. +# Copyright (c) 2020 by Pan Jing. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import io +import os +import struct +import sys +from typing import IO + +from . import Image, ImageFile, PngImagePlugin, features + +enable_jpeg2k = features.check_codec("jpg_2000") +if enable_jpeg2k: + from . import Jpeg2KImagePlugin + +MAGIC = b"icns" +HEADERSIZE = 8 + + +def nextheader(fobj: IO[bytes]) -> tuple[bytes, int]: + return struct.unpack(">4sI", fobj.read(HEADERSIZE)) + + +def read_32t( + fobj: IO[bytes], start_length: tuple[int, int], size: tuple[int, int, int] +) -> dict[str, Image.Image]: + # The 128x128 icon seems to have an extra header for some reason. + start, length = start_length + fobj.seek(start) + sig = fobj.read(4) + if sig != b"\x00\x00\x00\x00": + msg = "Unknown signature, expecting 0x00000000" + raise SyntaxError(msg) + return read_32(fobj, (start + 4, length - 4), size) + + +def read_32( + fobj: IO[bytes], start_length: tuple[int, int], size: tuple[int, int, int] +) -> dict[str, Image.Image]: + """ + Read a 32bit RGB icon resource. Seems to be either uncompressed or + an RLE packbits-like scheme. + """ + start, length = start_length + fobj.seek(start) + pixel_size = (size[0] * size[2], size[1] * size[2]) + sizesq = pixel_size[0] * pixel_size[1] + if length == sizesq * 3: + # uncompressed ("RGBRGBGB") + indata = fobj.read(length) + im = Image.frombuffer("RGB", pixel_size, indata, "raw", "RGB", 0, 1) + else: + # decode image + im = Image.new("RGB", pixel_size, None) + for band_ix in range(3): + data = [] + bytesleft = sizesq + while bytesleft > 0: + byte = fobj.read(1) + if not byte: + break + byte_int = byte[0] + if byte_int & 0x80: + blocksize = byte_int - 125 + byte = fobj.read(1) + data.extend([byte] * blocksize) + else: + blocksize = byte_int + 1 + data.append(fobj.read(blocksize)) + bytesleft -= blocksize + if bytesleft <= 0: + break + if bytesleft != 0: + msg = f"Error reading channel [{repr(bytesleft)} left]" + raise SyntaxError(msg) + band = Image.frombuffer("L", pixel_size, b"".join(data), "raw", "L", 0, 1) + im.im.putband(band.im, band_ix) + return {"RGB": im} + + +def read_mk( + fobj: IO[bytes], start_length: tuple[int, int], size: tuple[int, int, int] +) -> dict[str, Image.Image]: + # Alpha masks seem to be uncompressed + start = start_length[0] + fobj.seek(start) + pixel_size = (size[0] * size[2], size[1] * size[2]) + sizesq = pixel_size[0] * pixel_size[1] + band = Image.frombuffer("L", pixel_size, fobj.read(sizesq), "raw", "L", 0, 1) + return {"A": band} + + +def read_png_or_jpeg2000( + fobj: IO[bytes], start_length: tuple[int, int], size: tuple[int, int, int] +) -> dict[str, Image.Image]: + start, length = start_length + fobj.seek(start) + sig = fobj.read(12) + + im: Image.Image + if sig.startswith(b"\x89PNG\x0d\x0a\x1a\x0a"): + fobj.seek(start) + im = PngImagePlugin.PngImageFile(fobj) + Image._decompression_bomb_check(im.size) + return {"RGBA": im} + elif ( + sig.startswith((b"\xff\x4f\xff\x51", b"\x0d\x0a\x87\x0a")) + or sig == b"\x00\x00\x00\x0cjP \x0d\x0a\x87\x0a" + ): + if not enable_jpeg2k: + msg = ( + "Unsupported icon subimage format (rebuild PIL " + "with JPEG 2000 support to fix this)" + ) + raise ValueError(msg) + # j2k, jpc or j2c + fobj.seek(start) + jp2kstream = fobj.read(length) + f = io.BytesIO(jp2kstream) + im = Jpeg2KImagePlugin.Jpeg2KImageFile(f) + Image._decompression_bomb_check(im.size) + if im.mode != "RGBA": + im = im.convert("RGBA") + return {"RGBA": im} + else: + msg = "Unsupported icon subimage format" + raise ValueError(msg) + + +class IcnsFile: + SIZES = { + (512, 512, 2): [(b"ic10", read_png_or_jpeg2000)], + (512, 512, 1): [(b"ic09", read_png_or_jpeg2000)], + (256, 256, 2): [(b"ic14", read_png_or_jpeg2000)], + (256, 256, 1): [(b"ic08", read_png_or_jpeg2000)], + (128, 128, 2): [(b"ic13", read_png_or_jpeg2000)], + (128, 128, 1): [ + (b"ic07", read_png_or_jpeg2000), + (b"it32", read_32t), + (b"t8mk", read_mk), + ], + (64, 64, 1): [(b"icp6", read_png_or_jpeg2000)], + (32, 32, 2): [(b"ic12", read_png_or_jpeg2000)], + (48, 48, 1): [(b"ih32", read_32), (b"h8mk", read_mk)], + (32, 32, 1): [ + (b"icp5", read_png_or_jpeg2000), + (b"il32", read_32), + (b"l8mk", read_mk), + ], + (16, 16, 2): [(b"ic11", read_png_or_jpeg2000)], + (16, 16, 1): [ + (b"icp4", read_png_or_jpeg2000), + (b"is32", read_32), + (b"s8mk", read_mk), + ], + } + + def __init__(self, fobj: IO[bytes]) -> None: + """ + fobj is a file-like object as an icns resource + """ + # signature : (start, length) + self.dct = {} + self.fobj = fobj + sig, filesize = nextheader(fobj) + if not _accept(sig): + msg = "not an icns file" + raise SyntaxError(msg) + i = HEADERSIZE + while i < filesize: + sig, blocksize = nextheader(fobj) + if blocksize <= 0: + msg = "invalid block header" + raise SyntaxError(msg) + i += HEADERSIZE + blocksize -= HEADERSIZE + self.dct[sig] = (i, blocksize) + fobj.seek(blocksize, io.SEEK_CUR) + i += blocksize + + def itersizes(self) -> list[tuple[int, int, int]]: + sizes = [] + for size, fmts in self.SIZES.items(): + for fmt, reader in fmts: + if fmt in self.dct: + sizes.append(size) + break + return sizes + + def bestsize(self) -> tuple[int, int, int]: + sizes = self.itersizes() + if not sizes: + msg = "No 32bit icon resources found" + raise SyntaxError(msg) + return max(sizes) + + def dataforsize(self, size: tuple[int, int, int]) -> dict[str, Image.Image]: + """ + Get an icon resource as {channel: array}. Note that + the arrays are bottom-up like windows bitmaps and will likely + need to be flipped or transposed in some way. + """ + dct = {} + for code, reader in self.SIZES[size]: + desc = self.dct.get(code) + if desc is not None: + dct.update(reader(self.fobj, desc, size)) + return dct + + def getimage( + self, size: tuple[int, int] | tuple[int, int, int] | None = None + ) -> Image.Image: + if size is None: + size = self.bestsize() + elif len(size) == 2: + size = (size[0], size[1], 1) + channels = self.dataforsize(size) + + im = channels.get("RGBA") + if im: + return im + + im = channels["RGB"].copy() + try: + im.putalpha(channels["A"]) + except KeyError: + pass + return im + + +## +# Image plugin for Mac OS icons. + + +class IcnsImageFile(ImageFile.ImageFile): + """ + PIL image support for Mac OS .icns files. + Chooses the best resolution, but will possibly load + a different size image if you mutate the size attribute + before calling 'load'. + + The info dictionary has a key 'sizes' that is a list + of sizes that the icns file has. + """ + + format = "ICNS" + format_description = "Mac OS icns resource" + + def _open(self) -> None: + assert self.fp is not None + self.icns = IcnsFile(self.fp) + self._mode = "RGBA" + self.info["sizes"] = self.icns.itersizes() + self.best_size = self.icns.bestsize() + self.size = ( + self.best_size[0] * self.best_size[2], + self.best_size[1] * self.best_size[2], + ) + + @property + def size(self) -> tuple[int, int]: + return self._size + + @size.setter + def size(self, value: tuple[int, int]) -> None: + # Check that a matching size exists, + # or that there is a scale that would create a size that matches + for size in self.info["sizes"]: + simple_size = size[0] * size[2], size[1] * size[2] + scale = simple_size[0] // value[0] + if simple_size[1] / value[1] == scale: + self._size = value + return + msg = "This is not one of the allowed sizes of this image" + raise ValueError(msg) + + def load(self, scale: int | None = None) -> Image.core.PixelAccess | None: + if scale is not None: + width, height = self.size[:2] + self.size = width * scale, height * scale + self.best_size = width, height, scale + + px = Image.Image.load(self) + if self._im is not None and self.im.size == self.size: + # Already loaded + return px + self.load_prepare() + # This is likely NOT the best way to do it, but whatever. + im = self.icns.getimage(self.best_size) + + # If this is a PNG or JPEG 2000, it won't be loaded yet + px = im.load() + + self.im = im.im + self._mode = im.mode + self.size = im.size + + return px + + +def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + """ + Saves the image as a series of PNG files, + that are then combined into a .icns file. + """ + if hasattr(fp, "flush"): + fp.flush() + + sizes = { + b"ic07": 128, + b"ic08": 256, + b"ic09": 512, + b"ic10": 1024, + b"ic11": 32, + b"ic12": 64, + b"ic13": 256, + b"ic14": 512, + } + provided_images = {im.width: im for im in im.encoderinfo.get("append_images", [])} + size_streams = {} + for size in set(sizes.values()): + image = ( + provided_images[size] + if size in provided_images + else im.resize((size, size)) + ) + + temp = io.BytesIO() + image.save(temp, "png") + size_streams[size] = temp.getvalue() + + entries = [] + for type, size in sizes.items(): + stream = size_streams[size] + entries.append((type, HEADERSIZE + len(stream), stream)) + + # Header + fp.write(MAGIC) + file_length = HEADERSIZE # Header + file_length += HEADERSIZE + 8 * len(entries) # TOC + file_length += sum(entry[1] for entry in entries) + fp.write(struct.pack(">i", file_length)) + + # TOC + fp.write(b"TOC ") + fp.write(struct.pack(">i", HEADERSIZE + len(entries) * HEADERSIZE)) + for entry in entries: + fp.write(entry[0]) + fp.write(struct.pack(">i", entry[1])) + + # Data + for entry in entries: + fp.write(entry[0]) + fp.write(struct.pack(">i", entry[1])) + fp.write(entry[2]) + + if hasattr(fp, "flush"): + fp.flush() + + +def _accept(prefix: bytes) -> bool: + return prefix.startswith(MAGIC) + + +Image.register_open(IcnsImageFile.format, IcnsImageFile, _accept) +Image.register_extension(IcnsImageFile.format, ".icns") + +Image.register_save(IcnsImageFile.format, _save) +Image.register_mime(IcnsImageFile.format, "image/icns") + +if __name__ == "__main__": + if len(sys.argv) < 2: + print("Syntax: python3 IcnsImagePlugin.py [file]") + sys.exit() + + with open(sys.argv[1], "rb") as fp: + imf = IcnsImageFile(fp) + for size in imf.info["sizes"]: + width, height, scale = imf.size = size + imf.save(f"out-{width}-{height}-{scale}.png") + with Image.open(sys.argv[1]) as im: + im.save("out.png") + if sys.platform == "windows": + os.startfile("out.png") diff --git a/.venv/lib/python3.11/site-packages/PIL/IcoImagePlugin.py b/.venv/lib/python3.11/site-packages/PIL/IcoImagePlugin.py new file mode 100644 index 0000000000000000000000000000000000000000..8dd57ff858ab9aca62434699d9fef8ae956a4867 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/IcoImagePlugin.py @@ -0,0 +1,396 @@ +# +# The Python Imaging Library. +# $Id$ +# +# Windows Icon support for PIL +# +# History: +# 96-05-27 fl Created +# +# Copyright (c) Secret Labs AB 1997. +# Copyright (c) Fredrik Lundh 1996. +# +# See the README file for information on usage and redistribution. +# + +# This plugin is a refactored version of Win32IconImagePlugin by Bryan Davis +# . +# https://code.google.com/archive/p/casadebender/wikis/Win32IconImagePlugin.wiki +# +# Copyright 2008 Bryan Davis +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Icon format references: +# * https://en.wikipedia.org/wiki/ICO_(file_format) +# * https://msdn.microsoft.com/en-us/library/ms997538.aspx +from __future__ import annotations + +import warnings +from io import BytesIO +from math import ceil, log +from typing import IO, NamedTuple + +from . import BmpImagePlugin, Image, ImageFile, PngImagePlugin +from ._binary import i16le as i16 +from ._binary import i32le as i32 +from ._binary import o8 +from ._binary import o16le as o16 +from ._binary import o32le as o32 + +# +# -------------------------------------------------------------------- + +_MAGIC = b"\0\0\1\0" + + +def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + fp.write(_MAGIC) # (2+2) + bmp = im.encoderinfo.get("bitmap_format") == "bmp" + sizes = im.encoderinfo.get( + "sizes", + [(16, 16), (24, 24), (32, 32), (48, 48), (64, 64), (128, 128), (256, 256)], + ) + frames = [] + provided_ims = [im] + im.encoderinfo.get("append_images", []) + width, height = im.size + for size in sorted(set(sizes)): + if size[0] > width or size[1] > height or size[0] > 256 or size[1] > 256: + continue + + for provided_im in provided_ims: + if provided_im.size != size: + continue + frames.append(provided_im) + if bmp: + bits = BmpImagePlugin.SAVE[provided_im.mode][1] + bits_used = [bits] + for other_im in provided_ims: + if other_im.size != size: + continue + bits = BmpImagePlugin.SAVE[other_im.mode][1] + if bits not in bits_used: + # Another image has been supplied for this size + # with a different bit depth + frames.append(other_im) + bits_used.append(bits) + break + else: + # TODO: invent a more convenient method for proportional scalings + frame = provided_im.copy() + frame.thumbnail(size, Image.Resampling.LANCZOS, reducing_gap=None) + frames.append(frame) + fp.write(o16(len(frames))) # idCount(2) + offset = fp.tell() + len(frames) * 16 + for frame in frames: + width, height = frame.size + # 0 means 256 + fp.write(o8(width if width < 256 else 0)) # bWidth(1) + fp.write(o8(height if height < 256 else 0)) # bHeight(1) + + bits, colors = BmpImagePlugin.SAVE[frame.mode][1:] if bmp else (32, 0) + fp.write(o8(colors)) # bColorCount(1) + fp.write(b"\0") # bReserved(1) + fp.write(b"\0\0") # wPlanes(2) + fp.write(o16(bits)) # wBitCount(2) + + image_io = BytesIO() + if bmp: + frame.save(image_io, "dib") + + if bits != 32: + and_mask = Image.new("1", size) + ImageFile._save( + and_mask, + image_io, + [ImageFile._Tile("raw", (0, 0) + size, 0, ("1", 0, -1))], + ) + else: + frame.save(image_io, "png") + image_io.seek(0) + image_bytes = image_io.read() + if bmp: + image_bytes = image_bytes[:8] + o32(height * 2) + image_bytes[12:] + bytes_len = len(image_bytes) + fp.write(o32(bytes_len)) # dwBytesInRes(4) + fp.write(o32(offset)) # dwImageOffset(4) + current = fp.tell() + fp.seek(offset) + fp.write(image_bytes) + offset = offset + bytes_len + fp.seek(current) + + +def _accept(prefix: bytes) -> bool: + return prefix.startswith(_MAGIC) + + +class IconHeader(NamedTuple): + width: int + height: int + nb_color: int + reserved: int + planes: int + bpp: int + size: int + offset: int + dim: tuple[int, int] + square: int + color_depth: int + + +class IcoFile: + def __init__(self, buf: IO[bytes]) -> None: + """ + Parse image from file-like object containing ico file data + """ + + # check magic + s = buf.read(6) + if not _accept(s): + msg = "not an ICO file" + raise SyntaxError(msg) + + self.buf = buf + self.entry = [] + + # Number of items in file + self.nb_items = i16(s, 4) + + # Get headers for each item + for i in range(self.nb_items): + s = buf.read(16) + + # See Wikipedia + width = s[0] or 256 + height = s[1] or 256 + + # No. of colors in image (0 if >=8bpp) + nb_color = s[2] + bpp = i16(s, 6) + icon_header = IconHeader( + width=width, + height=height, + nb_color=nb_color, + reserved=s[3], + planes=i16(s, 4), + bpp=i16(s, 6), + size=i32(s, 8), + offset=i32(s, 12), + dim=(width, height), + square=width * height, + # See Wikipedia notes about color depth. + # We need this just to differ images with equal sizes + color_depth=bpp or (nb_color != 0 and ceil(log(nb_color, 2))) or 256, + ) + + self.entry.append(icon_header) + + self.entry = sorted(self.entry, key=lambda x: x.color_depth) + # ICO images are usually squares + self.entry = sorted(self.entry, key=lambda x: x.square, reverse=True) + + def sizes(self) -> set[tuple[int, int]]: + """ + Get a set of all available icon sizes and color depths. + """ + return {(h.width, h.height) for h in self.entry} + + def getentryindex(self, size: tuple[int, int], bpp: int | bool = False) -> int: + for i, h in enumerate(self.entry): + if size == h.dim and (bpp is False or bpp == h.color_depth): + return i + return 0 + + def getimage(self, size: tuple[int, int], bpp: int | bool = False) -> Image.Image: + """ + Get an image from the icon + """ + return self.frame(self.getentryindex(size, bpp)) + + def frame(self, idx: int) -> Image.Image: + """ + Get an image from frame idx + """ + + header = self.entry[idx] + + self.buf.seek(header.offset) + data = self.buf.read(8) + self.buf.seek(header.offset) + + im: Image.Image + if data[:8] == PngImagePlugin._MAGIC: + # png frame + im = PngImagePlugin.PngImageFile(self.buf) + Image._decompression_bomb_check(im.size) + else: + # XOR + AND mask bmp frame + im = BmpImagePlugin.DibImageFile(self.buf) + Image._decompression_bomb_check(im.size) + + # change tile dimension to only encompass XOR image + im._size = (im.size[0], int(im.size[1] / 2)) + d, e, o, a = im.tile[0] + im.tile[0] = ImageFile._Tile(d, (0, 0) + im.size, o, a) + + # figure out where AND mask image starts + if header.bpp == 32: + # 32-bit color depth icon image allows semitransparent areas + # PIL's DIB format ignores transparency bits, recover them. + # The DIB is packed in BGRX byte order where X is the alpha + # channel. + + # Back up to start of bmp data + self.buf.seek(o) + # extract every 4th byte (eg. 3,7,11,15,...) + alpha_bytes = self.buf.read(im.size[0] * im.size[1] * 4)[3::4] + + # convert to an 8bpp grayscale image + try: + mask = Image.frombuffer( + "L", # 8bpp + im.size, # (w, h) + alpha_bytes, # source chars + "raw", # raw decoder + ("L", 0, -1), # 8bpp inverted, unpadded, reversed + ) + except ValueError: + if ImageFile.LOAD_TRUNCATED_IMAGES: + mask = None + else: + raise + else: + # get AND image from end of bitmap + w = im.size[0] + if (w % 32) > 0: + # bitmap row data is aligned to word boundaries + w += 32 - (im.size[0] % 32) + + # the total mask data is + # padded row size * height / bits per char + + total_bytes = int((w * im.size[1]) / 8) + and_mask_offset = header.offset + header.size - total_bytes + + self.buf.seek(and_mask_offset) + mask_data = self.buf.read(total_bytes) + + # convert raw data to image + try: + mask = Image.frombuffer( + "1", # 1 bpp + im.size, # (w, h) + mask_data, # source chars + "raw", # raw decoder + ("1;I", int(w / 8), -1), # 1bpp inverted, padded, reversed + ) + except ValueError: + if ImageFile.LOAD_TRUNCATED_IMAGES: + mask = None + else: + raise + + # now we have two images, im is XOR image and mask is AND image + + # apply mask image as alpha channel + if mask: + im = im.convert("RGBA") + im.putalpha(mask) + + return im + + +## +# Image plugin for Windows Icon files. + + +class IcoImageFile(ImageFile.ImageFile): + """ + PIL read-only image support for Microsoft Windows .ico files. + + By default the largest resolution image in the file will be loaded. This + can be changed by altering the 'size' attribute before calling 'load'. + + The info dictionary has a key 'sizes' that is a list of the sizes available + in the icon file. + + Handles classic, XP and Vista icon formats. + + When saving, PNG compression is used. Support for this was only added in + Windows Vista. If you are unable to view the icon in Windows, convert the + image to "RGBA" mode before saving. + + This plugin is a refactored version of Win32IconImagePlugin by Bryan Davis + . + https://code.google.com/archive/p/casadebender/wikis/Win32IconImagePlugin.wiki + """ + + format = "ICO" + format_description = "Windows Icon" + + def _open(self) -> None: + assert self.fp is not None + self.ico = IcoFile(self.fp) + self.info["sizes"] = self.ico.sizes() + self.size = self.ico.entry[0].dim + self.load() + + @property + def size(self) -> tuple[int, int]: + return self._size + + @size.setter + def size(self, value: tuple[int, int]) -> None: + if value not in self.info["sizes"]: + msg = "This is not one of the allowed sizes of this image" + raise ValueError(msg) + self._size = value + + def load(self) -> Image.core.PixelAccess | None: + if self._im is not None and self.im.size == self.size: + # Already loaded + return Image.Image.load(self) + im = self.ico.getimage(self.size) + # if tile is PNG, it won't really be loaded yet + im.load() + self.im = im.im + self._mode = im.mode + if im.palette: + self.palette = im.palette + if im.size != self.size: + warnings.warn("Image was not the expected size") + + index = self.ico.getentryindex(self.size) + sizes = list(self.info["sizes"]) + sizes[index] = im.size + self.info["sizes"] = set(sizes) + + self.size = im.size + return Image.Image.load(self) + + def load_seek(self, pos: int) -> None: + # Flag the ImageFile.Parser so that it + # just does all the decode at the end. + pass + + +# +# -------------------------------------------------------------------- + + +Image.register_open(IcoImageFile.format, IcoImageFile, _accept) +Image.register_save(IcoImageFile.format, _save) +Image.register_extension(IcoImageFile.format, ".ico") + +Image.register_mime(IcoImageFile.format, "image/x-icon") diff --git a/.venv/lib/python3.11/site-packages/PIL/ImImagePlugin.py b/.venv/lib/python3.11/site-packages/PIL/ImImagePlugin.py new file mode 100644 index 0000000000000000000000000000000000000000..ef54f16e97e69a1410880e48ffecb1a2cbf15ea8 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/ImImagePlugin.py @@ -0,0 +1,390 @@ +# +# The Python Imaging Library. +# $Id$ +# +# IFUNC IM file handling for PIL +# +# history: +# 1995-09-01 fl Created. +# 1997-01-03 fl Save palette images +# 1997-01-08 fl Added sequence support +# 1997-01-23 fl Added P and RGB save support +# 1997-05-31 fl Read floating point images +# 1997-06-22 fl Save floating point images +# 1997-08-27 fl Read and save 1-bit images +# 1998-06-25 fl Added support for RGB+LUT images +# 1998-07-02 fl Added support for YCC images +# 1998-07-15 fl Renamed offset attribute to avoid name clash +# 1998-12-29 fl Added I;16 support +# 2001-02-17 fl Use 're' instead of 'regex' (Python 2.1) (0.7) +# 2003-09-26 fl Added LA/PA support +# +# Copyright (c) 1997-2003 by Secret Labs AB. +# Copyright (c) 1995-2001 by Fredrik Lundh. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import os +import re +from typing import IO, Any + +from . import Image, ImageFile, ImagePalette +from ._util import DeferredError + +# -------------------------------------------------------------------- +# Standard tags + +COMMENT = "Comment" +DATE = "Date" +EQUIPMENT = "Digitalization equipment" +FRAMES = "File size (no of images)" +LUT = "Lut" +NAME = "Name" +SCALE = "Scale (x,y)" +SIZE = "Image size (x*y)" +MODE = "Image type" + +TAGS = { + COMMENT: 0, + DATE: 0, + EQUIPMENT: 0, + FRAMES: 0, + LUT: 0, + NAME: 0, + SCALE: 0, + SIZE: 0, + MODE: 0, +} + +OPEN = { + # ifunc93/p3cfunc formats + "0 1 image": ("1", "1"), + "L 1 image": ("1", "1"), + "Greyscale image": ("L", "L"), + "Grayscale image": ("L", "L"), + "RGB image": ("RGB", "RGB;L"), + "RLB image": ("RGB", "RLB"), + "RYB image": ("RGB", "RLB"), + "B1 image": ("1", "1"), + "B2 image": ("P", "P;2"), + "B4 image": ("P", "P;4"), + "X 24 image": ("RGB", "RGB"), + "L 32 S image": ("I", "I;32"), + "L 32 F image": ("F", "F;32"), + # old p3cfunc formats + "RGB3 image": ("RGB", "RGB;T"), + "RYB3 image": ("RGB", "RYB;T"), + # extensions + "LA image": ("LA", "LA;L"), + "PA image": ("LA", "PA;L"), + "RGBA image": ("RGBA", "RGBA;L"), + "RGBX image": ("RGB", "RGBX;L"), + "CMYK image": ("CMYK", "CMYK;L"), + "YCC image": ("YCbCr", "YCbCr;L"), +} + +# ifunc95 extensions +for i in ["8", "8S", "16", "16S", "32", "32F"]: + OPEN[f"L {i} image"] = ("F", f"F;{i}") + OPEN[f"L*{i} image"] = ("F", f"F;{i}") +for i in ["16", "16L", "16B"]: + OPEN[f"L {i} image"] = (f"I;{i}", f"I;{i}") + OPEN[f"L*{i} image"] = (f"I;{i}", f"I;{i}") +for i in ["32S"]: + OPEN[f"L {i} image"] = ("I", f"I;{i}") + OPEN[f"L*{i} image"] = ("I", f"I;{i}") +for j in range(2, 33): + OPEN[f"L*{j} image"] = ("F", f"F;{j}") + + +# -------------------------------------------------------------------- +# Read IM directory + +split = re.compile(rb"^([A-Za-z][^:]*):[ \t]*(.*)[ \t]*$") + + +def number(s: Any) -> float: + try: + return int(s) + except ValueError: + return float(s) + + +## +# Image plugin for the IFUNC IM file format. + + +class ImImageFile(ImageFile.ImageFile): + format = "IM" + format_description = "IFUNC Image Memory" + _close_exclusive_fp_after_loading = False + + def _open(self) -> None: + # Quick rejection: if there's not an LF among the first + # 100 bytes, this is (probably) not a text header. + + assert self.fp is not None + if b"\n" not in self.fp.read(100): + msg = "not an IM file" + raise SyntaxError(msg) + self.fp.seek(0) + + n = 0 + + # Default values + self.info[MODE] = "L" + self.info[SIZE] = (512, 512) + self.info[FRAMES] = 1 + + self.rawmode = "L" + + while True: + s = self.fp.read(1) + + # Some versions of IFUNC uses \n\r instead of \r\n... + if s == b"\r": + continue + + if not s or s == b"\0" or s == b"\x1a": + break + + # FIXME: this may read whole file if not a text file + s = s + self.fp.readline() + + if len(s) > 100: + msg = "not an IM file" + raise SyntaxError(msg) + + if s.endswith(b"\r\n"): + s = s[:-2] + elif s.endswith(b"\n"): + s = s[:-1] + + try: + m = split.match(s) + except re.error as e: + msg = "not an IM file" + raise SyntaxError(msg) from e + + if m: + k, v = m.group(1, 2) + + # Don't know if this is the correct encoding, + # but a decent guess (I guess) + k = k.decode("latin-1", "replace") + v = v.decode("latin-1", "replace") + + # Convert value as appropriate + if k in [FRAMES, SCALE, SIZE]: + v = v.replace("*", ",") + v = tuple(map(number, v.split(","))) + if len(v) == 1: + v = v[0] + elif k == MODE and v in OPEN: + v, self.rawmode = OPEN[v] + + # Add to dictionary. Note that COMMENT tags are + # combined into a list of strings. + if k == COMMENT: + if k in self.info: + self.info[k].append(v) + else: + self.info[k] = [v] + else: + self.info[k] = v + + if k in TAGS: + n += 1 + + else: + msg = f"Syntax error in IM header: {s.decode('ascii', 'replace')}" + raise SyntaxError(msg) + + if not n: + msg = "Not an IM file" + raise SyntaxError(msg) + + # Basic attributes + self._size = self.info[SIZE] + self._mode = self.info[MODE] + + # Skip forward to start of image data + while s and not s.startswith(b"\x1a"): + s = self.fp.read(1) + if not s: + msg = "File truncated" + raise SyntaxError(msg) + + if LUT in self.info: + # convert lookup table to palette or lut attribute + palette = self.fp.read(768) + greyscale = 1 # greyscale palette + linear = 1 # linear greyscale palette + for i in range(256): + if palette[i] == palette[i + 256] == palette[i + 512]: + if palette[i] != i: + linear = 0 + else: + greyscale = 0 + if self.mode in ["L", "LA", "P", "PA"]: + if greyscale: + if not linear: + self.lut = list(palette[:256]) + else: + if self.mode in ["L", "P"]: + self._mode = self.rawmode = "P" + elif self.mode in ["LA", "PA"]: + self._mode = "PA" + self.rawmode = "PA;L" + self.palette = ImagePalette.raw("RGB;L", palette) + elif self.mode == "RGB": + if not greyscale or not linear: + self.lut = list(palette) + + self.frame = 0 + + self.__offset = offs = self.fp.tell() + + self._fp = self.fp # FIXME: hack + + if self.rawmode.startswith("F;"): + # ifunc95 formats + try: + # use bit decoder (if necessary) + bits = int(self.rawmode[2:]) + if bits not in [8, 16, 32]: + self.tile = [ + ImageFile._Tile( + "bit", (0, 0) + self.size, offs, (bits, 8, 3, 0, -1) + ) + ] + return + except ValueError: + pass + + if self.rawmode in ["RGB;T", "RYB;T"]: + # Old LabEye/3PC files. Would be very surprised if anyone + # ever stumbled upon such a file ;-) + size = self.size[0] * self.size[1] + self.tile = [ + ImageFile._Tile("raw", (0, 0) + self.size, offs, ("G", 0, -1)), + ImageFile._Tile("raw", (0, 0) + self.size, offs + size, ("R", 0, -1)), + ImageFile._Tile( + "raw", (0, 0) + self.size, offs + 2 * size, ("B", 0, -1) + ), + ] + else: + # LabEye/IFUNC files + self.tile = [ + ImageFile._Tile("raw", (0, 0) + self.size, offs, (self.rawmode, 0, -1)) + ] + + @property + def n_frames(self) -> int: + return self.info[FRAMES] + + @property + def is_animated(self) -> bool: + return self.info[FRAMES] > 1 + + def seek(self, frame: int) -> None: + if not self._seek_check(frame): + return + if isinstance(self._fp, DeferredError): + raise self._fp.ex + + self.frame = frame + + if self.mode == "1": + bits = 1 + else: + bits = 8 * len(self.mode) + + size = ((self.size[0] * bits + 7) // 8) * self.size[1] + offs = self.__offset + frame * size + + self.fp = self._fp + + self.tile = [ + ImageFile._Tile("raw", (0, 0) + self.size, offs, (self.rawmode, 0, -1)) + ] + + def tell(self) -> int: + return self.frame + + +# +# -------------------------------------------------------------------- +# Save IM files + + +SAVE = { + # mode: (im type, raw mode) + "1": ("0 1", "1"), + "L": ("Greyscale", "L"), + "LA": ("LA", "LA;L"), + "P": ("Greyscale", "P"), + "PA": ("LA", "PA;L"), + "I": ("L 32S", "I;32S"), + "I;16": ("L 16", "I;16"), + "I;16L": ("L 16L", "I;16L"), + "I;16B": ("L 16B", "I;16B"), + "F": ("L 32F", "F;32F"), + "RGB": ("RGB", "RGB;L"), + "RGBA": ("RGBA", "RGBA;L"), + "RGBX": ("RGBX", "RGBX;L"), + "CMYK": ("CMYK", "CMYK;L"), + "YCbCr": ("YCC", "YCbCr;L"), +} + + +def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + try: + image_type, rawmode = SAVE[im.mode] + except KeyError as e: + msg = f"Cannot save {im.mode} images as IM" + raise ValueError(msg) from e + + frames = im.encoderinfo.get("frames", 1) + + fp.write(f"Image type: {image_type} image\r\n".encode("ascii")) + if filename: + # Each line must be 100 characters or less, + # or: SyntaxError("not an IM file") + # 8 characters are used for "Name: " and "\r\n" + # Keep just the filename, ditch the potentially overlong path + if isinstance(filename, bytes): + filename = filename.decode("ascii") + name, ext = os.path.splitext(os.path.basename(filename)) + name = "".join([name[: 92 - len(ext)], ext]) + + fp.write(f"Name: {name}\r\n".encode("ascii")) + fp.write(f"Image size (x*y): {im.size[0]}*{im.size[1]}\r\n".encode("ascii")) + fp.write(f"File size (no of images): {frames}\r\n".encode("ascii")) + if im.mode in ["P", "PA"]: + fp.write(b"Lut: 1\r\n") + fp.write(b"\000" * (511 - fp.tell()) + b"\032") + if im.mode in ["P", "PA"]: + im_palette = im.im.getpalette("RGB", "RGB;L") + colors = len(im_palette) // 3 + palette = b"" + for i in range(3): + palette += im_palette[colors * i : colors * (i + 1)] + palette += b"\x00" * (256 - colors) + fp.write(palette) # 768 bytes + ImageFile._save( + im, fp, [ImageFile._Tile("raw", (0, 0) + im.size, 0, (rawmode, 0, -1))] + ) + + +# +# -------------------------------------------------------------------- +# Registry + + +Image.register_open(ImImageFile.format, ImImageFile) +Image.register_save(ImImageFile.format, _save) + +Image.register_extension(ImImageFile.format, ".im") diff --git a/.venv/lib/python3.11/site-packages/PIL/Image.py b/.venv/lib/python3.11/site-packages/PIL/Image.py new file mode 100644 index 0000000000000000000000000000000000000000..ebbd8fd35f8c70efea20518729602143df3466c7 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/Image.py @@ -0,0 +1,4385 @@ +# +# The Python Imaging Library. +# $Id$ +# +# the Image class wrapper +# +# partial release history: +# 1995-09-09 fl Created +# 1996-03-11 fl PIL release 0.0 (proof of concept) +# 1996-04-30 fl PIL release 0.1b1 +# 1999-07-28 fl PIL release 1.0 final +# 2000-06-07 fl PIL release 1.1 +# 2000-10-20 fl PIL release 1.1.1 +# 2001-05-07 fl PIL release 1.1.2 +# 2002-03-15 fl PIL release 1.1.3 +# 2003-05-10 fl PIL release 1.1.4 +# 2005-03-28 fl PIL release 1.1.5 +# 2006-12-02 fl PIL release 1.1.6 +# 2009-11-15 fl PIL release 1.1.7 +# +# Copyright (c) 1997-2009 by Secret Labs AB. All rights reserved. +# Copyright (c) 1995-2009 by Fredrik Lundh. +# +# See the README file for information on usage and redistribution. +# + +from __future__ import annotations + +import abc +import atexit +import builtins +import io +import logging +import math +import os +import re +import struct +import sys +import tempfile +import warnings +from collections.abc import MutableMapping +from enum import IntEnum +from typing import IO, Protocol, cast + +# VERSION was removed in Pillow 6.0.0. +# PILLOW_VERSION was removed in Pillow 9.0.0. +# Use __version__ instead. +from . import ( + ExifTags, + ImageMode, + TiffTags, + UnidentifiedImageError, + __version__, + _plugins, +) +from ._binary import i32le, o32be, o32le +from ._deprecate import deprecate +from ._util import DeferredError, is_path + +ElementTree: ModuleType | None +try: + from defusedxml import ElementTree +except ImportError: + ElementTree = None + +TYPE_CHECKING = False +if TYPE_CHECKING: + from collections.abc import Callable, Iterator, Sequence + from types import ModuleType + from typing import Any, Literal + +logger = logging.getLogger(__name__) + + +class DecompressionBombWarning(RuntimeWarning): + pass + + +class DecompressionBombError(Exception): + pass + + +WARN_POSSIBLE_FORMATS: bool = False + +# Limit to around a quarter gigabyte for a 24-bit (3 bpp) image +MAX_IMAGE_PIXELS: int | None = int(1024 * 1024 * 1024 // 4 // 3) + + +try: + # If the _imaging C module is not present, Pillow will not load. + # Note that other modules should not refer to _imaging directly; + # import Image and use the Image.core variable instead. + # Also note that Image.core is not a publicly documented interface, + # and should be considered private and subject to change. + from . import _imaging as core + + if __version__ != getattr(core, "PILLOW_VERSION", None): + msg = ( + "The _imaging extension was built for another version of Pillow or PIL:\n" + f"Core version: {getattr(core, 'PILLOW_VERSION', None)}\n" + f"Pillow version: {__version__}" + ) + raise ImportError(msg) + +except ImportError as v: + # Explanations for ways that we know we might have an import error + if str(v).startswith("Module use of python"): + # The _imaging C module is present, but not compiled for + # the right version (windows only). Print a warning, if + # possible. + warnings.warn( + "The _imaging extension was built for another version of Python.", + RuntimeWarning, + ) + elif str(v).startswith("The _imaging extension"): + warnings.warn(str(v), RuntimeWarning) + # Fail here anyway. Don't let people run with a mostly broken Pillow. + # see docs/porting.rst + raise + + +# +# Constants + + +# transpose +class Transpose(IntEnum): + FLIP_LEFT_RIGHT = 0 + FLIP_TOP_BOTTOM = 1 + ROTATE_90 = 2 + ROTATE_180 = 3 + ROTATE_270 = 4 + TRANSPOSE = 5 + TRANSVERSE = 6 + + +# transforms (also defined in Imaging.h) +class Transform(IntEnum): + AFFINE = 0 + EXTENT = 1 + PERSPECTIVE = 2 + QUAD = 3 + MESH = 4 + + +# resampling filters (also defined in Imaging.h) +class Resampling(IntEnum): + NEAREST = 0 + BOX = 4 + BILINEAR = 2 + HAMMING = 5 + BICUBIC = 3 + LANCZOS = 1 + + +_filters_support = { + Resampling.BOX: 0.5, + Resampling.BILINEAR: 1.0, + Resampling.HAMMING: 1.0, + Resampling.BICUBIC: 2.0, + Resampling.LANCZOS: 3.0, +} + + +# dithers +class Dither(IntEnum): + NONE = 0 + ORDERED = 1 # Not yet implemented + RASTERIZE = 2 # Not yet implemented + FLOYDSTEINBERG = 3 # default + + +# palettes/quantizers +class Palette(IntEnum): + WEB = 0 + ADAPTIVE = 1 + + +class Quantize(IntEnum): + MEDIANCUT = 0 + MAXCOVERAGE = 1 + FASTOCTREE = 2 + LIBIMAGEQUANT = 3 + + +module = sys.modules[__name__] +for enum in (Transpose, Transform, Resampling, Dither, Palette, Quantize): + for item in enum: + setattr(module, item.name, item.value) + + +if hasattr(core, "DEFAULT_STRATEGY"): + DEFAULT_STRATEGY = core.DEFAULT_STRATEGY + FILTERED = core.FILTERED + HUFFMAN_ONLY = core.HUFFMAN_ONLY + RLE = core.RLE + FIXED = core.FIXED + + +# -------------------------------------------------------------------- +# Registries + +TYPE_CHECKING = False +if TYPE_CHECKING: + import mmap + from xml.etree.ElementTree import Element + + from IPython.lib.pretty import PrettyPrinter + + from . import ImageFile, ImageFilter, ImagePalette, ImageQt, TiffImagePlugin + from ._typing import CapsuleType, NumpyArray, StrOrBytesPath +ID: list[str] = [] +OPEN: dict[ + str, + tuple[ + Callable[[IO[bytes], str | bytes], ImageFile.ImageFile], + Callable[[bytes], bool | str] | None, + ], +] = {} +MIME: dict[str, str] = {} +SAVE: dict[str, Callable[[Image, IO[bytes], str | bytes], None]] = {} +SAVE_ALL: dict[str, Callable[[Image, IO[bytes], str | bytes], None]] = {} +EXTENSION: dict[str, str] = {} +DECODERS: dict[str, type[ImageFile.PyDecoder]] = {} +ENCODERS: dict[str, type[ImageFile.PyEncoder]] = {} + +# -------------------------------------------------------------------- +# Modes + +_ENDIAN = "<" if sys.byteorder == "little" else ">" + + +def _conv_type_shape(im: Image) -> tuple[tuple[int, ...], str]: + m = ImageMode.getmode(im.mode) + shape: tuple[int, ...] = (im.height, im.width) + extra = len(m.bands) + if extra != 1: + shape += (extra,) + return shape, m.typestr + + +MODES = [ + "1", + "CMYK", + "F", + "HSV", + "I", + "I;16", + "I;16B", + "I;16L", + "I;16N", + "L", + "LA", + "La", + "LAB", + "P", + "PA", + "RGB", + "RGBA", + "RGBa", + "RGBX", + "YCbCr", +] + +# raw modes that may be memory mapped. NOTE: if you change this, you +# may have to modify the stride calculation in map.c too! +_MAPMODES = ("L", "P", "RGBX", "RGBA", "CMYK", "I;16", "I;16L", "I;16B") + + +def getmodebase(mode: str) -> str: + """ + Gets the "base" mode for given mode. This function returns "L" for + images that contain grayscale data, and "RGB" for images that + contain color data. + + :param mode: Input mode. + :returns: "L" or "RGB". + :exception KeyError: If the input mode was not a standard mode. + """ + return ImageMode.getmode(mode).basemode + + +def getmodetype(mode: str) -> str: + """ + Gets the storage type mode. Given a mode, this function returns a + single-layer mode suitable for storing individual bands. + + :param mode: Input mode. + :returns: "L", "I", or "F". + :exception KeyError: If the input mode was not a standard mode. + """ + return ImageMode.getmode(mode).basetype + + +def getmodebandnames(mode: str) -> tuple[str, ...]: + """ + Gets a list of individual band names. Given a mode, this function returns + a tuple containing the names of individual bands (use + :py:method:`~PIL.Image.getmodetype` to get the mode used to store each + individual band. + + :param mode: Input mode. + :returns: A tuple containing band names. The length of the tuple + gives the number of bands in an image of the given mode. + :exception KeyError: If the input mode was not a standard mode. + """ + return ImageMode.getmode(mode).bands + + +def getmodebands(mode: str) -> int: + """ + Gets the number of individual bands for this mode. + + :param mode: Input mode. + :returns: The number of bands in this mode. + :exception KeyError: If the input mode was not a standard mode. + """ + return len(ImageMode.getmode(mode).bands) + + +# -------------------------------------------------------------------- +# Helpers + +_initialized = 0 + +# Mapping from file extension to plugin module name for lazy importing +_EXTENSION_PLUGIN: dict[str, str] = { + # Common formats (preinit) + ".bmp": "BmpImagePlugin", + ".dib": "BmpImagePlugin", + ".gif": "GifImagePlugin", + ".jfif": "JpegImagePlugin", + ".jpe": "JpegImagePlugin", + ".jpg": "JpegImagePlugin", + ".jpeg": "JpegImagePlugin", + ".pbm": "PpmImagePlugin", + ".pgm": "PpmImagePlugin", + ".pnm": "PpmImagePlugin", + ".ppm": "PpmImagePlugin", + ".pfm": "PpmImagePlugin", + ".png": "PngImagePlugin", + ".apng": "PngImagePlugin", + # Less common formats (init) + ".avif": "AvifImagePlugin", + ".avifs": "AvifImagePlugin", + ".blp": "BlpImagePlugin", + ".bufr": "BufrStubImagePlugin", + ".cur": "CurImagePlugin", + ".dcx": "DcxImagePlugin", + ".dds": "DdsImagePlugin", + ".ps": "EpsImagePlugin", + ".eps": "EpsImagePlugin", + ".fit": "FitsImagePlugin", + ".fits": "FitsImagePlugin", + ".fli": "FliImagePlugin", + ".flc": "FliImagePlugin", + ".fpx": "FpxImagePlugin", + ".ftc": "FtexImagePlugin", + ".ftu": "FtexImagePlugin", + ".gbr": "GbrImagePlugin", + ".grib": "GribStubImagePlugin", + ".h5": "Hdf5StubImagePlugin", + ".hdf": "Hdf5StubImagePlugin", + ".icns": "IcnsImagePlugin", + ".ico": "IcoImagePlugin", + ".im": "ImImagePlugin", + ".iim": "IptcImagePlugin", + ".jp2": "Jpeg2KImagePlugin", + ".j2k": "Jpeg2KImagePlugin", + ".jpc": "Jpeg2KImagePlugin", + ".jpf": "Jpeg2KImagePlugin", + ".jpx": "Jpeg2KImagePlugin", + ".j2c": "Jpeg2KImagePlugin", + ".mic": "MicImagePlugin", + ".mpg": "MpegImagePlugin", + ".mpeg": "MpegImagePlugin", + ".mpo": "MpoImagePlugin", + ".msp": "MspImagePlugin", + ".palm": "PalmImagePlugin", + ".pcd": "PcdImagePlugin", + ".pcx": "PcxImagePlugin", + ".pdf": "PdfImagePlugin", + ".pxr": "PixarImagePlugin", + ".psd": "PsdImagePlugin", + ".qoi": "QoiImagePlugin", + ".bw": "SgiImagePlugin", + ".rgb": "SgiImagePlugin", + ".rgba": "SgiImagePlugin", + ".sgi": "SgiImagePlugin", + ".ras": "SunImagePlugin", + ".tga": "TgaImagePlugin", + ".icb": "TgaImagePlugin", + ".vda": "TgaImagePlugin", + ".vst": "TgaImagePlugin", + ".tif": "TiffImagePlugin", + ".tiff": "TiffImagePlugin", + ".webp": "WebPImagePlugin", + ".wmf": "WmfImagePlugin", + ".emf": "WmfImagePlugin", + ".xbm": "XbmImagePlugin", + ".xpm": "XpmImagePlugin", +} + + +def _import_plugin_for_extension(ext: str | bytes) -> bool: + """Import only the plugin needed for a specific file extension.""" + if not ext: + return False + + if isinstance(ext, bytes): + ext = ext.decode() + ext = ext.lower() + if ext in EXTENSION: + return True + + plugin = _EXTENSION_PLUGIN.get(ext) + if plugin is None: + return False + + try: + logger.debug("Importing %s", plugin) + __import__(f"{__spec__.parent}.{plugin}", globals(), locals(), []) + return True + except ImportError as e: + logger.debug("Image: failed to import %s: %s", plugin, e) + return False + + +def preinit() -> None: + """ + Explicitly loads BMP, GIF, JPEG, PPM and PNG file format drivers. + + It is called when opening or saving images. + """ + + global _initialized + if _initialized >= 1: + return + + try: + from . import BmpImagePlugin + + assert BmpImagePlugin + except ImportError: + pass + try: + from . import GifImagePlugin + + assert GifImagePlugin + except ImportError: + pass + try: + from . import JpegImagePlugin + + assert JpegImagePlugin + except ImportError: + pass + try: + from . import PpmImagePlugin + + assert PpmImagePlugin + except ImportError: + pass + try: + from . import PngImagePlugin + + assert PngImagePlugin + except ImportError: + pass + + _initialized = 1 + + +def init() -> bool: + """ + Explicitly initializes the Python Imaging Library. This function + loads all available file format drivers. + + It is called when opening or saving images if :py:meth:`~preinit()` is + insufficient, and by :py:meth:`~PIL.features.pilinfo`. + """ + + global _initialized + if _initialized >= 2: + return False + + for plugin in _plugins: + try: + logger.debug("Importing %s", plugin) + __import__(f"{__spec__.parent}.{plugin}", globals(), locals(), []) + except ImportError as e: # noqa: PERF203 + logger.debug("Image: failed to import %s: %s", plugin, e) + + if OPEN or SAVE: + _initialized = 2 + return True + return False + + +# -------------------------------------------------------------------- +# Codec factories (used by tobytes/frombytes and ImageFile.load) + + +def _getdecoder( + mode: str, decoder_name: str, args: Any, extra: tuple[Any, ...] = () +) -> core.ImagingDecoder | ImageFile.PyDecoder: + # tweak arguments + if args is None: + args = () + elif not isinstance(args, tuple): + args = (args,) + + try: + decoder = DECODERS[decoder_name] + except KeyError: + pass + else: + return decoder(mode, *args + extra) + + try: + # get decoder + decoder = getattr(core, f"{decoder_name}_decoder") + except AttributeError as e: + msg = f"decoder {decoder_name} not available" + raise OSError(msg) from e + return decoder(mode, *args + extra) + + +def _getencoder( + mode: str, encoder_name: str, args: Any, extra: tuple[Any, ...] = () +) -> core.ImagingEncoder | ImageFile.PyEncoder: + # tweak arguments + if args is None: + args = () + elif not isinstance(args, tuple): + args = (args,) + + try: + encoder = ENCODERS[encoder_name] + except KeyError: + pass + else: + return encoder(mode, *args + extra) + + try: + # get encoder + encoder = getattr(core, f"{encoder_name}_encoder") + except AttributeError as e: + msg = f"encoder {encoder_name} not available" + raise OSError(msg) from e + return encoder(mode, *args + extra) + + +# -------------------------------------------------------------------- +# Simple expression analyzer + + +class ImagePointTransform: + """ + Used with :py:meth:`~PIL.Image.Image.point` for single band images with more than + 8 bits, this represents an affine transformation, where the value is multiplied by + ``scale`` and ``offset`` is added. + """ + + def __init__(self, scale: float, offset: float) -> None: + self.scale = scale + self.offset = offset + + def __neg__(self) -> ImagePointTransform: + return ImagePointTransform(-self.scale, -self.offset) + + def __add__(self, other: ImagePointTransform | float) -> ImagePointTransform: + if isinstance(other, ImagePointTransform): + return ImagePointTransform( + self.scale + other.scale, self.offset + other.offset + ) + return ImagePointTransform(self.scale, self.offset + other) + + __radd__ = __add__ + + def __sub__(self, other: ImagePointTransform | float) -> ImagePointTransform: + return self + -other + + def __rsub__(self, other: ImagePointTransform | float) -> ImagePointTransform: + return other + -self + + def __mul__(self, other: ImagePointTransform | float) -> ImagePointTransform: + if isinstance(other, ImagePointTransform): + return NotImplemented + return ImagePointTransform(self.scale * other, self.offset * other) + + __rmul__ = __mul__ + + def __truediv__(self, other: ImagePointTransform | float) -> ImagePointTransform: + if isinstance(other, ImagePointTransform): + return NotImplemented + return ImagePointTransform(self.scale / other, self.offset / other) + + +def _getscaleoffset( + expr: Callable[[ImagePointTransform], ImagePointTransform | float], +) -> tuple[float, float]: + a = expr(ImagePointTransform(1, 0)) + return (a.scale, a.offset) if isinstance(a, ImagePointTransform) else (0, a) + + +# -------------------------------------------------------------------- +# Implementation wrapper + + +class SupportsGetData(Protocol): + def getdata( + self, + ) -> tuple[Transform, Sequence[int]]: ... + + +class Image: + """ + This class represents an image object. To create + :py:class:`~PIL.Image.Image` objects, use the appropriate factory + functions. There's hardly ever any reason to call the Image constructor + directly. + + * :py:func:`~PIL.Image.open` + * :py:func:`~PIL.Image.new` + * :py:func:`~PIL.Image.frombytes` + """ + + format: str | None = None + format_description: str | None = None + _close_exclusive_fp_after_loading = True + + def __init__(self) -> None: + # FIXME: take "new" parameters / other image? + self._im: core.ImagingCore | DeferredError | None = None + self._mode = "" + self._size = (0, 0) + self.palette: ImagePalette.ImagePalette | None = None + self.info: dict[str | tuple[int, int], Any] = {} + self.readonly = 0 + self._exif: Exif | None = None + + @property + def im(self) -> core.ImagingCore: + if isinstance(self._im, DeferredError): + raise self._im.ex + assert self._im is not None + return self._im + + @im.setter + def im(self, im: core.ImagingCore) -> None: + self._im = im + + @property + def width(self) -> int: + return self.size[0] + + @property + def height(self) -> int: + return self.size[1] + + @property + def size(self) -> tuple[int, int]: + return self._size + + @property + def mode(self) -> str: + return self._mode + + @property + def readonly(self) -> int: + return (self._im and self._im.readonly) or self._readonly + + @readonly.setter + def readonly(self, readonly: int) -> None: + self._readonly = readonly + + def _new(self, im: core.ImagingCore) -> Image: + new = Image() + new.im = im + new._mode = im.mode + new._size = im.size + if im.mode in ("P", "PA"): + if self.palette: + new.palette = self.palette.copy() + else: + from . import ImagePalette + + new.palette = ImagePalette.ImagePalette() + new.info = self.info.copy() + return new + + # Context manager support + def __enter__(self) -> Image: + return self + + def __exit__(self, *args: object) -> None: + pass + + def close(self) -> None: + """ + This operation will destroy the image core and release its memory. + The image data will be unusable afterward. + + This function is required to close images that have multiple frames or + have not had their file read and closed by the + :py:meth:`~PIL.Image.Image.load` method. See :ref:`file-handling` for + more information. + """ + if getattr(self, "map", None): + if sys.platform == "win32" and hasattr(sys, "pypy_version_info"): + self.map.close() + self.map: mmap.mmap | None = None + + # Instead of simply setting to None, we're setting up a + # deferred error that will better explain that the core image + # object is gone. + self._im = DeferredError(ValueError("Operation on closed image")) + + def _copy(self) -> None: + self.load() + self.im = self.im.copy() + self.readonly = 0 + + def _ensure_mutable(self) -> None: + if self.readonly: + self._copy() + else: + self.load() + + def _dump( + self, file: str | None = None, format: str | None = None, **options: Any + ) -> str: + suffix = f".{format}" if format else "" + + if file: + filename = file + if not filename.endswith(suffix): + filename += suffix + else: + f, filename = tempfile.mkstemp(suffix) + os.close(f) + + self.save(filename, format or "PPM", **options) + + return filename + + def __eq__(self, other: object) -> bool: + if self.__class__ is not other.__class__: + return False + assert isinstance(other, Image) + return ( + self.mode == other.mode + and self.size == other.size + and self.info == other.info + and self.getpalette() == other.getpalette() + and self.tobytes() == other.tobytes() + ) + + def __repr__(self) -> str: + return ( + f"<{self.__class__.__module__}.{self.__class__.__name__} " + f"image mode={self.mode} size={self.size[0]}x{self.size[1]} " + f"at 0x{id(self):X}>" + ) + + def _repr_pretty_(self, p: PrettyPrinter, cycle: bool) -> None: + """IPython plain text display support""" + + # Same as __repr__ but without unpredictable id(self), + # to keep Jupyter notebook `text/plain` output stable. + p.text( + f"<{self.__class__.__module__}.{self.__class__.__name__} " + f"image mode={self.mode} size={self.size[0]}x{self.size[1]}>" + ) + + def _repr_image(self, image_format: str, **kwargs: Any) -> bytes | None: + """Helper function for iPython display hook. + + :param image_format: Image format. + :returns: image as bytes, saved into the given format. + """ + b = io.BytesIO() + try: + self.save(b, image_format, **kwargs) + except Exception: + return None + return b.getvalue() + + def _repr_png_(self) -> bytes | None: + """iPython display hook support for PNG format. + + :returns: PNG version of the image as bytes + """ + return self._repr_image("PNG", compress_level=1) + + def _repr_jpeg_(self) -> bytes | None: + """iPython display hook support for JPEG format. + + :returns: JPEG version of the image as bytes + """ + return self._repr_image("JPEG") + + @property + def __array_interface__(self) -> dict[str, str | bytes | int | tuple[int, ...]]: + # numpy array interface support + new: dict[str, str | bytes | int | tuple[int, ...]] = {"version": 3} + if self.mode == "1": + # Binary images need to be extended from bits to bytes + # See: https://github.com/python-pillow/Pillow/issues/350 + new["data"] = self.tobytes("raw", "L") + else: + new["data"] = self.tobytes() + new["shape"], new["typestr"] = _conv_type_shape(self) + return new + + def __arrow_c_schema__(self) -> object: + self.load() + return self.im.__arrow_c_schema__() + + def __arrow_c_array__( + self, requested_schema: object | None = None + ) -> tuple[object, object]: + self.load() + return (self.im.__arrow_c_schema__(), self.im.__arrow_c_array__()) + + def __getstate__(self) -> list[Any]: + im_data = self.tobytes() # load image first + return [self.info, self.mode, self.size, self.getpalette(), im_data] + + def __setstate__(self, state: list[Any]) -> None: + Image.__init__(self) + info, mode, size, palette, data = state[:5] + self.info = info + self._mode = mode + self._size = size + self.im = core.new(mode, size) + if mode in ("L", "LA", "P", "PA") and palette: + self.putpalette(palette) + self.frombytes(data) + + def tobytes(self, encoder_name: str = "raw", *args: Any) -> bytes: + """ + Return image as a bytes object. + + .. warning:: + + This method returns raw image data derived from Pillow's internal + storage. For compressed image data (e.g. PNG, JPEG) use + :meth:`~.save`, with a BytesIO parameter for in-memory data. + + :param encoder_name: What encoder to use. + + The default is to use the standard "raw" encoder. + To see how this packs pixel data into the returned + bytes, see :file:`libImaging/Pack.c`. + + A list of C encoders can be seen under codecs + section of the function array in + :file:`_imaging.c`. Python encoders are registered + within the relevant plugins. + :param args: Extra arguments to the encoder. + :returns: A :py:class:`bytes` object. + """ + + encoder_args: Any = args + if len(encoder_args) == 1 and isinstance(encoder_args[0], tuple): + # may pass tuple instead of argument list + encoder_args = encoder_args[0] + + if encoder_name == "raw" and encoder_args == (): + encoder_args = self.mode + + self.load() + + if self.width == 0 or self.height == 0: + return b"" + + # unpack data + e = _getencoder(self.mode, encoder_name, encoder_args) + e.setimage(self.im, (0, 0) + self.size) + + from . import ImageFile + + bufsize = max(ImageFile.MAXBLOCK, self.size[0] * 4) # see RawEncode.c + + output = [] + while True: + bytes_consumed, errcode, data = e.encode(bufsize) + output.append(data) + if errcode: + break + if errcode < 0: + msg = f"encoder error {errcode} in tobytes" + raise RuntimeError(msg) + + return b"".join(output) + + def tobitmap(self, name: str = "image") -> bytes: + """ + Returns the image converted to an X11 bitmap. + + .. note:: This method only works for mode "1" images. + + :param name: The name prefix to use for the bitmap variables. + :returns: A string containing an X11 bitmap. + :raises ValueError: If the mode is not "1" + """ + + self.load() + if self.mode != "1": + msg = "not a bitmap" + raise ValueError(msg) + data = self.tobytes("xbm") + return b"".join( + [ + f"#define {name}_width {self.size[0]}\n".encode("ascii"), + f"#define {name}_height {self.size[1]}\n".encode("ascii"), + f"static char {name}_bits[] = {{\n".encode("ascii"), + data, + b"};", + ] + ) + + def frombytes( + self, + data: DecoderInput, + decoder_name: str = "raw", + *args: Any, + ) -> None: + """ + Loads this image with pixel data from a bytes object. + + This method is similar to the :py:func:`~PIL.Image.frombytes` function, + but loads data into this image instead of creating a new image object. + """ + + if self.width == 0 or self.height == 0: + return + + decoder_args: Any = args + if len(decoder_args) == 1 and isinstance(decoder_args[0], tuple): + # may pass tuple instead of argument list + decoder_args = decoder_args[0] + + if decoder_args and decoder_args[0] in {"P;2L", "P;4L"}: + multiple = 4 if decoder_args[0] == "P;2L" else 8 + if len(data) % multiple: + msg = "not enough image data" + raise ValueError(msg) + + # default format + if decoder_name == "raw" and decoder_args == (): + decoder_args = self.mode + + # unpack data + d = _getdecoder(self.mode, decoder_name, decoder_args) + d.setimage(self.im, (0, 0) + self.size) + s = d.decode(data) + + if s[0] >= 0: + msg = "not enough image data" + raise ValueError(msg) + if s[1] != 0: + msg = "cannot decode image data" + raise ValueError(msg) + + def load(self) -> core.PixelAccess | None: + """ + Allocates storage for the image and loads the pixel data. In + normal cases, you don't need to call this method, since the + Image class automatically loads an opened image when it is + accessed for the first time. + + If the file associated with the image was opened by Pillow, then this + method will close it. The exception to this is if the image has + multiple frames, in which case the file will be left open for seek + operations. See :ref:`file-handling` for more information. + + :returns: An image access object. + :rtype: :py:class:`.PixelAccess` + """ + if self._im is not None and self.palette and self.palette.dirty: + # realize palette + mode, arr = self.palette.getdata() + self.im.putpalette(self.palette.mode, mode, arr) + self.palette.dirty = 0 + self.palette.rawmode = None + if "transparency" in self.info and mode in ("LA", "PA"): + if isinstance(self.info["transparency"], int): + self.im.putpalettealpha(self.info["transparency"], 0) + else: + self.im.putpalettealphas(self.info["transparency"]) + self.palette.mode = "RGBA" + elif self.palette.mode != mode: + # If the palette rawmode is different to the mode, + # then update the Python palette data + self.palette.palette = self.im.getpalette( + self.palette.mode, self.palette.mode + ) + + if self._im is not None: + return self.im.pixel_access(self.readonly) + return None + + def verify(self) -> None: + """ + Verifies the contents of a file. For data read from a file, this + method attempts to determine if the file is broken, without + actually decoding the image data. If this method finds any + problems, it raises suitable exceptions. If you need to load + the image after using this method, you must reopen the image + file. + """ + pass + + def convert( + self, + mode: str | None = None, + matrix: tuple[float, ...] | None = None, + dither: Dither | None = None, + palette: Palette = Palette.WEB, + colors: int = 256, + ) -> Image: + """ + Returns a converted copy of this image. For the "P" mode, this + method translates pixels through the palette. If mode is + omitted, a mode is chosen so that all information in the image + and the palette can be represented without a palette. + + This supports all possible conversions between "L", "RGB" and "CMYK". The + ``matrix`` argument only supports "L" and "RGB". + + When translating a color image to grayscale (mode "L"), + the library uses the ITU-R 601-2 luma transform:: + + L = R * 299/1000 + G * 587/1000 + B * 114/1000 + + The default method of converting a grayscale ("L") or "RGB" + image into a bilevel (mode "1") image uses Floyd-Steinberg + dither to approximate the original image luminosity levels. If + dither is ``None``, all values larger than 127 are set to 255 (white), + all other values to 0 (black). To use other thresholds, use the + :py:meth:`~PIL.Image.Image.point` method. + + When converting from "RGBA" to "P" without a ``matrix`` argument, + this passes the operation to :py:meth:`~PIL.Image.Image.quantize`, + and ``dither`` and ``palette`` are ignored. + + When converting from "PA", if an "RGBA" palette is present, the alpha + channel from the image will be used instead of the values from the palette. + + :param mode: The requested mode. See: :ref:`concept-modes`. + :param matrix: An optional conversion matrix. If given, this + should be 4- or 12-tuple containing floating point values. + :param dither: Dithering method, used when converting from + mode "RGB" to "P" or from "RGB" or "L" to "1". + Available methods are :data:`Dither.NONE` or :data:`Dither.FLOYDSTEINBERG` + (default). Note that this is not used when ``matrix`` is supplied. + :param palette: Palette to use when converting from mode "RGB" + to "P". Available palettes are :data:`Palette.WEB` or + :data:`Palette.ADAPTIVE`. + :param colors: Number of colors to use for the :data:`Palette.ADAPTIVE` + palette. Defaults to 256. + :rtype: :py:class:`~PIL.Image.Image` + :returns: An :py:class:`~PIL.Image.Image` object. + """ + + self.load() + + has_transparency = "transparency" in self.info + if not mode and self.mode == "P": + # determine default mode + if self.palette: + mode = self.palette.mode + else: + mode = "RGB" + if mode == "RGB" and has_transparency: + mode = "RGBA" + if not mode or (mode == self.mode and not matrix): + return self.copy() + + if matrix: + # matrix conversion + if mode not in ("L", "RGB"): + msg = "illegal conversion" + raise ValueError(msg) + im = self.im.convert_matrix(mode, matrix) + new_im = self._new(im) + if has_transparency and self.im.bands == 3: + transparency = new_im.info["transparency"] + + def convert_transparency( + m: tuple[float, ...], v: tuple[int, int, int] + ) -> int: + value = m[0] * v[0] + m[1] * v[1] + m[2] * v[2] + m[3] * 0.5 + return max(0, min(255, int(value))) + + if mode == "L": + transparency = convert_transparency(matrix, transparency) + elif len(mode) == 3: + transparency = tuple( + convert_transparency(matrix[i * 4 : i * 4 + 4], transparency) + for i in range(len(transparency)) + ) + new_im.info["transparency"] = transparency + return new_im + + if self.mode == "RGBA": + if mode == "P": + return self.quantize(colors) + elif mode == "PA": + r, g, b, a = self.split() + rgb = merge("RGB", (r, g, b)) + p = rgb.quantize(colors) + return merge("PA", (p, a)) + + trns = None + delete_trns = False + # transparency handling + if has_transparency: + if (self.mode in ("1", "L", "I", "I;16") and mode in ("LA", "RGBA")) or ( + self.mode == "RGB" and mode in ("La", "LA", "RGBa", "RGBA") + ): + # Use transparent conversion to promote from transparent + # color to an alpha channel. + new_im = self._new( + self.im.convert_transparent(mode, self.info["transparency"]) + ) + del new_im.info["transparency"] + return new_im + elif self.mode in ("L", "RGB", "P") and mode in ("L", "RGB", "P"): + t = self.info["transparency"] + if isinstance(t, bytes): + # Dragons. This can't be represented by a single color + warnings.warn( + "Palette images with Transparency expressed in bytes should be " + "converted to RGBA images" + ) + delete_trns = True + else: + # get the new transparency color. + # use existing conversions + trns_im = new(self.mode, (1, 1)) + if self.mode == "P": + assert self.palette is not None + trns_im.putpalette(self.palette, self.palette.mode) + if isinstance(t, tuple): + err = "Couldn't allocate a palette color for transparency" + assert trns_im.palette is not None + try: + t = trns_im.palette.getcolor(t, self) + except ValueError as e: + if str(e) == "cannot allocate more than 256 colors": + # If all 256 colors are in use, + # then there is no need for transparency + t = None + else: + raise ValueError(err) from e + if t is None: + trns = None + else: + trns_im.putpixel((0, 0), t) + + if mode in ("L", "RGB"): + trns_im = trns_im.convert(mode) + else: + # can't just retrieve the palette number, got to do it + # after quantization. + trns_im = trns_im.convert("RGB") + trns = trns_im.getpixel((0, 0)) + + elif self.mode == "P" and mode in ("LA", "PA", "RGBA"): + t = self.info["transparency"] + delete_trns = True + + if isinstance(t, bytes): + self.im.putpalettealphas(t) + elif isinstance(t, int): + self.im.putpalettealpha(t, 0) + else: + msg = "Transparency for P mode should be bytes or int" + raise ValueError(msg) + + if mode == "P" and palette == Palette.ADAPTIVE: + im = self.im.quantize(colors) + new_im = self._new(im) + from . import ImagePalette + + new_im.palette = ImagePalette.ImagePalette( + "RGB", new_im.im.getpalette("RGB") + ) + if delete_trns: + # This could possibly happen if we requantize to fewer colors. + # The transparency would be totally off in that case. + del new_im.info["transparency"] + if trns is not None: + try: + new_im.info["transparency"] = new_im.palette.getcolor( + cast(tuple[int, ...], trns), # trns was converted to RGB + new_im, + ) + except Exception: + # if we can't make a transparent color, don't leave the old + # transparency hanging around to mess us up. + del new_im.info["transparency"] + warnings.warn("Couldn't allocate palette entry for transparency") + return new_im + + if "LAB" in (self.mode, mode): + im = self + if mode == "LAB": + if im.mode not in ("RGB", "RGBA", "RGBX"): + im = im.convert("RGBA") + other_mode = im.mode + else: + other_mode = mode + if other_mode in ("RGB", "RGBA", "RGBX"): + from . import ImageCms + + srgb = ImageCms.createProfile("sRGB") + lab = ImageCms.createProfile("LAB") + profiles = [lab, srgb] if im.mode == "LAB" else [srgb, lab] + transform = ImageCms.buildTransform( + profiles[0], profiles[1], im.mode, mode + ) + return transform.apply(im) + + # colorspace conversion + if dither is None: + dither = Dither.FLOYDSTEINBERG + + try: + im = self.im.convert(mode, dither) + except ValueError: + try: + # normalize source image and try again + modebase = getmodebase(self.mode) + if modebase == self.mode: + raise + im = self.im.convert(modebase) + im = im.convert(mode, dither) + except KeyError as e: + msg = "illegal conversion" + raise ValueError(msg) from e + + new_im = self._new(im) + if mode in ("P", "PA") and palette != Palette.ADAPTIVE: + from . import ImagePalette + + new_im.palette = ImagePalette.ImagePalette("RGB", im.getpalette("RGB")) + if delete_trns: + # crash fail if we leave a bytes transparency in an rgb/l mode. + del new_im.info["transparency"] + if trns is not None: + if new_im.mode == "P" and new_im.palette: + try: + new_im.info["transparency"] = new_im.palette.getcolor( + cast(tuple[int, ...], trns), new_im # trns was converted to RGB + ) + except ValueError as e: + del new_im.info["transparency"] + if str(e) != "cannot allocate more than 256 colors": + # If all 256 colors are in use, + # then there is no need for transparency + warnings.warn( + "Couldn't allocate palette entry for transparency" + ) + else: + new_im.info["transparency"] = trns + return new_im + + def quantize( + self, + colors: int = 256, + method: int | None = None, + kmeans: int = 0, + palette: Image | None = None, + dither: Dither = Dither.FLOYDSTEINBERG, + ) -> Image: + """ + Convert the image to 'P' mode with the specified number + of colors. + + :param colors: The desired number of colors, <= 256 + :param method: :data:`Quantize.MEDIANCUT` (median cut), + :data:`Quantize.MAXCOVERAGE` (maximum coverage), + :data:`Quantize.FASTOCTREE` (fast octree), + :data:`Quantize.LIBIMAGEQUANT` (libimagequant; check support + using :py:func:`PIL.features.check_feature` with + ``feature="libimagequant"``). + + By default, :data:`Quantize.MEDIANCUT` will be used. + + The exception to this is RGBA images. :data:`Quantize.MEDIANCUT` + and :data:`Quantize.MAXCOVERAGE` do not support RGBA images, so + :data:`Quantize.FASTOCTREE` is used by default instead. + :param kmeans: Integer greater than or equal to zero. + :param palette: Quantize to the palette of given + :py:class:`PIL.Image.Image`. + :param dither: Dithering method, used when converting from + mode "RGB" to "P" or from "RGB" or "L" to "1". + Available methods are :data:`Dither.NONE` or :data:`Dither.FLOYDSTEINBERG` + (default). + :returns: A new image + """ + + self.load() + + if method is None: + # defaults: + method = Quantize.MEDIANCUT + if self.mode == "RGBA": + method = Quantize.FASTOCTREE + + if self.mode == "RGBA" and method not in ( + Quantize.FASTOCTREE, + Quantize.LIBIMAGEQUANT, + ): + # Caller specified an invalid mode. + msg = ( + "Fast Octree (method == 2) and libimagequant (method == 3) " + "are the only valid methods for quantizing RGBA images" + ) + raise ValueError(msg) + + if palette: + # use palette from reference image + palette.load() + if palette.mode != "P": + msg = "bad mode for palette image" + raise ValueError(msg) + if self.mode not in {"RGB", "L"}: + msg = "only RGB or L mode images can be quantized to a palette" + raise ValueError(msg) + im = self.im.convert("P", dither, palette.im) + new_im = self._new(im) + assert palette.palette is not None + new_im.palette = palette.palette.copy() + return new_im + + if kmeans < 0: + msg = "kmeans must not be negative" + raise ValueError(msg) + + im = self._new(self.im.quantize(colors, method, kmeans)) + + from . import ImagePalette + + mode = im.im.getpalettemode() + palette_data = im.im.getpalette(mode, mode)[: colors * len(mode)] + im.palette = ImagePalette.ImagePalette(mode, palette_data) + + return im + + def copy(self) -> Image: + """ + Copies this image. Use this method if you wish to paste things + into an image, but still retain the original. + + :rtype: :py:class:`~PIL.Image.Image` + :returns: An :py:class:`~PIL.Image.Image` object. + """ + self.load() + return self._new(self.im.copy()) + + __copy__ = copy + + def crop(self, box: tuple[float, float, float, float] | None = None) -> Image: + """ + Returns a rectangular region from this image. The box is a + 4-tuple defining the left, upper, right, and lower pixel + coordinate. See :ref:`coordinate-system`. + + Note: Prior to Pillow 3.4.0, this was a lazy operation. + + :param box: The crop rectangle, as a (left, upper, right, lower)-tuple. + :rtype: :py:class:`~PIL.Image.Image` + :returns: An :py:class:`~PIL.Image.Image` object. + """ + + if box is None: + return self.copy() + + if box[2] < box[0]: + msg = "Coordinate 'right' is less than 'left'" + raise ValueError(msg) + elif box[3] < box[1]: + msg = "Coordinate 'lower' is less than 'upper'" + raise ValueError(msg) + + self.load() + return self._new(self._crop(self.im, box)) + + def _crop( + self, im: core.ImagingCore, box: tuple[float, float, float, float] + ) -> core.ImagingCore: + """ + Returns a rectangular region from the core image object im. + + This is equivalent to calling im.crop((x0, y0, x1, y1)), but + includes additional sanity checks. + + :param im: a core image object + :param box: The crop rectangle, as a (left, upper, right, lower)-tuple. + :returns: A core image object. + """ + + x0, y0, x1, y1 = map(int, map(round, box)) + + absolute_values = (abs(x1 - x0), abs(y1 - y0)) + + _decompression_bomb_check(absolute_values) + + return im.crop((x0, y0, x1, y1)) + + def draft( + self, mode: str | None, size: tuple[int, int] | None + ) -> tuple[str, tuple[int, int, float, float]] | None: + """ + Configures the image file loader so it returns a version of the + image that as closely as possible matches the given mode and + size. For example, you can use this method to convert a color + JPEG to grayscale while loading it. + + If any changes are made, returns a tuple with the chosen ``mode`` and + ``box`` with coordinates of the original image within the altered one. + + Note that this method modifies the :py:class:`~PIL.Image.Image` object + in place. If the image has already been loaded, this method has no + effect. + + Note: This method is not implemented for most images. It is + currently implemented only for JPEG and MPO images. + + :param mode: The requested mode. + :param size: The requested size in pixels, as a 2-tuple: + (width, height). + """ + pass + + def filter(self, filter: ImageFilter.Filter | type[ImageFilter.Filter]) -> Image: + """ + Filters this image using the given filter. For a list of + available filters, see the :py:mod:`~PIL.ImageFilter` module. + + :param filter: Filter kernel. + :returns: An :py:class:`~PIL.Image.Image` object.""" + + from . import ImageFilter + + self.load() + + if callable(filter): + filter = filter() + if not hasattr(filter, "filter"): + msg = "filter argument should be ImageFilter.Filter instance or class" + raise TypeError(msg) + + multiband = isinstance(filter, ImageFilter.MultibandFilter) + if self.im.bands == 1 or multiband: + return self._new(filter.filter(self.im)) + + ims = [ + self._new(filter.filter(self.im.getband(c))) for c in range(self.im.bands) + ] + return merge(self.mode, ims) + + def getbands(self) -> tuple[str, ...]: + """ + Returns a tuple containing the name of each band in this image. + For example, ``getbands`` on an RGB image returns ("R", "G", "B"). + + :returns: A tuple containing band names. + :rtype: tuple + """ + return ImageMode.getmode(self.mode).bands + + def getbbox(self, *, alpha_only: bool = True) -> tuple[int, int, int, int] | None: + """ + Calculates the bounding box of the non-zero regions in the + image. + + :param alpha_only: Optional flag, defaulting to ``True``. + If ``True`` and the image has an alpha channel, trim transparent pixels. + Otherwise, trim pixels when all channels are zero. + Keyword-only argument. + :returns: The bounding box is returned as a 4-tuple defining the + left, upper, right, and lower pixel coordinate. See + :ref:`coordinate-system`. If the image is completely empty, this + method returns None. + + """ + + self.load() + return self.im.getbbox(alpha_only) + + def getcolors( + self, maxcolors: int = 256 + ) -> list[tuple[int, tuple[int, ...]]] | list[tuple[int, float]] | None: + """ + Returns a list of colors used in this image. + + The colors will be in the image's mode. For example, an RGB image will + return a tuple of (red, green, blue) color values, and a P image will + return the index of the color in the palette. + + :param maxcolors: Maximum number of colors. If this number is + exceeded, this method returns None. The default limit is + 256 colors. + :returns: An unsorted list of (count, pixel) values. + """ + + self.load() + if self.mode in ("1", "L", "P"): + h = self.im.histogram() + out: list[tuple[int, float]] = [(h[i], i) for i in range(256) if h[i]] + if len(out) > maxcolors: + return None + return out + return self.im.getcolors(maxcolors) + + def getdata(self, band: int | None = None) -> core.ImagingCore: + """ + Returns the contents of this image as a sequence object + containing pixel values. The sequence object is flattened, so + that values for line one follow directly after the values of + line zero, and so on. + + Note that the sequence object returned by this method is an + internal PIL data type, which only supports certain sequence + operations. To convert it to an ordinary sequence (e.g. for + printing), use ``list(im.getdata())``. + + :param band: What band to return. The default is to return + all bands. To return a single band, pass in the index + value (e.g. 0 to get the "R" band from an "RGB" image). + :returns: A sequence-like object. + """ + deprecate("Image.Image.getdata", 14, "get_flattened_data") + + self.load() + if band is not None: + return self.im.getband(band) + return self.im # could be abused + + def get_flattened_data( + self, band: int | None = None + ) -> tuple[tuple[int, ...], ...] | tuple[float, ...]: + """ + Returns the contents of this image as a tuple containing pixel values. + The sequence object is flattened, so that values for line one follow + directly after the values of line zero, and so on. + + :param band: What band to return. The default is to return + all bands. To return a single band, pass in the index + value (e.g. 0 to get the "R" band from an "RGB" image). + :returns: A tuple containing pixel values. + """ + self.load() + if band is not None: + return tuple(self.im.getband(band)) + return tuple(self.im) + + def getextrema(self) -> tuple[float, float] | tuple[tuple[int, int], ...]: + """ + Gets the minimum and maximum pixel values for each band in + the image. + + :returns: For a single-band image, a 2-tuple containing the + minimum and maximum pixel value. For a multi-band image, + a tuple containing one 2-tuple for each band. + """ + + self.load() + if self.im.bands > 1: + return tuple(self.im.getband(i).getextrema() for i in range(self.im.bands)) + return self.im.getextrema() + + def getxmp(self) -> dict[str, Any]: + """ + Returns a dictionary containing the XMP tags. + Requires defusedxml to be installed. + + :returns: XMP tags in a dictionary. + """ + + def get_name(tag: str) -> str: + return re.sub("^{[^}]+}", "", tag) + + def get_value(element: Element) -> str | dict[str, Any] | None: + value: dict[str, Any] = {get_name(k): v for k, v in element.attrib.items()} + children = list(element) + if children: + for child in children: + name = get_name(child.tag) + child_value = get_value(child) + if name in value: + if not isinstance(value[name], list): + value[name] = [value[name]] + value[name].append(child_value) + else: + value[name] = child_value + elif value: + if element.text: + value["text"] = element.text + else: + return element.text + return value + + if ElementTree is None: + warnings.warn("XMP data cannot be read without defusedxml dependency") + return {} + if "xmp" not in self.info: + return {} + root = ElementTree.fromstring(self.info["xmp"].rstrip(b"\x00 ")) + return {get_name(root.tag): get_value(root)} + + def getexif(self) -> Exif: + """ + Gets EXIF data from the image. + + :returns: an :py:class:`~PIL.Image.Exif` object. + """ + if self._exif is None: + self._exif = Exif() + elif self._exif._loaded: + return self._exif + self._exif._loaded = True + + exif_info = self.info.get("exif") + if exif_info is None: + if "Raw profile type exif" in self.info: + exif_info = bytes.fromhex( + "".join(self.info["Raw profile type exif"].split("\n")[3:]) + ) + elif hasattr(self, "tag_v2"): + from . import TiffImagePlugin + + assert isinstance(self, TiffImagePlugin.TiffImageFile) + self._exif.bigtiff = self.tag_v2._bigtiff + self._exif.endian = self.tag_v2._endian + + assert self.fp is not None + self._exif.load_from_fp(self.fp, self.tag_v2._offset) + if exif_info is not None: + self._exif.load(exif_info) + + # XMP tags + if ExifTags.Base.Orientation not in self._exif: + xmp_tags = self.info.get("XML:com.adobe.xmp") + pattern: str | bytes = r'tiff:Orientation(="|>)([0-9])' + if not xmp_tags and (xmp_tags := self.info.get("xmp")): + pattern = rb'tiff:Orientation(="|>)([0-9])' + if xmp_tags: + match = re.search(pattern, xmp_tags) + if match: + self._exif[ExifTags.Base.Orientation] = int(match[2]) + + return self._exif + + def _reload_exif(self) -> None: + if self._exif is None or not self._exif._loaded: + return + self._exif._loaded = False + self.getexif() + + def get_child_images(self) -> list[ImageFile.ImageFile]: + from . import ImageFile + + deprecate("Image.Image.get_child_images", 13) + return ImageFile.ImageFile.get_child_images(self) # type: ignore[arg-type] + + def getim(self) -> CapsuleType: + """ + Returns a capsule that points to the internal image memory. + + :returns: A capsule object. + """ + + self.load() + return self.im.ptr + + def getpalette(self, rawmode: str | None = "RGB") -> list[int] | None: + """ + Returns the image palette as a list. + + :param rawmode: The mode in which to return the palette. ``None`` will + return the palette in its current mode. + + .. versionadded:: 9.1.0 + + :returns: A list of color values [r, g, b, ...], or None if the + image has no palette. + """ + + self.load() + try: + mode = self.im.getpalettemode() + except ValueError: + return None # no palette + if rawmode is None: + rawmode = mode + return list(self.im.getpalette(mode, rawmode)) + + @property + def has_transparency_data(self) -> bool: + """ + Determine if an image has transparency data, whether in the form of an + alpha channel, a palette with an alpha channel, or a "transparency" key + in the info dictionary. + + Note the image might still appear solid, if all of the values shown + within are opaque. + + :returns: A boolean. + """ + if ( + self.mode in ("LA", "La", "PA", "RGBA", "RGBa") + or "transparency" in self.info + ): + return True + if self.mode == "P": + assert self.palette is not None + return self.palette.mode.endswith("A") + return False + + def apply_transparency(self) -> None: + """ + If a P mode image has a "transparency" key in the info dictionary, + remove the key and instead apply the transparency to the palette. + Otherwise, the image is unchanged. + """ + if self.mode != "P" or "transparency" not in self.info: + return + + from . import ImagePalette + + palette = self.getpalette("RGBA") + assert palette is not None + transparency = self.info["transparency"] + if isinstance(transparency, bytes): + for i, alpha in enumerate(transparency): + palette[i * 4 + 3] = alpha + else: + palette[transparency * 4 + 3] = 0 + self.palette = ImagePalette.ImagePalette("RGBA", bytes(palette)) + self.palette.dirty = 1 + + del self.info["transparency"] + + def getpixel( + self, xy: tuple[int, int] | list[int] + ) -> float | tuple[int, ...] | None: + """ + Returns the pixel value at a given position. + + :param xy: The coordinate, given as (x, y). See + :ref:`coordinate-system`. + :returns: The pixel value. If the image is a multi-layer image, + this method returns a tuple. + """ + + self.load() + return self.im.getpixel(tuple(xy)) + + def getprojection(self) -> tuple[list[int], list[int]]: + """ + Get projection to x and y axes + + :returns: Two sequences, indicating where there are non-zero + pixels along the X-axis and the Y-axis, respectively. + """ + + self.load() + x, y = self.im.getprojection() + return list(x), list(y) + + def histogram( + self, mask: Image | None = None, extrema: tuple[float, float] | None = None + ) -> list[int]: + """ + Returns a histogram for the image. The histogram is returned as a + list of pixel counts, one for each pixel value in the source + image. Counts are grouped into 256 bins for each band, even if + the image has more than 8 bits per band. If the image has more + than one band, the histograms for all bands are concatenated (for + example, the histogram for an "RGB" image contains 768 values). + + A bilevel image (mode "1") is treated as a grayscale ("L") image + by this method. + + If a mask is provided, the method returns a histogram for those + parts of the image where the mask image is non-zero. The mask + image must have the same size as the image, and be either a + bi-level image (mode "1") or a grayscale image ("L"). + + :param mask: An optional mask. + :param extrema: An optional tuple of manually-specified extrema. + :returns: A list containing pixel counts. + """ + self.load() + if mask: + mask.load() + return self.im.histogram((0, 0), mask.im) + if self.mode in ("I", "F"): + return self.im.histogram( + extrema if extrema is not None else self.getextrema() + ) + return self.im.histogram() + + def entropy( + self, mask: Image | None = None, extrema: tuple[float, float] | None = None + ) -> float: + """ + Calculates and returns the entropy for the image. + + A bilevel image (mode "1") is treated as a grayscale ("L") + image by this method. + + If a mask is provided, the method employs the histogram for + those parts of the image where the mask image is non-zero. + The mask image must have the same size as the image, and be + either a bi-level image (mode "1") or a grayscale image ("L"). + + :param mask: An optional mask. + :param extrema: An optional tuple of manually-specified extrema. + :returns: A float value representing the image entropy + """ + self.load() + if mask: + mask.load() + return self.im.entropy((0, 0), mask.im) + if self.mode in ("I", "F"): + return self.im.entropy( + extrema if extrema is not None else self.getextrema() + ) + return self.im.entropy() + + def paste( + self, + im: Image | str | float | tuple[float, ...], + box: Image | tuple[int, int, int, int] | tuple[int, int] | None = None, + mask: Image | None = None, + ) -> None: + """ + Pastes another image into this image. The box argument is either + a 2-tuple giving the upper left corner, a 4-tuple defining the + left, upper, right, and lower pixel coordinate, or None (same as + (0, 0)). See :ref:`coordinate-system`. If a 4-tuple is given, the size + of the pasted image must match the size of the region. + + If the modes don't match, the pasted image is converted to the mode of + this image (see the :py:meth:`~PIL.Image.Image.convert` method for + details). + + Instead of an image, the source can be a integer or tuple + containing pixel values. The method then fills the region + with the given color. When creating RGB images, you can + also use color strings as supported by the ImageColor module. See + :ref:`colors` for more information. + + If a mask is given, this method updates only the regions + indicated by the mask. You can use either "1", "L", "LA", "RGBA" + or "RGBa" images (if present, the alpha band is used as mask). + Where the mask is 255, the given image is copied as is. Where + the mask is 0, the current value is preserved. Intermediate + values will mix the two images together, including their alpha + channels if they have them. + + See :py:meth:`~PIL.Image.Image.alpha_composite` if you want to + combine images with respect to their alpha channels. + + :param im: Source image or pixel value (integer, float or tuple). + :param box: An optional 4-tuple giving the region to paste into. + If a 2-tuple is used instead, it's treated as the upper left + corner. If omitted or None, the source is pasted into the + upper left corner. + + If an image is given as the second argument and there is no + third, the box defaults to (0, 0), and the second argument + is interpreted as a mask image. + :param mask: An optional mask image. + """ + + if isinstance(box, Image): + if mask is not None: + msg = "If using second argument as mask, third argument must be None" + raise ValueError(msg) + # abbreviated paste(im, mask) syntax + mask = box + box = None + + if box is None: + box = (0, 0) + + if len(box) == 2: + # upper left corner given; get size from image or mask + if isinstance(im, Image): + size = im.size + elif isinstance(mask, Image): + size = mask.size + else: + # FIXME: use self.size here? + msg = "cannot determine region size; use 4-item box" + raise ValueError(msg) + box += (box[0] + size[0], box[1] + size[1]) + + source: core.ImagingCore | str | float | tuple[float, ...] + if isinstance(im, str): + from . import ImageColor + + source = ImageColor.getcolor(im, self.mode) + elif isinstance(im, Image): + im.load() + if self.mode != im.mode: + if self.mode != "RGB" or im.mode not in ("LA", "RGBA", "RGBa"): + # should use an adapter for this! + im = im.convert(self.mode) + source = im.im + else: + source = im + + self._ensure_mutable() + + if mask: + mask.load() + self.im.paste(source, box, mask.im) + else: + self.im.paste(source, box) + + def alpha_composite( + self, im: Image, dest: Sequence[int] = (0, 0), source: Sequence[int] = (0, 0) + ) -> None: + """'In-place' analog of Image.alpha_composite. Composites an image + onto this image. + + :param im: image to composite over this one + :param dest: Optional 2 tuple (left, top) specifying the upper + left corner in this (destination) image. + :param source: Optional 2 (left, top) tuple for the upper left + corner in the overlay source image, or 4 tuple (left, top, right, + bottom) for the bounds of the source rectangle + + Performance Note: Not currently implemented in-place in the core layer. + """ + + if not isinstance(source, (list, tuple)): + msg = "Source must be a list or tuple" + raise ValueError(msg) + if not isinstance(dest, (list, tuple)): + msg = "Destination must be a list or tuple" + raise ValueError(msg) + + if len(source) == 4: + overlay_crop_box = tuple(source) + elif len(source) == 2: + overlay_crop_box = tuple(source) + im.size + else: + msg = "Source must be a sequence of length 2 or 4" + raise ValueError(msg) + + if not len(dest) == 2: + msg = "Destination must be a sequence of length 2" + raise ValueError(msg) + if min(source) < 0: + msg = "Source must be non-negative" + raise ValueError(msg) + + # over image, crop if it's not the whole image. + if overlay_crop_box == (0, 0) + im.size: + overlay = im + else: + overlay = im.crop(overlay_crop_box) + + # target for the paste + box = tuple(dest) + (dest[0] + overlay.width, dest[1] + overlay.height) + + # destination image. don't copy if we're using the whole image. + if box == (0, 0) + self.size: + background = self + else: + background = self.crop(box) + + result = alpha_composite(background, overlay) + self.paste(result, box) + + def point( + self, + lut: ( + Sequence[float] + | NumpyArray + | Callable[[int], float] + | Callable[[ImagePointTransform], ImagePointTransform | float] + | ImagePointHandler + ), + mode: str | None = None, + ) -> Image: + """ + Maps this image through a lookup table or function. + + :param lut: A lookup table, containing 256 (or 65536 if + self.mode=="I" and mode == "L") values per band in the + image. A function can be used instead, it should take a + single argument. The function is called once for each + possible pixel value, and the resulting table is applied to + all bands of the image. + + It may also be an :py:class:`~PIL.Image.ImagePointHandler` + object:: + + class Example(Image.ImagePointHandler): + def point(self, im: Image) -> Image: + # Return result + :param mode: Output mode (default is same as input). This can only be used if + the source image has mode "L" or "P", and the output has mode "1" or the + source image mode is "I" and the output mode is "L". + :returns: An :py:class:`~PIL.Image.Image` object. + """ + + self.load() + + if isinstance(lut, ImagePointHandler): + return lut.point(self) + + if callable(lut): + # if it isn't a list, it should be a function + if self.mode in ("I", "I;16", "F"): + # check if the function can be used with point_transform + # UNDONE wiredfool -- I think this prevents us from ever doing + # a gamma function point transform on > 8bit images. + scale, offset = _getscaleoffset(lut) # type: ignore[arg-type] + return self._new(self.im.point_transform(scale, offset)) + # for other modes, convert the function to a table + flatLut = [lut(i) for i in range(256)] * self.im.bands # type: ignore[arg-type] + else: + flatLut = lut + + if self.mode == "F": + # FIXME: _imaging returns a confusing error message for this case + msg = "point operation not supported for this mode" + raise ValueError(msg) + + if mode != "F": + flatLut = [round(i) for i in flatLut] + return self._new(self.im.point(flatLut, mode)) + + def putalpha(self, alpha: Image | int) -> None: + """ + Adds or replaces the alpha layer in this image. If the image + does not have an alpha layer, it's converted to "LA" or "RGBA". + The new layer must be either "L" or "1". + + :param alpha: The new alpha layer. This can either be an "L" or "1" + image having the same size as this image, or an integer. + """ + + self._ensure_mutable() + + if self.mode not in ("LA", "PA", "RGBA"): + # attempt to promote self to a matching alpha mode + try: + mode = getmodebase(self.mode) + "A" + try: + self.im.setmode(mode) + except (AttributeError, ValueError) as e: + # do things the hard way + im = self.im.convert(mode) + if im.mode not in ("LA", "PA", "RGBA"): + msg = "alpha channel could not be added" + raise ValueError(msg) from e # sanity check + self.im = im + self._mode = self.im.mode + except KeyError as e: + msg = "illegal image mode" + raise ValueError(msg) from e + + if self.mode in ("LA", "PA"): + band = 1 + else: + band = 3 + + if isinstance(alpha, Image): + # alpha layer + if alpha.mode not in ("1", "L"): + msg = "illegal image mode" + raise ValueError(msg) + alpha.load() + if alpha.mode == "1": + alpha = alpha.convert("L") + else: + # constant alpha + try: + self.im.fillband(band, alpha) + except (AttributeError, ValueError): + # do things the hard way + alpha = new("L", self.size, alpha) + else: + return + + self.im.putband(alpha.im, band) + + def putdata( + self, + data: Sequence[float] | Sequence[Sequence[int]] | core.ImagingCore | NumpyArray, + scale: float = 1.0, + offset: float = 0.0, + ) -> None: + """ + Copies pixel data from a flattened sequence object into the image. The + values should start at the upper left corner (0, 0), continue to the + end of the line, followed directly by the first value of the second + line, and so on. Data will be read until either the image or the + sequence ends. The scale and offset values are used to adjust the + sequence values: **pixel = value*scale + offset**. + + :param data: A flattened sequence object. See :ref:`colors` for more + information about values. + :param scale: An optional scale value. The default is 1.0. + :param offset: An optional offset value. The default is 0.0. + """ + + self._ensure_mutable() + + self.im.putdata(data, scale, offset) + + def putpalette( + self, + data: ImagePalette.ImagePalette | bytes | Sequence[int], + rawmode: str = "RGB", + ) -> None: + """ + Attaches a palette to this image. The image must be a "P", "PA", "L" + or "LA" image. + + The palette sequence must contain at most 256 colors, made up of one + integer value for each channel in the raw mode. + For example, if the raw mode is "RGB", then it can contain at most 768 + values, made up of red, green and blue values for the corresponding pixel + index in the 256 colors. + If the raw mode is "RGBA", then it can contain at most 1024 values, + containing red, green, blue and alpha values. + + Alternatively, an 8-bit string may be used instead of an integer sequence. + + :param data: A palette sequence (either a list or a string). + :param rawmode: The raw mode of the palette. Either "RGB", "RGBA", "CMYK", or a + mode that can be transformed to one of those modes (e.g. "R", "RGBA;L"). + """ + from . import ImagePalette + + if self.mode not in ("L", "LA", "P", "PA"): + msg = "illegal image mode" + raise ValueError(msg) + if isinstance(data, ImagePalette.ImagePalette): + if data.rawmode is not None: + palette = ImagePalette.raw(data.rawmode, data.palette) + else: + palette = ImagePalette.ImagePalette(palette=data.palette) + palette.dirty = 1 + else: + if not isinstance(data, bytes): + data = bytes(data) + palette = ImagePalette.raw(rawmode, data) + self._mode = "PA" if "A" in self.mode else "P" + self.palette = palette + if rawmode.startswith("CMYK"): + self.palette.mode = "CMYK" + elif "A" in rawmode: + self.palette.mode = "RGBA" + else: + self.palette.mode = "RGB" + self.load() # install new palette + + def putpixel( + self, + xy: tuple[int, int] | list[int], + value: float | tuple[int, ...] | list[int], + ) -> None: + """ + Modifies the pixel at the given position. The color is given as + a single numerical value for single-band images, and a tuple for + multi-band images. In addition to this, RGB and RGBA tuples are + accepted for P and PA images. See :ref:`colors` for more information. + + Note that this method is relatively slow. For more extensive changes, + use :py:meth:`~PIL.Image.Image.paste` or the :py:mod:`~PIL.ImageDraw` + module instead. + + See: + + * :py:meth:`~PIL.Image.Image.paste` + * :py:meth:`~PIL.Image.Image.putdata` + * :py:mod:`~PIL.ImageDraw` + + :param xy: The pixel coordinate, given as (x, y). See + :ref:`coordinate-system`. + :param value: The pixel value. + """ + + self._ensure_mutable() + + if ( + self.mode in ("P", "PA") + and isinstance(value, (list, tuple)) + and len(value) in [3, 4] + ): + # RGB or RGBA value for a P or PA image + if self.mode == "PA": + alpha = value[3] if len(value) == 4 else 255 + value = value[:3] + assert self.palette is not None + palette_index = self.palette.getcolor(tuple(value), self) + value = (palette_index, alpha) if self.mode == "PA" else palette_index + return self.im.putpixel(xy, value) + + def remap_palette( + self, dest_map: list[int], source_palette: bytes | bytearray | None = None + ) -> Image: + """ + Rewrites the image to reorder the palette. + + :param dest_map: A list of indexes into the original palette. + e.g. ``[1,0]`` would swap a two item palette, and ``list(range(256))`` + is the identity transform. + :param source_palette: Bytes or None. + :returns: An :py:class:`~PIL.Image.Image` object. + + """ + from . import ImagePalette + + if self.mode not in ("L", "P"): + msg = "illegal image mode" + raise ValueError(msg) + + bands = 3 + palette_mode = "RGB" + if source_palette is None: + if self.mode == "P": + self.load() + palette_mode = self.im.getpalettemode() + if palette_mode == "RGBA": + bands = 4 + source_palette = self.im.getpalette(palette_mode, palette_mode) + else: # L-mode + source_palette = bytearray(i // 3 for i in range(768)) + elif len(source_palette) > 768: + bands = 4 + palette_mode = "RGBA" + + palette_bytes = b"" + new_positions = [0] * 256 + + # pick only the used colors from the palette + for i, oldPosition in enumerate(dest_map): + palette_bytes += source_palette[ + oldPosition * bands : oldPosition * bands + bands + ] + new_positions[oldPosition] = i + + # replace the palette color id of all pixel with the new id + + # Palette images are [0..255], mapped through a 1 or 3 + # byte/color map. We need to remap the whole image + # from palette 1 to palette 2. New_positions is + # an array of indexes into palette 1. Palette 2 is + # palette 1 with any holes removed. + + # We're going to leverage the convert mechanism to use the + # C code to remap the image from palette 1 to palette 2, + # by forcing the source image into 'L' mode and adding a + # mapping 'L' mode palette, then converting back to 'L' + # sans palette thus converting the image bytes, then + # assigning the optimized RGB palette. + + # perf reference, 9500x4000 gif, w/~135 colors + # 14 sec prepatch, 1 sec postpatch with optimization forced. + + mapping_palette = bytearray(new_positions) + + m_im = self.copy() + m_im._mode = "P" + + m_im.palette = ImagePalette.ImagePalette( + palette_mode, palette=mapping_palette * bands + ) + # possibly set palette dirty, then + # m_im.putpalette(mapping_palette, 'L') # converts to 'P' + # or just force it. + # UNDONE -- this is part of the general issue with palettes + m_im.im.putpalette(palette_mode, palette_mode + ";L", m_im.palette.tobytes()) + + m_im = m_im.convert("L") + + m_im.putpalette(palette_bytes, palette_mode) + m_im.palette = ImagePalette.ImagePalette(palette_mode, palette=palette_bytes) + + if "transparency" in self.info: + try: + m_im.info["transparency"] = dest_map.index(self.info["transparency"]) + except ValueError: + if "transparency" in m_im.info: + del m_im.info["transparency"] + + return m_im + + def _get_safe_box( + self, + size: tuple[int, int], + resample: Resampling, + box: tuple[float, float, float, float], + ) -> tuple[int, int, int, int]: + """Expands the box so it includes adjacent pixels + that may be used by resampling with the given resampling filter. + """ + filter_support = _filters_support[resample] - 0.5 + scale_x = (box[2] - box[0]) / size[0] + scale_y = (box[3] - box[1]) / size[1] + support_x = filter_support * scale_x + support_y = filter_support * scale_y + + return ( + max(0, int(box[0] - support_x)), + max(0, int(box[1] - support_y)), + min(self.size[0], math.ceil(box[2] + support_x)), + min(self.size[1], math.ceil(box[3] + support_y)), + ) + + def resize( + self, + size: tuple[int, int] | list[int] | NumpyArray, + resample: int | None = None, + box: tuple[float, float, float, float] | None = None, + reducing_gap: float | None = None, + ) -> Image: + """ + Returns a resized copy of this image. + + :param size: The requested size in pixels, as a tuple or array: + (width, height). + :param resample: An optional resampling filter. This can be + one of :py:data:`Resampling.NEAREST`, :py:data:`Resampling.BOX`, + :py:data:`Resampling.BILINEAR`, :py:data:`Resampling.HAMMING`, + :py:data:`Resampling.BICUBIC` or :py:data:`Resampling.LANCZOS`. + If the image has mode "1" or "P", it is always set to + :py:data:`Resampling.NEAREST`. Otherwise, the default filter is + :py:data:`Resampling.BICUBIC`. See: :ref:`concept-filters`. + :param box: An optional 4-tuple of floats providing + the source image region to be scaled. + The values must be within (0, 0, width, height) rectangle. + If omitted or None, the entire source is used. + :param reducing_gap: Apply optimization by resizing the image + in two steps. First, reducing the image by integer times + using :py:meth:`~PIL.Image.Image.reduce`. + Second, resizing using regular resampling. The last step + changes size no less than by ``reducing_gap`` times. + ``reducing_gap`` may be None (no first step is performed) + or should be greater than 1.0. The bigger ``reducing_gap``, + the closer the result to the fair resampling. + The smaller ``reducing_gap``, the faster resizing. + With ``reducing_gap`` greater or equal to 3.0, the result is + indistinguishable from fair resampling in most cases. + The default value is None (no optimization). + :returns: An :py:class:`~PIL.Image.Image` object. + """ + + if resample is None: + resample = Resampling.BICUBIC + elif resample not in ( + Resampling.NEAREST, + Resampling.BILINEAR, + Resampling.BICUBIC, + Resampling.LANCZOS, + Resampling.BOX, + Resampling.HAMMING, + ): + msg = f"Unknown resampling filter ({resample})." + + filters = [ + f"{filter[1]} ({filter[0]})" + for filter in ( + (Resampling.NEAREST, "Image.Resampling.NEAREST"), + (Resampling.LANCZOS, "Image.Resampling.LANCZOS"), + (Resampling.BILINEAR, "Image.Resampling.BILINEAR"), + (Resampling.BICUBIC, "Image.Resampling.BICUBIC"), + (Resampling.BOX, "Image.Resampling.BOX"), + (Resampling.HAMMING, "Image.Resampling.HAMMING"), + ) + ] + msg += f" Use {', '.join(filters[:-1])} or {filters[-1]}" + raise ValueError(msg) + + if reducing_gap is not None and reducing_gap < 1.0: + msg = "reducing_gap must be 1.0 or greater" + raise ValueError(msg) + + if box is None: + box = (0, 0) + self.size + + size = tuple(size) + if self.size == size and box == (0, 0) + self.size: + return self.copy() + + if self.mode in ("1", "P"): + resample = Resampling.NEAREST + + if self.mode in ["LA", "RGBA"] and resample != Resampling.NEAREST: + im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) + im = im.resize(size, resample, box) + return im.convert(self.mode) + + self.load() + + if reducing_gap is not None and resample != Resampling.NEAREST: + factor_x = int((box[2] - box[0]) / size[0] / reducing_gap) or 1 + factor_y = int((box[3] - box[1]) / size[1] / reducing_gap) or 1 + if factor_x > 1 or factor_y > 1: + reduce_box = self._get_safe_box(size, cast(Resampling, resample), box) + factor = (factor_x, factor_y) + self = ( + self.reduce(factor, box=reduce_box) + if callable(self.reduce) + else Image.reduce(self, factor, box=reduce_box) + ) + box = ( + (box[0] - reduce_box[0]) / factor_x, + (box[1] - reduce_box[1]) / factor_y, + (box[2] - reduce_box[0]) / factor_x, + (box[3] - reduce_box[1]) / factor_y, + ) + + if self.size[1] > self.size[0] * 100 and size[1] < self.size[1]: + im = self.im.resize( + (self.size[0], size[1]), resample, (0, box[1], self.size[0], box[3]) + ) + im = im.resize(size, resample, (box[0], 0, box[2], size[1])) + else: + im = self.im.resize(size, resample, box) + return self._new(im) + + def reduce( + self, + factor: int | tuple[int, int], + box: tuple[int, int, int, int] | None = None, + ) -> Image: + """ + Returns a copy of the image reduced ``factor`` times. + If the size of the image is not dividable by ``factor``, + the resulting size will be rounded up. + + :param factor: A greater than 0 integer or tuple of two integers + for width and height separately. + :param box: An optional 4-tuple of ints providing + the source image region to be reduced. + The values must be within ``(0, 0, width, height)`` rectangle. + If omitted or ``None``, the entire source is used. + """ + if not isinstance(factor, (list, tuple)): + factor = (factor, factor) + + if box is None: + box = (0, 0) + self.size + + if factor == (1, 1) and box == (0, 0) + self.size: + return self.copy() + + if self.mode in ["LA", "RGBA"]: + im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) + im = im.reduce(factor, box) + return im.convert(self.mode) + + self.load() + + return self._new(self.im.reduce(factor, box)) + + def rotate( + self, + angle: float, + resample: Resampling = Resampling.NEAREST, + expand: int | bool = False, + center: tuple[float, float] | None = None, + translate: tuple[int, int] | None = None, + fillcolor: float | tuple[float, ...] | str | None = None, + ) -> Image: + """ + Returns a rotated copy of this image. This method returns a + copy of this image, rotated the given number of degrees counter + clockwise around its centre. + + :param angle: In degrees counter clockwise. + :param resample: An optional resampling filter. This can be + one of :py:data:`Resampling.NEAREST` (use nearest neighbour), + :py:data:`Resampling.BILINEAR` (linear interpolation in a 2x2 + environment), or :py:data:`Resampling.BICUBIC` (cubic spline + interpolation in a 4x4 environment). If omitted, or if the image has + mode "1" or "P", it is set to :py:data:`Resampling.NEAREST`. + See :ref:`concept-filters`. + :param expand: Optional expansion flag. If true, expands the output + image to make it large enough to hold the entire rotated image. + If false or omitted, make the output image the same size as the + input image. Note that the expand flag assumes rotation around + the center and no translation. + :param center: Optional center of rotation (a 2-tuple). Origin is + the upper left corner. Default is the center of the image. + :param translate: An optional post-rotate translation (a 2-tuple). + :param fillcolor: An optional color for area outside the rotated image. + :returns: An :py:class:`~PIL.Image.Image` object. + """ + + angle = angle % 360.0 + + # Fast paths regardless of filter, as long as we're not + # translating or changing the center. + if not (center or translate): + if angle == 0: + return self.copy() + if angle == 180: + return self.transpose(Transpose.ROTATE_180) + if angle in (90, 270) and (expand or self.width == self.height): + return self.transpose( + Transpose.ROTATE_90 if angle == 90 else Transpose.ROTATE_270 + ) + + # Calculate the affine matrix. Note that this is the reverse + # transformation (from destination image to source) because we + # want to interpolate the (discrete) destination pixel from + # the local area around the (floating) source pixel. + + # The matrix we actually want (note that it operates from the right): + # (1, 0, tx) (1, 0, cx) ( cos a, sin a, 0) (1, 0, -cx) + # (0, 1, ty) * (0, 1, cy) * (-sin a, cos a, 0) * (0, 1, -cy) + # (0, 0, 1) (0, 0, 1) ( 0, 0, 1) (0, 0, 1) + + # The reverse matrix is thus: + # (1, 0, cx) ( cos -a, sin -a, 0) (1, 0, -cx) (1, 0, -tx) + # (0, 1, cy) * (-sin -a, cos -a, 0) * (0, 1, -cy) * (0, 1, -ty) + # (0, 0, 1) ( 0, 0, 1) (0, 0, 1) (0, 0, 1) + + # In any case, the final translation may be updated at the end to + # compensate for the expand flag. + + w, h = self.size + + if translate is None: + post_trans = (0, 0) + else: + post_trans = translate + if center is None: + center = (w / 2, h / 2) + + angle = -math.radians(angle) + matrix = [ + round(math.cos(angle), 15), + round(math.sin(angle), 15), + 0.0, + round(-math.sin(angle), 15), + round(math.cos(angle), 15), + 0.0, + ] + + def transform(x: float, y: float, matrix: list[float]) -> tuple[float, float]: + a, b, c, d, e, f = matrix + return a * x + b * y + c, d * x + e * y + f + + matrix[2], matrix[5] = transform( + -center[0] - post_trans[0], -center[1] - post_trans[1], matrix + ) + matrix[2] += center[0] + matrix[5] += center[1] + + if expand: + # calculate output size + xx = [] + yy = [] + for x, y in ((0, 0), (w, 0), (w, h), (0, h)): + transformed_x, transformed_y = transform(x, y, matrix) + xx.append(transformed_x) + yy.append(transformed_y) + nw = math.ceil(max(xx)) - math.floor(min(xx)) + nh = math.ceil(max(yy)) - math.floor(min(yy)) + + # We multiply a translation matrix from the right. Because of its + # special form, this is the same as taking the image of the + # translation vector as new translation vector. + matrix[2], matrix[5] = transform(-(nw - w) / 2.0, -(nh - h) / 2.0, matrix) + w, h = nw, nh + + return self.transform( + (w, h), Transform.AFFINE, matrix, resample, fillcolor=fillcolor + ) + + def save( + self, fp: StrOrBytesPath | IO[bytes], format: str | None = None, **params: Any + ) -> None: + """ + Saves this image under the given filename. If no format is + specified, the format to use is determined from the filename + extension, if possible. + + Keyword options can be used to provide additional instructions + to the writer. If a writer doesn't recognise an option, it is + silently ignored. The available options are described in the + :doc:`image format documentation + <../handbook/image-file-formats>` for each writer. + + You can use a file object instead of a filename. In this case, + you must always specify the format. The file object must + implement the ``seek``, ``tell``, and ``write`` + methods, and be opened in binary mode. + + :param fp: A filename (string), os.PathLike object or file object. + :param format: Optional format override. If omitted, the + format to use is determined from the filename extension. + If a file object was used instead of a filename, this + parameter should always be used. + :param params: Extra parameters to the image writer. These can also be + set on the image itself through ``encoderinfo``. This is useful when + saving multiple images:: + + # Saving XMP data to a single image + from PIL import Image + red = Image.new("RGB", (1, 1), "#f00") + red.save("out.mpo", xmp=b"test") + + # Saving XMP data to the second frame of an image + from PIL import Image + black = Image.new("RGB", (1, 1)) + red = Image.new("RGB", (1, 1), "#f00") + red.encoderinfo = {"xmp": b"test"} + black.save("out.mpo", save_all=True, append_images=[red]) + :returns: None + :exception ValueError: If the output format could not be determined + from the file name. Use the format option to solve this. + :exception OSError: If the file could not be written. The file + may have been created, and may contain partial data. + """ + + filename: str | bytes = "" + open_fp = False + if is_path(fp): + filename = os.fspath(fp) + open_fp = True + elif fp == sys.stdout and isinstance(sys.stdout, io.TextIOWrapper): + fp = sys.stdout.buffer + if not filename and hasattr(fp, "name") and is_path(fp.name): + # only set the name for metadata purposes + filename = os.fspath(fp.name) + + if format: + preinit() + else: + filename_ext = os.path.splitext(filename)[1].lower() + ext = ( + filename_ext.decode() + if isinstance(filename_ext, bytes) + else filename_ext + ) + + # Try importing only the plugin for this extension first + if not _import_plugin_for_extension(ext): + preinit() + + if ext not in EXTENSION: + init() + try: + format = EXTENSION[ext] + except KeyError as e: + msg = f"unknown file extension: {ext}" + raise ValueError(msg) from e + + from . import ImageFile + + # may mutate self! + if isinstance(self, ImageFile.ImageFile) and os.path.abspath( + filename + ) == os.path.abspath(self.filename): + self._ensure_mutable() + else: + self.load() + + save_all = params.pop("save_all", None) + self._default_encoderinfo = params + encoderinfo = getattr(self, "encoderinfo", {}) + self._attach_default_encoderinfo(self) + self.encoderconfig: tuple[Any, ...] = () + + if format.upper() not in SAVE: + init() + if save_all or ( + save_all is None + and params.get("append_images") + and format.upper() in SAVE_ALL + ): + save_handler = SAVE_ALL[format.upper()] + else: + save_handler = SAVE[format.upper()] + + created = False + if open_fp: + created = not os.path.exists(filename) + if params.get("append", False): + # Open also for reading ("+"), because TIFF save_all + # writer needs to go back and edit the written data. + fp = builtins.open(filename, "r+b") + else: + fp = builtins.open(filename, "w+b") + else: + fp = cast(IO[bytes], fp) + + try: + save_handler(self, fp, filename) + except Exception: + if open_fp: + fp.close() + if created: + try: + os.remove(filename) + except PermissionError: + pass + raise + finally: + self.encoderinfo = encoderinfo + if open_fp: + fp.close() + + def _attach_default_encoderinfo(self, im: Image) -> dict[str, Any]: + encoderinfo = getattr(self, "encoderinfo", {}) + self.encoderinfo = {**im._default_encoderinfo, **encoderinfo} + return encoderinfo + + def seek(self, frame: int) -> None: + """ + Seeks to the given frame in this sequence file. If you seek + beyond the end of the sequence, the method raises an + ``EOFError`` exception. When a sequence file is opened, the + library automatically seeks to frame 0. + + See :py:meth:`~PIL.Image.Image.tell`. + + If defined, :attr:`~PIL.Image.Image.n_frames` refers to the + number of available frames. + + :param frame: Frame number, starting at 0. + :exception EOFError: If the call attempts to seek beyond the end + of the sequence. + """ + + # overridden by file handlers + if frame != 0: + msg = "no more images in file" + raise EOFError(msg) + + def show(self, title: str | None = None) -> None: + """ + Displays this image. This method is mainly intended for debugging purposes. + + This method calls :py:func:`PIL.ImageShow.show` internally. You can use + :py:func:`PIL.ImageShow.register` to override its default behaviour. + + The image is first saved to a temporary file. By default, it will be in + PNG format. + + On Unix, the image is then opened using the **xdg-open**, **display**, + **gm**, **eog** or **xv** utility, depending on which one can be found. + + On macOS, the image is opened with the native Preview application. + + On Windows, the image is opened with the standard PNG display utility. + + :param title: Optional title to use for the image window, where possible. + """ + + from . import ImageShow + + ImageShow.show(self, title) + + def split(self) -> tuple[Image, ...]: + """ + Split this image into individual bands. This method returns a + tuple of individual image bands from an image. For example, + splitting an "RGB" image creates three new images each + containing a copy of one of the original bands (red, green, + blue). + + If you need only one band, :py:meth:`~PIL.Image.Image.getchannel` + method can be more convenient and faster. + + :returns: A tuple containing bands. + """ + + self.load() + if self.im.bands == 1: + return (self.copy(),) + return tuple(map(self._new, self.im.split())) + + def getchannel(self, channel: int | str) -> Image: + """ + Returns an image containing a single channel of the source image. + + :param channel: What channel to return. Could be index + (0 for "R" channel of "RGB") or channel name + ("A" for alpha channel of "RGBA"). + :returns: An image in "L" mode. + + .. versionadded:: 4.3.0 + """ + self.load() + + if isinstance(channel, str): + try: + channel = self.getbands().index(channel) + except ValueError as e: + msg = f'The image has no channel "{channel}"' + raise ValueError(msg) from e + + return self._new(self.im.getband(channel)) + + def tell(self) -> int: + """ + Returns the current frame number. See :py:meth:`~PIL.Image.Image.seek`. + + If defined, :attr:`~PIL.Image.Image.n_frames` refers to the + number of available frames. + + :returns: Frame number, starting with 0. + """ + return 0 + + def thumbnail( + self, + size: tuple[float, float], + resample: Resampling = Resampling.BICUBIC, + reducing_gap: float | None = 2.0, + ) -> None: + """ + Make this image into a thumbnail. This method modifies the + image to contain a thumbnail version of itself, no larger than + the given size. This method calculates an appropriate thumbnail + size to preserve the aspect of the image, calls the + :py:meth:`~PIL.Image.Image.draft` method to configure the file reader + (where applicable), and finally resizes the image. + + Note that this function modifies the :py:class:`~PIL.Image.Image` + object in place. If you need to use the full resolution image as well, + apply this method to a :py:meth:`~PIL.Image.Image.copy` of the original + image. + + :param size: The requested size in pixels, as a 2-tuple: + (width, height). + :param resample: Optional resampling filter. This can be one + of :py:data:`Resampling.NEAREST`, :py:data:`Resampling.BOX`, + :py:data:`Resampling.BILINEAR`, :py:data:`Resampling.HAMMING`, + :py:data:`Resampling.BICUBIC` or :py:data:`Resampling.LANCZOS`. + If omitted, it defaults to :py:data:`Resampling.BICUBIC`. + (was :py:data:`Resampling.NEAREST` prior to version 2.5.0). + See: :ref:`concept-filters`. + :param reducing_gap: Apply optimization by resizing the image + in two steps. First, reducing the image by integer times + using :py:meth:`~PIL.Image.Image.reduce` or + :py:meth:`~PIL.Image.Image.draft` for JPEG images. + Second, resizing using regular resampling. The last step + changes size no less than by ``reducing_gap`` times. + ``reducing_gap`` may be None (no first step is performed) + or should be greater than 1.0. The bigger ``reducing_gap``, + the closer the result to the fair resampling. + The smaller ``reducing_gap``, the faster resizing. + With ``reducing_gap`` greater or equal to 3.0, the result is + indistinguishable from fair resampling in most cases. + The default value is 2.0 (very close to fair resampling + while still being faster in many cases). + :returns: None + """ + + provided_size = tuple(map(math.floor, size)) + + def preserve_aspect_ratio() -> tuple[int, int] | None: + def round_aspect(number: float, key: Callable[[int], float]) -> int: + return max(min(math.floor(number), math.ceil(number), key=key), 1) + + x, y = provided_size + if x >= self.width and y >= self.height: + return None + + aspect = self.width / self.height + if x / y >= aspect: + x = round_aspect(y * aspect, key=lambda n: abs(aspect - n / y)) + else: + y = round_aspect( + x / aspect, key=lambda n: 0 if n == 0 else abs(aspect - x / n) + ) + return x, y + + preserved_size = preserve_aspect_ratio() + if preserved_size is None: + return + final_size = preserved_size + + box = None + if reducing_gap is not None: + res = self.draft( + None, (int(size[0] * reducing_gap), int(size[1] * reducing_gap)) + ) + if res is not None: + box = res[1] + + if self.size != final_size: + im = self.resize(final_size, resample, box=box, reducing_gap=reducing_gap) + + self.im = im.im + self._size = final_size + self._mode = self.im.mode + + self.readonly = 0 + + # FIXME: the different transform methods need further explanation + # instead of bloating the method docs, add a separate chapter. + def transform( + self, + size: tuple[int, int], + method: Transform | ImageTransformHandler | SupportsGetData, + data: Sequence[Any] | None = None, + resample: int = Resampling.NEAREST, + fill: int = 1, + fillcolor: float | tuple[float, ...] | str | None = None, + ) -> Image: + """ + Transforms this image. This method creates a new image with the + given size, and the same mode as the original, and copies data + to the new image using the given transform. + + :param size: The output size in pixels, as a 2-tuple: + (width, height). + :param method: The transformation method. This is one of + :py:data:`Transform.EXTENT` (cut out a rectangular subregion), + :py:data:`Transform.AFFINE` (affine transform), + :py:data:`Transform.PERSPECTIVE` (perspective transform), + :py:data:`Transform.QUAD` (map a quadrilateral to a rectangle), or + :py:data:`Transform.MESH` (map a number of source quadrilaterals + in one operation). + + It may also be an :py:class:`~PIL.Image.ImageTransformHandler` + object:: + + class Example(Image.ImageTransformHandler): + def transform(self, size, data, resample, fill=1): + # Return result + + Implementations of :py:class:`~PIL.Image.ImageTransformHandler` + for some of the :py:class:`Transform` methods are provided + in :py:mod:`~PIL.ImageTransform`. + + It may also be an object with a ``method.getdata`` method + that returns a tuple supplying new ``method`` and ``data`` values:: + + class Example: + def getdata(self): + method = Image.Transform.EXTENT + data = (0, 0, 100, 100) + return method, data + :param data: Extra data to the transformation method. + :param resample: Optional resampling filter. It can be one of + :py:data:`Resampling.NEAREST` (use nearest neighbour), + :py:data:`Resampling.BILINEAR` (linear interpolation in a 2x2 + environment), or :py:data:`Resampling.BICUBIC` (cubic spline + interpolation in a 4x4 environment). If omitted, or if the image + has mode "1" or "P", it is set to :py:data:`Resampling.NEAREST`. + See: :ref:`concept-filters`. + :param fill: If ``method`` is an + :py:class:`~PIL.Image.ImageTransformHandler` object, this is one of + the arguments passed to it. Otherwise, it is unused. + :param fillcolor: Optional fill color for the area outside the + transform in the output image. + :returns: An :py:class:`~PIL.Image.Image` object. + """ + + if self.mode in ("LA", "RGBA") and resample != Resampling.NEAREST: + return ( + self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) + .transform(size, method, data, resample, fill, fillcolor) + .convert(self.mode) + ) + + if isinstance(method, ImageTransformHandler): + return method.transform(size, self, resample=resample, fill=fill) + + if hasattr(method, "getdata"): + # compatibility w. old-style transform objects + method, data = method.getdata() + + if data is None: + msg = "missing method data" + raise ValueError(msg) + + im = new(self.mode, size, fillcolor) + if self.mode == "P" and self.palette: + im.palette = self.palette.copy() + im.info = self.info.copy() + if method == Transform.MESH: + # list of quads + for box, quad in data: + im.__transformer( + box, self, Transform.QUAD, quad, resample, fillcolor is None + ) + else: + im.__transformer( + (0, 0) + size, self, method, data, resample, fillcolor is None + ) + + return im + + def __transformer( + self, + box: tuple[int, int, int, int], + image: Image, + method: Transform, + data: Sequence[float], + resample: int = Resampling.NEAREST, + fill: bool = True, + ) -> None: + w = box[2] - box[0] + h = box[3] - box[1] + + if method == Transform.AFFINE: + data = data[:6] + + elif method == Transform.EXTENT: + # convert extent to an affine transform + x0, y0, x1, y1 = data + xs = (x1 - x0) / w + ys = (y1 - y0) / h + method = Transform.AFFINE + data = (xs, 0, x0, 0, ys, y0) + + elif method == Transform.PERSPECTIVE: + data = data[:8] + + elif method == Transform.QUAD: + # quadrilateral warp. data specifies the four corners + # given as NW, SW, SE, and NE. + nw = data[:2] + sw = data[2:4] + se = data[4:6] + ne = data[6:8] + x0, y0 = nw + As = 1.0 / w + At = 1.0 / h + data = ( + x0, + (ne[0] - x0) * As, + (sw[0] - x0) * At, + (se[0] - sw[0] - ne[0] + x0) * As * At, + y0, + (ne[1] - y0) * As, + (sw[1] - y0) * At, + (se[1] - sw[1] - ne[1] + y0) * As * At, + ) + + else: + msg = "unknown transformation method" + raise ValueError(msg) + + if resample not in ( + Resampling.NEAREST, + Resampling.BILINEAR, + Resampling.BICUBIC, + ): + if resample in (Resampling.BOX, Resampling.HAMMING, Resampling.LANCZOS): + unusable: dict[int, str] = { + Resampling.BOX: "Image.Resampling.BOX", + Resampling.HAMMING: "Image.Resampling.HAMMING", + Resampling.LANCZOS: "Image.Resampling.LANCZOS", + } + msg = unusable[resample] + f" ({resample}) cannot be used." + else: + msg = f"Unknown resampling filter ({resample})." + + filters = [ + f"{filter[1]} ({filter[0]})" + for filter in ( + (Resampling.NEAREST, "Image.Resampling.NEAREST"), + (Resampling.BILINEAR, "Image.Resampling.BILINEAR"), + (Resampling.BICUBIC, "Image.Resampling.BICUBIC"), + ) + ] + msg += f" Use {', '.join(filters[:-1])} or {filters[-1]}" + raise ValueError(msg) + + image.load() + + self.load() + + if image.mode in ("1", "P"): + resample = Resampling.NEAREST + + self.im.transform(box, image.im, method, data, resample, fill) + + def transpose(self, method: Transpose) -> Image: + """ + Transpose image (flip or rotate in 90 degree steps) + + :param method: One of :py:data:`Transpose.FLIP_LEFT_RIGHT`, + :py:data:`Transpose.FLIP_TOP_BOTTOM`, :py:data:`Transpose.ROTATE_90`, + :py:data:`Transpose.ROTATE_180`, :py:data:`Transpose.ROTATE_270`, + :py:data:`Transpose.TRANSPOSE` or :py:data:`Transpose.TRANSVERSE`. + :returns: Returns a flipped or rotated copy of this image. + """ + + self.load() + return self._new(self.im.transpose(method)) + + def effect_spread(self, distance: int) -> Image: + """ + Randomly spread pixels in an image. + + :param distance: Distance to spread pixels. + """ + self.load() + return self._new(self.im.effect_spread(distance)) + + def toqimage(self) -> ImageQt.ImageQt: + """Returns a QImage copy of this image""" + from . import ImageQt + + if not ImageQt.qt_is_installed: + msg = "Qt bindings are not installed" + raise ImportError(msg) + return ImageQt.toqimage(self) + + def toqpixmap(self) -> ImageQt.QPixmap: + """Returns a QPixmap copy of this image""" + from . import ImageQt + + if not ImageQt.qt_is_installed: + msg = "Qt bindings are not installed" + raise ImportError(msg) + return ImageQt.toqpixmap(self) + + +# -------------------------------------------------------------------- +# Abstract handlers. + + +class ImagePointHandler(abc.ABC): + """ + Used as a mixin by point transforms + (for use with :py:meth:`~PIL.Image.Image.point`) + """ + + @abc.abstractmethod + def point(self, im: Image) -> Image: + pass + + +class ImageTransformHandler(abc.ABC): + """ + Used as a mixin by geometry transforms + (for use with :py:meth:`~PIL.Image.Image.transform`) + """ + + @abc.abstractmethod + def transform( + self, + size: tuple[int, int], + image: Image, + **options: Any, + ) -> Image: + pass + + +# -------------------------------------------------------------------- +# Factories + + +def _check_size(size: Any) -> None: + """ + Common check to enforce type and sanity check on size tuples + + :param size: Should be a 2 tuple of (width, height) + :returns: None, or raises a ValueError + """ + + if not isinstance(size, (list, tuple)): + msg = "Size must be a list or tuple" + raise ValueError(msg) + if len(size) != 2: + msg = "Size must be a sequence of length 2" + raise ValueError(msg) + if size[0] < 0 or size[1] < 0: + msg = "Width and height must be >= 0" + raise ValueError(msg) + + +def new( + mode: str, + size: tuple[int, int] | list[int], + color: float | tuple[float, ...] | str | None = 0, +) -> Image: + """ + Creates a new image with the given mode and size. + + :param mode: The mode to use for the new image. See: + :ref:`concept-modes`. + :param size: A 2-tuple, containing (width, height) in pixels. + :param color: What color to use for the image. Default is black. If given, + this should be a single integer or floating point value for single-band + modes, and a tuple for multi-band modes (one value per band). When + creating RGB or HSV images, you can also use color strings as supported + by the ImageColor module. See :ref:`colors` for more information. If the + color is None, the image is not initialised. + :returns: An :py:class:`~PIL.Image.Image` object. + """ + + _check_size(size) + + if color is None: + # don't initialize + return Image()._new(core.new(mode, size)) + + if isinstance(color, str): + # css3-style specifier + + from . import ImageColor + + color = ImageColor.getcolor(color, mode) + + im = Image() + if ( + mode == "P" + and isinstance(color, (list, tuple)) + and all(isinstance(i, int) for i in color) + ): + color_ints: tuple[int, ...] = cast(tuple[int, ...], tuple(color)) + if len(color_ints) == 3 or len(color_ints) == 4: + # RGB or RGBA value for a P image + from . import ImagePalette + + im.palette = ImagePalette.ImagePalette() + color = im.palette.getcolor(color_ints) + return im._new(core.fill(mode, size, color)) + + +def frombytes( + mode: str, + size: tuple[int, int], + data: DecoderInput, + decoder_name: str = "raw", + *args: Any, +) -> Image: + """ + Creates a copy of an image memory from pixel data in a buffer. + + In its simplest form, this function takes three arguments + (mode, size, and unpacked pixel data). + + You can also use any pixel decoder supported by PIL. For more + information on available decoders, see the section + :ref:`Writing Your Own File Codec `. + + Note that this function decodes pixel data only, not entire images. + If you have an entire image in a string, wrap it in a + :py:class:`~io.BytesIO` object, and use :py:func:`~PIL.Image.open` to load + it. + + :param mode: The image mode. See: :ref:`concept-modes`. + :param size: The image size. + :param data: A byte buffer containing raw data for the given mode. + :param decoder_name: What decoder to use. + :param args: Additional parameters for the given decoder. + :returns: An :py:class:`~PIL.Image.Image` object. + """ + + _check_size(size) + + im = new(mode, size) + if im.width != 0 and im.height != 0: + decoder_args: Any = args + if len(decoder_args) == 1 and isinstance(decoder_args[0], tuple): + # may pass tuple instead of argument list + decoder_args = decoder_args[0] + + if decoder_name == "raw" and decoder_args == (): + decoder_args = mode + + im.frombytes(data, decoder_name, decoder_args) + return im + + +def frombuffer( + mode: str, + size: tuple[int, int], + data: bytes | SupportsArrayInterface, + decoder_name: str = "raw", + *args: Any, +) -> Image: + """ + Creates an image memory referencing pixel data in a byte buffer. + + This function is similar to :py:func:`~PIL.Image.frombytes`, but uses data + in the byte buffer, where possible. This means that changes to the + original buffer object are reflected in this image). Not all modes can + share memory; supported modes include "L", "RGBX", "RGBA", and "CMYK". + + Note that this function decodes pixel data only, not entire images. + If you have an entire image file in a string, wrap it in a + :py:class:`~io.BytesIO` object, and use :py:func:`~PIL.Image.open` to load it. + + The default parameters used for the "raw" decoder differs from that used for + :py:func:`~PIL.Image.frombytes`. This is a bug, and will probably be fixed in a + future release. The current release issues a warning if you do this; to disable + the warning, you should provide the full set of parameters. See below for details. + + :param mode: The image mode. See: :ref:`concept-modes`. + :param size: The image size. + :param data: A bytes or other buffer object containing raw + data for the given mode. + :param decoder_name: What decoder to use. + :param args: Additional parameters for the given decoder. For the + default encoder ("raw"), it's recommended that you provide the + full set of parameters:: + + frombuffer(mode, size, data, "raw", mode, 0, 1) + + :returns: An :py:class:`~PIL.Image.Image` object. + + .. versionadded:: 1.1.4 + """ + + _check_size(size) + + # may pass tuple instead of argument list + if len(args) == 1 and isinstance(args[0], tuple): + args = args[0] + + if decoder_name == "raw": + if args == (): + args = mode, 0, 1 + if args[0] in _MAPMODES: + im = new(mode, (0, 0)) + im = im._new(core.map_buffer(data, size, decoder_name, 0, args)) + if mode == "P": + from . import ImagePalette + + im.palette = ImagePalette.ImagePalette("RGB", im.im.getpalette("RGB")) + im.readonly = 1 + return im + + return frombytes(mode, size, data, decoder_name, args) + + +class SupportsArrayInterface(Protocol): + """ + An object that has an ``__array_interface__`` dictionary. + """ + + @property + def __array_interface__(self) -> dict[str, Any]: + raise NotImplementedError() + + def __len__(self) -> int: + raise NotImplementedError() + + +DecoderInput = bytes | bytearray | memoryview | SupportsArrayInterface + + +class SupportsArrowArrayInterface(Protocol): + """ + An object that has an ``__arrow_c_array__`` method corresponding to the arrow c + data interface. + """ + + def __arrow_c_array__( + self, requested_schema: "PyCapsule" = None # type: ignore[name-defined] # noqa: F821, UP037 + ) -> tuple["PyCapsule", "PyCapsule"]: # type: ignore[name-defined] # noqa: F821, UP037 + raise NotImplementedError() + + +def fromarray(obj: SupportsArrayInterface, mode: str | None = None) -> Image: + """ + Creates an image memory from an object exporting the array interface + (using the buffer protocol):: + + from PIL import Image + import numpy as np + a = np.zeros((5, 5)) + im = Image.fromarray(a) + + If ``obj`` is not contiguous, then the ``tobytes`` method is called + and :py:func:`~PIL.Image.frombuffer` is used. + + In the case of NumPy, be aware that Pillow modes do not always correspond + to NumPy dtypes. Pillow modes only offer 1-bit pixels, 8-bit pixels, + 32-bit signed integer pixels, and 32-bit floating point pixels. + + Pillow images can also be converted to arrays:: + + from PIL import Image + import numpy as np + im = Image.open("hopper.jpg") + a = np.asarray(im) + + When converting Pillow images to arrays however, only pixel values are + transferred. This means that P and PA mode images will lose their palette. + + :param obj: Object with array interface + :param mode: Optional mode to use when reading ``obj``. Since pixel values do not + contain information about palettes or color spaces, this can be used to place + grayscale L mode data within a P mode image, or read RGB data as YCbCr for + example. + + See: :ref:`concept-modes` for general information about modes. + :returns: An image object. + + .. versionadded:: 1.1.6 + """ + arr = obj.__array_interface__ + shape = arr["shape"] + ndim = len(shape) + strides = arr.get("strides", None) + try: + typekey = (1, 1) + shape[2:], arr["typestr"] + except KeyError as e: + if mode is not None: + typekey = None + color_modes: list[str] = [] + else: + msg = "Cannot handle this data type" + raise TypeError(msg) from e + if typekey is not None: + try: + typemode, rawmode, color_modes = _fromarray_typemap[typekey] + except KeyError as e: + typekey_shape, typestr = typekey + msg = f"Cannot handle this data type: {typekey_shape}, {typestr}" + raise TypeError(msg) from e + if mode is not None: + if mode != typemode and mode not in color_modes: + deprecate("'mode' parameter for changing data types", 13) + rawmode = mode + else: + mode = typemode + if mode in ["1", "L", "I", "P", "F"]: + ndmax = 2 + elif mode == "RGB": + ndmax = 3 + else: + ndmax = 4 + if ndim > ndmax: + msg = f"Too many dimensions: {ndim} > {ndmax}." + raise ValueError(msg) + + size = 1 if ndim == 1 else shape[1], shape[0] + if strides is not None: + if hasattr(obj, "tobytes"): + obj = obj.tobytes() + elif hasattr(obj, "tostring"): + obj = obj.tostring() + else: + msg = "'strides' requires either tobytes() or tostring()" + raise ValueError(msg) + + return frombuffer(mode, size, obj, "raw", rawmode, 0, 1) + + +def fromarrow( + obj: SupportsArrowArrayInterface, mode: str, size: tuple[int, int] +) -> Image: + """Creates an image with zero-copy shared memory from an object exporting + the arrow_c_array interface protocol:: + + from PIL import Image + import pyarrow as pa + arr = pa.array([0]*(5*5*4), type=pa.uint8()) + im = Image.fromarrow(arr, 'RGBA', (5, 5)) + + If the data representation of the ``obj`` is not compatible with + Pillow internal storage, a ValueError is raised. + + Pillow images can also be converted to Arrow objects:: + + from PIL import Image + import pyarrow as pa + im = Image.open('hopper.jpg') + arr = pa.array(im) + + As with array support, when converting Pillow images to arrays, + only pixel values are transferred. This means that P and PA mode + images will lose their palette. + + :param obj: Object with an arrow_c_array interface + :param mode: Image mode. + :param size: Image size. This must match the storage of the arrow object. + :returns: An Image object + + Note that according to the Arrow spec, both the producer and the + consumer should consider the exported array to be immutable, as + unsynchronized updates will potentially cause inconsistent data. + + See: :ref:`arrow-support` for more detailed information + + .. versionadded:: 11.2.1 + + """ + if not hasattr(obj, "__arrow_c_array__"): + msg = "arrow_c_array interface not found" + raise ValueError(msg) + + schema_capsule, array_capsule = obj.__arrow_c_array__() + _im = core.new_arrow(mode, size, schema_capsule, array_capsule) + if _im: + return Image()._new(_im) + + msg = "new_arrow returned None without an exception" + raise ValueError(msg) + + +def fromqimage(im: ImageQt.QImage) -> ImageFile.ImageFile: + """Creates an image instance from a QImage image""" + from . import ImageQt + + if not ImageQt.qt_is_installed: + msg = "Qt bindings are not installed" + raise ImportError(msg) + return ImageQt.fromqimage(im) + + +def fromqpixmap(im: ImageQt.QPixmap) -> ImageFile.ImageFile: + """Creates an image instance from a QPixmap image""" + from . import ImageQt + + if not ImageQt.qt_is_installed: + msg = "Qt bindings are not installed" + raise ImportError(msg) + return ImageQt.fromqpixmap(im) + + +_fromarray_typemap = { + # (shape, typestr) => mode, rawmode, color modes + # first two members of shape are set to one + ((1, 1), "|b1"): ("1", "1;8", []), + ((1, 1), "|u1"): ("L", "L", ["P"]), + ((1, 1), "|i1"): ("I", "I;8", []), + ((1, 1), "u2"): ("I", "I;16B", []), + ((1, 1), "i2"): ("I", "I;16BS", []), + ((1, 1), "u4"): ("I", "I;32B", []), + ((1, 1), "i4"): ("I", "I;32BS", []), + ((1, 1), "f4"): ("F", "F;32BF", []), + ((1, 1), "f8"): ("F", "F;64BF", []), + ((1, 1, 2), "|u1"): ("LA", "LA", ["La", "PA"]), + ((1, 1, 3), "|u1"): ("RGB", "RGB", ["YCbCr", "LAB", "HSV"]), + ((1, 1, 4), "|u1"): ("RGBA", "RGBA", ["RGBa", "RGBX", "CMYK"]), + # shortcuts: + ((1, 1), f"{_ENDIAN}i4"): ("I", "I", []), + ((1, 1), f"{_ENDIAN}f4"): ("F", "F", []), +} + + +def _decompression_bomb_check(size: tuple[int, int]) -> None: + if MAX_IMAGE_PIXELS is None: + return + + pixels = max(1, size[0]) * max(1, size[1]) + + if pixels > 2 * MAX_IMAGE_PIXELS: + msg = ( + f"Image size ({pixels} pixels) exceeds limit of {2 * MAX_IMAGE_PIXELS} " + "pixels, could be decompression bomb DOS attack." + ) + raise DecompressionBombError(msg) + + if pixels > MAX_IMAGE_PIXELS: + warnings.warn( + f"Image size ({pixels} pixels) exceeds limit of {MAX_IMAGE_PIXELS} pixels, " + "could be decompression bomb DOS attack.", + DecompressionBombWarning, + ) + + +def open( + fp: StrOrBytesPath | IO[bytes], + mode: Literal["r"] = "r", + formats: list[str] | tuple[str, ...] | None = None, +) -> ImageFile.ImageFile: + """ + Opens and identifies the given image file. + + This is a lazy operation; this function identifies the file, but + the file remains open and the actual image data is not read from + the file until you try to process the data (or call the + :py:meth:`~PIL.Image.Image.load` method). See + :py:func:`~PIL.Image.new`. See :ref:`file-handling`. + + :param fp: A filename (string), os.PathLike object or a file object. + The file object must implement ``file.read``, + ``file.seek``, and ``file.tell`` methods, + and be opened in binary mode. The file object will also seek to zero + before reading. + :param mode: The mode. If given, this argument must be "r". + :param formats: A list or tuple of formats to attempt to load the file in. + This can be used to restrict the set of formats checked. + Pass ``None`` to try all supported formats. You can print the set of + available formats by running ``python3 -m PIL`` or using + the :py:func:`PIL.features.pilinfo` function. + :returns: An :py:class:`~PIL.Image.Image` object. + :exception FileNotFoundError: If the file cannot be found. + :exception PIL.UnidentifiedImageError: If the image cannot be opened and + identified. + :exception ValueError: If the ``mode`` is not "r", or if a ``StringIO`` + instance is used for ``fp``. + :exception TypeError: If ``formats`` is not ``None``, a list or a tuple. + """ + + if mode != "r": + msg = f"bad mode {repr(mode)}" # type: ignore[unreachable] + raise ValueError(msg) + elif isinstance(fp, io.StringIO): + msg = ( # type: ignore[unreachable] + "StringIO cannot be used to open an image. " + "Binary data must be used instead." + ) + raise ValueError(msg) + + if formats is None: + formats = ID + elif not isinstance(formats, (list, tuple)): + msg = "formats must be a list or tuple" # type: ignore[unreachable] + raise TypeError(msg) + + exclusive_fp = False + filename: str | bytes = "" + if is_path(fp): + filename = os.fspath(fp) + fp = builtins.open(filename, "rb") + exclusive_fp = True + else: + fp = cast(IO[bytes], fp) + + try: + fp.seek(0) + except (AttributeError, io.UnsupportedOperation): + fp = io.BytesIO(fp.read()) + exclusive_fp = True + + prefix = fp.read(16) + + # Try to import just the plugin needed for this file extension + # before falling back to preinit() which imports common plugins + ext = os.path.splitext(filename)[1] if filename else "" + if not _import_plugin_for_extension(ext): + preinit() + + warning_messages: list[str] = [] + + def _open_core( + fp: IO[bytes], + filename: str | bytes, + prefix: bytes, + formats: list[str] | tuple[str, ...], + ) -> ImageFile.ImageFile | None: + for i in formats: + i = i.upper() + if i not in OPEN: + init() + try: + factory, accept = OPEN[i] + result = not accept or accept(prefix) + if isinstance(result, str): + warning_messages.append(result) + elif result: + fp.seek(0) + im = factory(fp, filename) + _decompression_bomb_check(im.size) + return im + except (SyntaxError, IndexError, TypeError, struct.error) as e: + if WARN_POSSIBLE_FORMATS: + warning_messages.append(i + " opening failed. " + str(e)) + except BaseException: + if exclusive_fp: + fp.close() + raise + return None + + im = _open_core(fp, filename, prefix, formats) + + if im is None and formats is ID: + # Try preinit (few common plugins) then init (all plugins) + for loader in (preinit, init): + checked_formats = ID.copy() + loader() + if formats != checked_formats: + im = _open_core( + fp, + filename, + prefix, + tuple(f for f in formats if f not in checked_formats), + ) + if im is not None: + break + + if im: + im._exclusive_fp = exclusive_fp + return im + + if exclusive_fp: + fp.close() + for message in warning_messages: + warnings.warn(message) + msg = "cannot identify image file %r" % (filename if filename else fp) + raise UnidentifiedImageError(msg) + + +# +# Image processing. + + +def alpha_composite(im1: Image, im2: Image) -> Image: + """ + Alpha composite im2 over im1. + + :param im1: The first image. Must have mode RGBA or LA. + :param im2: The second image. Must have the same mode and size as the first image. + :returns: An :py:class:`~PIL.Image.Image` object. + """ + + im1.load() + im2.load() + return im1._new(core.alpha_composite(im1.im, im2.im)) + + +def blend(im1: Image, im2: Image, alpha: float) -> Image: + """ + Creates a new image by interpolating between two input images, using + a constant alpha:: + + out = image1 * (1.0 - alpha) + image2 * alpha + + :param im1: The first image. + :param im2: The second image. Must have the same mode and size as + the first image. + :param alpha: The interpolation alpha factor. If alpha is 0.0, a + copy of the first image is returned. If alpha is 1.0, a copy of + the second image is returned. There are no restrictions on the + alpha value. If necessary, the result is clipped to fit into + the allowed output range. + :returns: An :py:class:`~PIL.Image.Image` object. + """ + + im1.load() + im2.load() + return im1._new(core.blend(im1.im, im2.im, alpha)) + + +def composite(image1: Image, image2: Image, mask: Image) -> Image: + """ + Create composite image by blending images using a transparency mask. + + :param image1: The first image. + :param image2: The second image. Must have the same mode and + size as the first image. + :param mask: A mask image. This image can have mode + "1", "L", or "RGBA", and must have the same size as the + other two images. + """ + + image = image2.copy() + image.paste(image1, None, mask) + return image + + +def eval(image: Image, *args: Callable[[int], float]) -> Image: + """ + Applies the function (which should take one argument) to each pixel + in the given image. If the image has more than one band, the same + function is applied to each band. Note that the function is + evaluated once for each possible pixel value, so you cannot use + random components or other generators. + + :param image: The input image. + :param function: A function object, taking one integer argument. + :returns: An :py:class:`~PIL.Image.Image` object. + """ + + return image.point(args[0]) + + +def merge(mode: str, bands: Sequence[Image]) -> Image: + """ + Merge a set of single band images into a new multiband image. + + :param mode: The mode to use for the output image. See: + :ref:`concept-modes`. + :param bands: A sequence containing one single-band image for + each band in the output image. All bands must have the + same size. + :returns: An :py:class:`~PIL.Image.Image` object. + """ + + if getmodebands(mode) != len(bands) or "*" in mode: + msg = "wrong number of bands" + raise ValueError(msg) + for band in bands[1:]: + if band.mode != getmodetype(mode): + msg = "mode mismatch" + raise ValueError(msg) + if band.size != bands[0].size: + msg = "size mismatch" + raise ValueError(msg) + for band in bands: + band.load() + return bands[0]._new(core.merge(mode, *[b.im for b in bands])) + + +# -------------------------------------------------------------------- +# Plugin registry + + +def register_open( + id: str, + factory: ( + Callable[[IO[bytes], str | bytes], ImageFile.ImageFile] + | type[ImageFile.ImageFile] + ), + accept: Callable[[bytes], bool | str] | None = None, +) -> None: + """ + Register an image file plugin. This function should not be used + in application code. + + :param id: An image format identifier. + :param factory: An image file factory method. + :param accept: An optional function that can be used to quickly + reject images having another format. + """ + id = id.upper() + if id not in ID: + ID.append(id) + OPEN[id] = factory, accept + + +def register_mime(id: str, mimetype: str) -> None: + """ + Registers an image MIME type by populating ``Image.MIME``. This function + should not be used in application code. + + ``Image.MIME`` provides a mapping from image format identifiers to mime + formats, but :py:meth:`~PIL.ImageFile.ImageFile.get_format_mimetype` can + provide a different result for specific images. + + :param id: An image format identifier. + :param mimetype: The image MIME type for this format. + """ + MIME[id.upper()] = mimetype + + +def register_save( + id: str, driver: Callable[[Image, IO[bytes], str | bytes], None] +) -> None: + """ + Registers an image save function. This function should not be + used in application code. + + :param id: An image format identifier. + :param driver: A function to save images in this format. + """ + SAVE[id.upper()] = driver + + +def register_save_all( + id: str, driver: Callable[[Image, IO[bytes], str | bytes], None] +) -> None: + """ + Registers an image function to save all the frames + of a multiframe format. This function should not be + used in application code. + + :param id: An image format identifier. + :param driver: A function to save images in this format. + """ + SAVE_ALL[id.upper()] = driver + + +def register_extension(id: str, extension: str) -> None: + """ + Registers an image extension. This function should not be + used in application code. + + :param id: An image format identifier. + :param extension: An extension used for this format. + """ + EXTENSION[extension.lower()] = id.upper() + + +def register_extensions(id: str, extensions: list[str]) -> None: + """ + Registers image extensions. This function should not be + used in application code. + + :param id: An image format identifier. + :param extensions: A list of extensions used for this format. + """ + for extension in extensions: + register_extension(id, extension) + + +def registered_extensions() -> dict[str, str]: + """ + Returns a dictionary containing all file extensions belonging + to registered plugins + """ + init() + return EXTENSION + + +def register_decoder(name: str, decoder: type[ImageFile.PyDecoder]) -> None: + """ + Registers an image decoder. This function should not be + used in application code. + + :param name: The name of the decoder + :param decoder: An ImageFile.PyDecoder object + + .. versionadded:: 4.1.0 + """ + DECODERS[name] = decoder + + +def register_encoder(name: str, encoder: type[ImageFile.PyEncoder]) -> None: + """ + Registers an image encoder. This function should not be + used in application code. + + :param name: The name of the encoder + :param encoder: An ImageFile.PyEncoder object + + .. versionadded:: 4.1.0 + """ + ENCODERS[name] = encoder + + +# -------------------------------------------------------------------- +# Simple display support. + + +def _show(image: Image, **options: Any) -> None: + from . import ImageShow + + deprecate("Image._show", 13, "ImageShow.show") + ImageShow.show(image, **options) + + +# -------------------------------------------------------------------- +# Effects + + +def effect_mandelbrot( + size: tuple[int, int], extent: tuple[float, float, float, float], quality: int +) -> Image: + """ + Generate a Mandelbrot set covering the given extent. + + :param size: The requested size in pixels, as a 2-tuple: + (width, height). + :param extent: The extent to cover, as a 4-tuple: + (x0, y0, x1, y1). + :param quality: Quality. + """ + return Image()._new(core.effect_mandelbrot(size, extent, quality)) + + +def effect_noise(size: tuple[int, int], sigma: float) -> Image: + """ + Generate Gaussian noise centered around 128. + + :param size: The requested size in pixels, as a 2-tuple: + (width, height). + :param sigma: Standard deviation of noise. + """ + return Image()._new(core.effect_noise(size, sigma)) + + +def linear_gradient(mode: str) -> Image: + """ + Generate 256x256 linear gradient from black to white, top to bottom. + + :param mode: Input mode. + """ + return Image()._new(core.linear_gradient(mode)) + + +def radial_gradient(mode: str) -> Image: + """ + Generate 256x256 radial gradient from black to white, centre to edge. + + :param mode: Input mode. + """ + return Image()._new(core.radial_gradient(mode)) + + +# -------------------------------------------------------------------- +# Resources + + +def _apply_env_variables(env: dict[str, str] | None = None) -> None: + env_dict = env if env is not None else os.environ + + for var_name, setter in [ + ("PILLOW_ALIGNMENT", core.set_alignment), + ("PILLOW_BLOCK_SIZE", core.set_block_size), + ("PILLOW_BLOCKS_MAX", core.set_blocks_max), + ]: + if var_name not in env_dict: + continue + + var = env_dict[var_name].lower() + + units = 1 + for postfix, mul in [("k", 1024), ("m", 1024 * 1024)]: + if var.endswith(postfix): + units = mul + var = var[: -len(postfix)] + + try: + var_int = int(var) * units + except ValueError: + warnings.warn(f"{var_name} is not int") + continue + + try: + setter(var_int) + except ValueError as e: + warnings.warn(f"{var_name}: {e}") + + +_apply_env_variables() +atexit.register(core.clear_cache) + + +if TYPE_CHECKING: + _ExifBase = MutableMapping[int, Any] +else: + _ExifBase = MutableMapping + + +class Exif(_ExifBase): + """ + This class provides read and write access to EXIF image data:: + + from PIL import Image + im = Image.open("exif.png") + exif = im.getexif() # Returns an instance of this class + + Information can be read and written, iterated over or deleted:: + + print(exif[274]) # 1 + exif[274] = 2 + for k, v in exif.items(): + print("Tag", k, "Value", v) # Tag 274 Value 2 + del exif[274] + + To access information beyond IFD0, :py:meth:`~PIL.Image.Exif.get_ifd` + returns a dictionary:: + + from PIL import ExifTags + im = Image.open("exif_gps.jpg") + exif = im.getexif() + gps_ifd = exif.get_ifd(ExifTags.IFD.GPSInfo) + print(gps_ifd) + + Other IFDs include ``ExifTags.IFD.Exif``, ``ExifTags.IFD.MakerNote``, + ``ExifTags.IFD.Interop`` and ``ExifTags.IFD.IFD1``. + + :py:mod:`~PIL.ExifTags` also has enum classes to provide names for data:: + + print(exif[ExifTags.Base.Software]) # PIL + print(gps_ifd[ExifTags.GPS.GPSDateStamp]) # 1999:99:99 99:99:99 + """ + + endian: str | None = None + bigtiff = False + _loaded = False + + def __init__(self) -> None: + self._data: dict[int, Any] = {} + self._hidden_data: dict[int, Any] = {} + self._ifds: dict[int, dict[int, Any]] = {} + self._info: TiffImagePlugin.ImageFileDirectory_v2 | None = None + self._loaded_exif: bytes | None = None + + def _fixup(self, value: Any) -> Any: + try: + if len(value) == 1 and isinstance(value, tuple): + return value[0] + except Exception: + pass + return value + + def _fixup_dict(self, src_dict: dict[int, Any]) -> dict[int, Any]: + # Helper function + # returns a dict with any single item tuples/lists as individual values + return {k: self._fixup(v) for k, v in src_dict.items()} + + def _get_ifd_dict( + self, offset: int, group: int | None = None + ) -> dict[int, Any] | None: + try: + # an offset pointer to the location of the nested embedded IFD. + # It should be a long, but may be corrupted. + self.fp.seek(offset) + except (KeyError, TypeError): + return None + else: + from . import TiffImagePlugin + + info = TiffImagePlugin.ImageFileDirectory_v2(self.head, group=group) + info.load(self.fp) + return self._fixup_dict(dict(info)) + + def _get_head(self) -> bytes: + version = b"\x2b" if self.bigtiff else b"\x2a" + if self.endian == "<": + head = b"II" + version + b"\x00" + o32le(8) + else: + head = b"MM\x00" + version + o32be(8) + if self.bigtiff: + head += o32le(8) if self.endian == "<" else o32be(8) + head += b"\x00\x00\x00\x00" + return head + + def load(self, data: bytes) -> None: + # Extract EXIF information. This is highly experimental, + # and is likely to be replaced with something better in a future + # version. + + # The EXIF record consists of a TIFF file embedded in a JPEG + # application marker (!). + if data == self._loaded_exif: + return + self._loaded_exif = data + self._data.clear() + self._hidden_data.clear() + self._ifds.clear() + while data and data.startswith(b"Exif\x00\x00"): + data = data[6:] + if not data: + self._info = None + return + + self.fp: IO[bytes] = io.BytesIO(data) + self.head = self.fp.read(8) + # process dictionary + from . import TiffImagePlugin + + self._info = TiffImagePlugin.ImageFileDirectory_v2(self.head) + self.endian = self._info._endian + self.fp.seek(self._info.next) + self._info.load(self.fp) + + def load_from_fp(self, fp: IO[bytes], offset: int | None = None) -> None: + self._loaded_exif = None + self._data.clear() + self._hidden_data.clear() + self._ifds.clear() + + # process dictionary + from . import TiffImagePlugin + + self.fp = fp + if offset is not None: + self.head = self._get_head() + else: + self.head = self.fp.read(8) + self._info = TiffImagePlugin.ImageFileDirectory_v2(self.head) + if self.endian is None: + self.endian = self._info._endian + if offset is None: + offset = self._info.next + self.fp.tell() + self.fp.seek(offset) + self._info.load(self.fp) + + def _get_merged_dict(self) -> dict[int, Any]: + merged_dict = dict(self) + + # get EXIF extension + if ExifTags.IFD.Exif in self: + ifd = self._get_ifd_dict(self[ExifTags.IFD.Exif], ExifTags.IFD.Exif) + if ifd: + merged_dict.update(ifd) + + # GPS + if ExifTags.IFD.GPSInfo in self: + merged_dict[ExifTags.IFD.GPSInfo] = self._get_ifd_dict( + self[ExifTags.IFD.GPSInfo], ExifTags.IFD.GPSInfo + ) + + return merged_dict + + def tobytes(self, offset: int = 8) -> bytes: + from . import TiffImagePlugin + + head = self._get_head() + ifd = TiffImagePlugin.ImageFileDirectory_v2(ifh=head) + for tag, ifd_dict in self._ifds.items(): + if tag not in self: + ifd[tag] = ifd_dict + for tag, value in self.items(): + if tag in [ + ExifTags.IFD.Exif, + ExifTags.IFD.GPSInfo, + ] and not isinstance(value, dict): + value = self.get_ifd(tag) + if ( + tag == ExifTags.IFD.Exif + and ExifTags.IFD.Interop in value + and not isinstance(value[ExifTags.IFD.Interop], dict) + ): + value = value.copy() + value[ExifTags.IFD.Interop] = self.get_ifd(ExifTags.IFD.Interop) + ifd[tag] = value + return b"Exif\x00\x00" + head + ifd.tobytes(offset) + + def get_ifd(self, tag: int) -> dict[int, Any]: + if tag not in self._ifds: + if tag == ExifTags.IFD.IFD1: + if self._info is not None and self._info.next != 0: + ifd = self._get_ifd_dict(self._info.next) + if ifd is not None: + self._ifds[tag] = ifd + elif tag in [ExifTags.IFD.Exif, ExifTags.IFD.GPSInfo]: + offset = self._hidden_data.get(tag, self.get(tag)) + if offset is not None: + ifd = self._get_ifd_dict(offset, tag) + if ifd is not None: + self._ifds[tag] = ifd + elif tag in [ExifTags.IFD.Interop, ExifTags.IFD.MakerNote]: + if ExifTags.IFD.Exif not in self._ifds: + self.get_ifd(ExifTags.IFD.Exif) + tag_data = self._ifds[ExifTags.IFD.Exif][tag] + if tag == ExifTags.IFD.MakerNote: + from .TiffImagePlugin import ImageFileDirectory_v2 + + try: + if tag_data.startswith(b"FUJIFILM"): + ifd_offset = i32le(tag_data, 8) + ifd_data = tag_data[ifd_offset:] + + makernote = {} + for i in range(struct.unpack(" 4: + (offset,) = struct.unpack("H", tag_data[:2])[0]): + ifd_tag, typ, count, data = struct.unpack( + ">HHL4s", tag_data[i * 12 + 2 : (i + 1) * 12 + 2] + ) + if ifd_tag == 0x1101: + # CameraInfo + (offset,) = struct.unpack(">L", data) + self.fp.seek(offset) + + camerainfo: dict[str, int | bytes] = { + "ModelID": self.fp.read(4) + } + + self.fp.read(4) + # Seconds since 2000 + camerainfo["TimeStamp"] = i32le(self.fp.read(12)) + + self.fp.read(4) + camerainfo["InternalSerialNumber"] = self.fp.read(4) + + self.fp.read(12) + parallax = self.fp.read(4) + handler = ImageFileDirectory_v2._load_dispatch[ + TiffTags.FLOAT + ][1] + camerainfo["Parallax"] = handler( + ImageFileDirectory_v2(), parallax, False + )[0] + + self.fp.read(4) + camerainfo["Category"] = self.fp.read(2) + + makernote = {0x1101: camerainfo} + self._ifds[tag] = makernote + except struct.error: + pass + else: + # Interop + ifd = self._get_ifd_dict(tag_data, tag) + if ifd is not None: + self._ifds[tag] = ifd + ifd = self._ifds.setdefault(tag, {}) + if tag == ExifTags.IFD.Exif and self._hidden_data: + ifd = { + k: v + for (k, v) in ifd.items() + if k not in (ExifTags.IFD.Interop, ExifTags.IFD.MakerNote) + } + return ifd + + def hide_offsets(self) -> None: + for tag in (ExifTags.IFD.Exif, ExifTags.IFD.GPSInfo): + if tag in self: + self._hidden_data[tag] = self[tag] + del self[tag] + + def __str__(self) -> str: + if self._info is not None: + # Load all keys into self._data + for tag in self._info: + self[tag] + + return str(self._data) + + def __len__(self) -> int: + keys = set(self._data) + if self._info is not None: + keys.update(self._info) + return len(keys) + + def __getitem__(self, tag: int) -> Any: + if self._info is not None and tag not in self._data and tag in self._info: + self._data[tag] = self._fixup(self._info[tag]) + del self._info[tag] + return self._data[tag] + + def __contains__(self, tag: object) -> bool: + return tag in self._data or (self._info is not None and tag in self._info) + + def __setitem__(self, tag: int, value: Any) -> None: + if self._info is not None and tag in self._info: + del self._info[tag] + self._data[tag] = value + + def __delitem__(self, tag: int) -> None: + if self._info is not None and tag in self._info: + del self._info[tag] + else: + del self._data[tag] + if tag in self._ifds: + del self._ifds[tag] + + def __iter__(self) -> Iterator[int]: + keys = set(self._data) + if self._info is not None: + keys.update(self._info) + return iter(keys) diff --git a/.venv/lib/python3.11/site-packages/PIL/ImageChops.py b/.venv/lib/python3.11/site-packages/PIL/ImageChops.py new file mode 100644 index 0000000000000000000000000000000000000000..29a5c995fd802c9be16784f80707cfecb88b2002 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/ImageChops.py @@ -0,0 +1,311 @@ +# +# The Python Imaging Library. +# $Id$ +# +# standard channel operations +# +# History: +# 1996-03-24 fl Created +# 1996-08-13 fl Added logical operations (for "1" images) +# 2000-10-12 fl Added offset method (from Image.py) +# +# Copyright (c) 1997-2000 by Secret Labs AB +# Copyright (c) 1996-2000 by Fredrik Lundh +# +# See the README file for information on usage and redistribution. +# + +from __future__ import annotations + +from . import Image + + +def constant(image: Image.Image, value: int) -> Image.Image: + """Fill a channel with a given gray level. + + :rtype: :py:class:`~PIL.Image.Image` + """ + + return Image.new("L", image.size, value) + + +def duplicate(image: Image.Image) -> Image.Image: + """Copy a channel. Alias for :py:meth:`PIL.Image.Image.copy`. + + :rtype: :py:class:`~PIL.Image.Image` + """ + + return image.copy() + + +def invert(image: Image.Image) -> Image.Image: + """ + Invert an image (channel). :: + + out = MAX - image + + :rtype: :py:class:`~PIL.Image.Image` + """ + + image.load() + return image._new(image.im.chop_invert()) + + +def lighter(image1: Image.Image, image2: Image.Image) -> Image.Image: + """ + Compares the two images, pixel by pixel, and returns a new image containing + the lighter values. :: + + out = max(image1, image2) + + :rtype: :py:class:`~PIL.Image.Image` + """ + + image1.load() + image2.load() + return image1._new(image1.im.chop_lighter(image2.im)) + + +def darker(image1: Image.Image, image2: Image.Image) -> Image.Image: + """ + Compares the two images, pixel by pixel, and returns a new image containing + the darker values. :: + + out = min(image1, image2) + + :rtype: :py:class:`~PIL.Image.Image` + """ + + image1.load() + image2.load() + return image1._new(image1.im.chop_darker(image2.im)) + + +def difference(image1: Image.Image, image2: Image.Image) -> Image.Image: + """ + Returns the absolute value of the pixel-by-pixel difference between the two + images. :: + + out = abs(image1 - image2) + + :rtype: :py:class:`~PIL.Image.Image` + """ + + image1.load() + image2.load() + return image1._new(image1.im.chop_difference(image2.im)) + + +def multiply(image1: Image.Image, image2: Image.Image) -> Image.Image: + """ + Superimposes two images on top of each other. + + If you multiply an image with a solid black image, the result is black. If + you multiply with a solid white image, the image is unaffected. :: + + out = image1 * image2 / MAX + + :rtype: :py:class:`~PIL.Image.Image` + """ + + image1.load() + image2.load() + return image1._new(image1.im.chop_multiply(image2.im)) + + +def screen(image1: Image.Image, image2: Image.Image) -> Image.Image: + """ + Superimposes two inverted images on top of each other. :: + + out = MAX - ((MAX - image1) * (MAX - image2) / MAX) + + :rtype: :py:class:`~PIL.Image.Image` + """ + + image1.load() + image2.load() + return image1._new(image1.im.chop_screen(image2.im)) + + +def soft_light(image1: Image.Image, image2: Image.Image) -> Image.Image: + """ + Superimposes two images on top of each other using the Soft Light algorithm + + :rtype: :py:class:`~PIL.Image.Image` + """ + + image1.load() + image2.load() + return image1._new(image1.im.chop_soft_light(image2.im)) + + +def hard_light(image1: Image.Image, image2: Image.Image) -> Image.Image: + """ + Superimposes two images on top of each other using the Hard Light algorithm + + :rtype: :py:class:`~PIL.Image.Image` + """ + + image1.load() + image2.load() + return image1._new(image1.im.chop_hard_light(image2.im)) + + +def overlay(image1: Image.Image, image2: Image.Image) -> Image.Image: + """ + Superimposes two images on top of each other using the Overlay algorithm + + :rtype: :py:class:`~PIL.Image.Image` + """ + + image1.load() + image2.load() + return image1._new(image1.im.chop_overlay(image2.im)) + + +def add( + image1: Image.Image, image2: Image.Image, scale: float = 1.0, offset: float = 0 +) -> Image.Image: + """ + Adds two images, dividing the result by scale and adding the + offset. If omitted, scale defaults to 1.0, and offset to 0.0. :: + + out = ((image1 + image2) / scale + offset) + + :rtype: :py:class:`~PIL.Image.Image` + """ + + image1.load() + image2.load() + return image1._new(image1.im.chop_add(image2.im, scale, offset)) + + +def subtract( + image1: Image.Image, image2: Image.Image, scale: float = 1.0, offset: float = 0 +) -> Image.Image: + """ + Subtracts two images, dividing the result by scale and adding the offset. + If omitted, scale defaults to 1.0, and offset to 0.0. :: + + out = ((image1 - image2) / scale + offset) + + :rtype: :py:class:`~PIL.Image.Image` + """ + + image1.load() + image2.load() + return image1._new(image1.im.chop_subtract(image2.im, scale, offset)) + + +def add_modulo(image1: Image.Image, image2: Image.Image) -> Image.Image: + """Add two images, without clipping the result. :: + + out = ((image1 + image2) % MAX) + + :rtype: :py:class:`~PIL.Image.Image` + """ + + image1.load() + image2.load() + return image1._new(image1.im.chop_add_modulo(image2.im)) + + +def subtract_modulo(image1: Image.Image, image2: Image.Image) -> Image.Image: + """Subtract two images, without clipping the result. :: + + out = ((image1 - image2) % MAX) + + :rtype: :py:class:`~PIL.Image.Image` + """ + + image1.load() + image2.load() + return image1._new(image1.im.chop_subtract_modulo(image2.im)) + + +def logical_and(image1: Image.Image, image2: Image.Image) -> Image.Image: + """Logical AND between two images. + + Both of the images must have mode "1". If you would like to perform a + logical AND on an image with a mode other than "1", try + :py:meth:`~PIL.ImageChops.multiply` instead, using a black-and-white mask + as the second image. :: + + out = ((image1 and image2) % MAX) + + :rtype: :py:class:`~PIL.Image.Image` + """ + + image1.load() + image2.load() + return image1._new(image1.im.chop_and(image2.im)) + + +def logical_or(image1: Image.Image, image2: Image.Image) -> Image.Image: + """Logical OR between two images. + + Both of the images must have mode "1". :: + + out = ((image1 or image2) % MAX) + + :rtype: :py:class:`~PIL.Image.Image` + """ + + image1.load() + image2.load() + return image1._new(image1.im.chop_or(image2.im)) + + +def logical_xor(image1: Image.Image, image2: Image.Image) -> Image.Image: + """Logical XOR between two images. + + Both of the images must have mode "1". :: + + out = ((bool(image1) != bool(image2)) % MAX) + + :rtype: :py:class:`~PIL.Image.Image` + """ + + image1.load() + image2.load() + return image1._new(image1.im.chop_xor(image2.im)) + + +def blend(image1: Image.Image, image2: Image.Image, alpha: float) -> Image.Image: + """Blend images using constant transparency weight. Alias for + :py:func:`PIL.Image.blend`. + + :rtype: :py:class:`~PIL.Image.Image` + """ + + return Image.blend(image1, image2, alpha) + + +def composite( + image1: Image.Image, image2: Image.Image, mask: Image.Image +) -> Image.Image: + """Create composite using transparency mask. Alias for + :py:func:`PIL.Image.composite`. + + :rtype: :py:class:`~PIL.Image.Image` + """ + + return Image.composite(image1, image2, mask) + + +def offset(image: Image.Image, xoffset: int, yoffset: int | None = None) -> Image.Image: + """Returns a copy of the image where data has been offset by the given + distances. Data wraps around the edges. If ``yoffset`` is omitted, it + is assumed to be equal to ``xoffset``. + + :param image: Input image. + :param xoffset: The horizontal distance. + :param yoffset: The vertical distance. If omitted, both + distances are set to the same value. + :rtype: :py:class:`~PIL.Image.Image` + """ + + if yoffset is None: + yoffset = xoffset + image.load() + return image._new(image.im.offset(xoffset, yoffset)) diff --git a/.venv/lib/python3.11/site-packages/PIL/ImageCms.py b/.venv/lib/python3.11/site-packages/PIL/ImageCms.py new file mode 100644 index 0000000000000000000000000000000000000000..388a9296f8b4699db3f52d111a7136899ee0cd02 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/ImageCms.py @@ -0,0 +1,1078 @@ +# The Python Imaging Library. +# $Id$ + +# Optional color management support, based on Kevin Cazabon's PyCMS +# library. + +# Originally released under LGPL. Graciously donated to PIL in +# March 2009, for distribution under the standard PIL license + +# History: + +# 2009-03-08 fl Added to PIL. + +# Copyright (C) 2002-2003 Kevin Cazabon +# Copyright (c) 2009 by Fredrik Lundh +# Copyright (c) 2013 by Eric Soroos + +# See the README file for information on usage and redistribution. See +# below for the original description. +from __future__ import annotations + +import operator +import sys +from enum import IntEnum, IntFlag +from functools import reduce +from typing import Any, Literal, SupportsFloat, SupportsInt, Union + +from . import Image +from ._deprecate import deprecate +from ._typing import SupportsRead + +try: + from . import _imagingcms as core + + _CmsProfileCompatible = Union[ + str, SupportsRead[bytes], core.CmsProfile, "ImageCmsProfile" + ] +except ImportError as ex: + # Allow error import for doc purposes, but error out when accessing + # anything in core. + from ._util import DeferredError + + core = DeferredError.new(ex) + +_DESCRIPTION = """ +pyCMS + + a Python / PIL interface to the littleCMS ICC Color Management System + Copyright (C) 2002-2003 Kevin Cazabon + kevin@cazabon.com + https://www.cazabon.com + + pyCMS home page: https://www.cazabon.com/pyCMS + littleCMS home page: https://www.littlecms.com + (littleCMS is Copyright (C) 1998-2001 Marti Maria) + + Originally released under LGPL. Graciously donated to PIL in + March 2009, for distribution under the standard PIL license + + The pyCMS.py module provides a "clean" interface between Python/PIL and + pyCMSdll, taking care of some of the more complex handling of the direct + pyCMSdll functions, as well as error-checking and making sure that all + relevant data is kept together. + + While it is possible to call pyCMSdll functions directly, it's not highly + recommended. + + Version History: + + 1.0.0 pil Oct 2013 Port to LCMS 2. + + 0.1.0 pil mod March 10, 2009 + + Renamed display profile to proof profile. The proof + profile is the profile of the device that is being + simulated, not the profile of the device which is + actually used to display/print the final simulation + (that'd be the output profile) - also see LCMSAPI.txt + input colorspace -> using 'renderingIntent' -> proof + colorspace -> using 'proofRenderingIntent' -> output + colorspace + + Added LCMS FLAGS support. + Added FLAGS["SOFTPROOFING"] as default flag for + buildProofTransform (otherwise the proof profile/intent + would be ignored). + + 0.1.0 pil March 2009 - added to PIL, as PIL.ImageCms + + 0.0.2 alpha Jan 6, 2002 + + Added try/except statements around type() checks of + potential CObjects... Python won't let you use type() + on them, and raises a TypeError (stupid, if you ask + me!) + + Added buildProofTransformFromOpenProfiles() function. + Additional fixes in DLL, see DLL code for details. + + 0.0.1 alpha first public release, Dec. 26, 2002 + + Known to-do list with current version (of Python interface, not pyCMSdll): + + none + +""" + +_VERSION = "1.0.0 pil" + + +# --------------------------------------------------------------------. + + +# +# intent/direction values + + +class Intent(IntEnum): + PERCEPTUAL = 0 + RELATIVE_COLORIMETRIC = 1 + SATURATION = 2 + ABSOLUTE_COLORIMETRIC = 3 + + +class Direction(IntEnum): + INPUT = 0 + OUTPUT = 1 + PROOF = 2 + + +# +# flags + + +class Flags(IntFlag): + """Flags and documentation are taken from ``lcms2.h``.""" + + NONE = 0 + NOCACHE = 0x0040 + """Inhibit 1-pixel cache""" + NOOPTIMIZE = 0x0100 + """Inhibit optimizations""" + NULLTRANSFORM = 0x0200 + """Don't transform anyway""" + GAMUTCHECK = 0x1000 + """Out of Gamut alarm""" + SOFTPROOFING = 0x4000 + """Do softproofing""" + BLACKPOINTCOMPENSATION = 0x2000 + NOWHITEONWHITEFIXUP = 0x0004 + """Don't fix scum dot""" + HIGHRESPRECALC = 0x0400 + """Use more memory to give better accuracy""" + LOWRESPRECALC = 0x0800 + """Use less memory to minimize resources""" + # this should be 8BITS_DEVICELINK, but that is not a valid name in Python: + USE_8BITS_DEVICELINK = 0x0008 + """Create 8 bits devicelinks""" + GUESSDEVICECLASS = 0x0020 + """Guess device class (for ``transform2devicelink``)""" + KEEP_SEQUENCE = 0x0080 + """Keep profile sequence for devicelink creation""" + FORCE_CLUT = 0x0002 + """Force CLUT optimization""" + CLUT_POST_LINEARIZATION = 0x0001 + """create postlinearization tables if possible""" + CLUT_PRE_LINEARIZATION = 0x0010 + """create prelinearization tables if possible""" + NONEGATIVES = 0x8000 + """Prevent negative numbers in floating point transforms""" + COPY_ALPHA = 0x04000000 + """Alpha channels are copied on ``cmsDoTransform()``""" + NODEFAULTRESOURCEDEF = 0x01000000 + + _GRIDPOINTS_1 = 1 << 16 + _GRIDPOINTS_2 = 2 << 16 + _GRIDPOINTS_4 = 4 << 16 + _GRIDPOINTS_8 = 8 << 16 + _GRIDPOINTS_16 = 16 << 16 + _GRIDPOINTS_32 = 32 << 16 + _GRIDPOINTS_64 = 64 << 16 + _GRIDPOINTS_128 = 128 << 16 + + @staticmethod + def GRIDPOINTS(n: int) -> Flags: + """ + Fine-tune control over number of gridpoints + + :param n: :py:class:`int` in range ``0 <= n <= 255`` + """ + return Flags.NONE | ((n & 0xFF) << 16) + + +_MAX_FLAG = reduce(operator.or_, Flags) + + +_FLAGS = { + "MATRIXINPUT": 1, + "MATRIXOUTPUT": 2, + "MATRIXONLY": (1 | 2), + "NOWHITEONWHITEFIXUP": 4, # Don't hot fix scum dot + # Don't create prelinearization tables on precalculated transforms + # (internal use): + "NOPRELINEARIZATION": 16, + "GUESSDEVICECLASS": 32, # Guess device class (for transform2devicelink) + "NOTCACHE": 64, # Inhibit 1-pixel cache + "NOTPRECALC": 256, + "NULLTRANSFORM": 512, # Don't transform anyway + "HIGHRESPRECALC": 1024, # Use more memory to give better accuracy + "LOWRESPRECALC": 2048, # Use less memory to minimize resources + "WHITEBLACKCOMPENSATION": 8192, + "BLACKPOINTCOMPENSATION": 8192, + "GAMUTCHECK": 4096, # Out of Gamut alarm + "SOFTPROOFING": 16384, # Do softproofing + "PRESERVEBLACK": 32768, # Black preservation + "NODEFAULTRESOURCEDEF": 16777216, # CRD special + "GRIDPOINTS": lambda n: (n & 0xFF) << 16, # Gridpoints +} + + +# --------------------------------------------------------------------. +# Experimental PIL-level API +# --------------------------------------------------------------------. + +## +# Profile. + + +class ImageCmsProfile: + def __init__(self, profile: str | SupportsRead[bytes] | core.CmsProfile) -> None: + """ + :param profile: Either a string representing a filename, + a file like object containing a profile or a + low-level profile object + + """ + self.filename: str | None = None + + if isinstance(profile, str): + if sys.platform == "win32": + profile_bytes_path = profile.encode() + try: + profile_bytes_path.decode("ascii") + except UnicodeDecodeError: + with open(profile, "rb") as f: + self.profile = core.profile_frombytes(f.read()) + return + self.filename = profile + self.profile = core.profile_open(profile) + elif hasattr(profile, "read"): + self.profile = core.profile_frombytes(profile.read()) + elif isinstance(profile, core.CmsProfile): + self.profile = profile + else: + msg = "Invalid type for Profile" # type: ignore[unreachable] + raise TypeError(msg) + + def __getattr__(self, name: str) -> Any: + if name in ("product_name", "product_info"): + deprecate(f"ImageCms.ImageCmsProfile.{name}", 13) + return None + msg = f"'{self.__class__.__name__}' object has no attribute '{name}'" + raise AttributeError(msg) + + def tobytes(self) -> bytes: + """ + Returns the profile in a format suitable for embedding in + saved images. + + :returns: a bytes object containing the ICC profile. + """ + + return core.profile_tobytes(self.profile) + + +class ImageCmsTransform(Image.ImagePointHandler): + """ + Transform. This can be used with the procedural API, or with the standard + :py:func:`~PIL.Image.Image.point` method. + + Will return the output profile in the ``output.info['icc_profile']``. + """ + + def __init__( + self, + input: ImageCmsProfile, + output: ImageCmsProfile, + input_mode: str, + output_mode: str, + intent: Intent = Intent.PERCEPTUAL, + proof: ImageCmsProfile | None = None, + proof_intent: Intent = Intent.ABSOLUTE_COLORIMETRIC, + flags: Flags = Flags.NONE, + ): + if proof is None: + self.transform = core.buildTransform( + input.profile, output.profile, input_mode, output_mode, intent, flags + ) + else: + self.transform = core.buildProofTransform( + input.profile, + output.profile, + proof.profile, + input_mode, + output_mode, + intent, + proof_intent, + flags, + ) + # Note: inputMode and outputMode are for pyCMS compatibility only + self.input_mode = self.inputMode = input_mode + self.output_mode = self.outputMode = output_mode + + self.output_profile = output + + def point(self, im: Image.Image) -> Image.Image: + return self.apply(im) + + def apply(self, im: Image.Image, imOut: Image.Image | None = None) -> Image.Image: + if im.mode != self.input_mode: + msg = "mode mismatch" + raise ValueError(msg) + if imOut is not None: + if imOut.mode != self.output_mode: + msg = "mode mismatch" + raise ValueError(msg) + else: + imOut = Image.new(self.output_mode, im.size, None) + self.transform.apply(im.getim(), imOut.getim()) + imOut.info["icc_profile"] = self.output_profile.tobytes() + return imOut + + def apply_in_place(self, im: Image.Image) -> Image.Image: + return self.apply(im, im) + + +def get_display_profile(handle: SupportsInt | None = None) -> ImageCmsProfile | None: + """ + (experimental) Fetches the profile for the current display device. + + :returns: ``None`` if the profile is not known. + """ + + if sys.platform != "win32": + return None + + from . import ImageWin # type: ignore[unused-ignore, unreachable] + + if isinstance(handle, ImageWin.HDC): + profile = core.get_display_profile_win32(int(handle), 1) + else: + profile = core.get_display_profile_win32(int(handle or 0)) + if profile is None: + return None + return ImageCmsProfile(profile) + + +# --------------------------------------------------------------------. +# pyCMS compatible layer +# --------------------------------------------------------------------. + + +class PyCMSError(Exception): + """(pyCMS) Exception class. + This is used for all errors in the pyCMS API.""" + + pass + + +def profileToProfile( + im: Image.Image, + inputProfile: _CmsProfileCompatible, + outputProfile: _CmsProfileCompatible, + renderingIntent: Intent = Intent.PERCEPTUAL, + outputMode: str | None = None, + inPlace: bool = False, + flags: Flags = Flags.NONE, +) -> Image.Image | None: + """ + (pyCMS) Applies an ICC transformation to a given image, mapping from + ``inputProfile`` to ``outputProfile``. + + If the input or output profiles specified are not valid filenames, a + :exc:`PyCMSError` will be raised. If ``inPlace`` is ``True`` and + ``outputMode != im.mode``, a :exc:`PyCMSError` will be raised. + If an error occurs during application of the profiles, + a :exc:`PyCMSError` will be raised. + If ``outputMode`` is not a mode supported by the ``outputProfile`` (or by pyCMS), + a :exc:`PyCMSError` will be raised. + + This function applies an ICC transformation to im from ``inputProfile``'s + color space to ``outputProfile``'s color space using the specified rendering + intent to decide how to handle out-of-gamut colors. + + ``outputMode`` can be used to specify that a color mode conversion is to + be done using these profiles, but the specified profiles must be able + to handle that mode. I.e., if converting im from RGB to CMYK using + profiles, the input profile must handle RGB data, and the output + profile must handle CMYK data. + + :param im: An open :py:class:`~PIL.Image.Image` object (i.e. Image.new(...) + or Image.open(...), etc.) + :param inputProfile: String, as a valid filename path to the ICC input + profile you wish to use for this image, or a profile object + :param outputProfile: String, as a valid filename path to the ICC output + profile you wish to use for this image, or a profile object + :param renderingIntent: Integer (0-3) specifying the rendering intent you + wish to use for the transform + + ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT) + ImageCms.Intent.RELATIVE_COLORIMETRIC = 1 + ImageCms.Intent.SATURATION = 2 + ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3 + + see the pyCMS documentation for details on rendering intents and what + they do. + :param outputMode: A valid PIL mode for the output image (i.e. "RGB", + "CMYK", etc.). Note: if rendering the image "inPlace", outputMode + MUST be the same mode as the input, or omitted completely. If + omitted, the outputMode will be the same as the mode of the input + image (im.mode) + :param inPlace: Boolean. If ``True``, the original image is modified in-place, + and ``None`` is returned. If ``False`` (default), a new + :py:class:`~PIL.Image.Image` object is returned with the transform applied. + :param flags: Integer (0-...) specifying additional flags + :returns: Either None or a new :py:class:`~PIL.Image.Image` object, depending on + the value of ``inPlace`` + :exception PyCMSError: + """ + + if outputMode is None: + outputMode = im.mode + + if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3): + msg = "renderingIntent must be an integer between 0 and 3" + raise PyCMSError(msg) + + if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG): + msg = f"flags must be an integer between 0 and {_MAX_FLAG}" + raise PyCMSError(msg) + + try: + if not isinstance(inputProfile, ImageCmsProfile): + inputProfile = ImageCmsProfile(inputProfile) + if not isinstance(outputProfile, ImageCmsProfile): + outputProfile = ImageCmsProfile(outputProfile) + transform = ImageCmsTransform( + inputProfile, + outputProfile, + im.mode, + outputMode, + renderingIntent, + flags=flags, + ) + if inPlace: + transform.apply_in_place(im) + imOut = None + else: + imOut = transform.apply(im) + except (OSError, TypeError, ValueError) as v: + raise PyCMSError(v) from v + + return imOut + + +def getOpenProfile( + profileFilename: str | SupportsRead[bytes] | core.CmsProfile, +) -> ImageCmsProfile: + """ + (pyCMS) Opens an ICC profile file. + + The PyCMSProfile object can be passed back into pyCMS for use in creating + transforms and such (as in ImageCms.buildTransformFromOpenProfiles()). + + If ``profileFilename`` is not a valid filename for an ICC profile, + a :exc:`PyCMSError` will be raised. + + :param profileFilename: String, as a valid filename path to the ICC profile + you wish to open, or a file-like object. + :returns: A CmsProfile class object. + :exception PyCMSError: + """ + + try: + return ImageCmsProfile(profileFilename) + except (OSError, TypeError, ValueError) as v: + raise PyCMSError(v) from v + + +def buildTransform( + inputProfile: _CmsProfileCompatible, + outputProfile: _CmsProfileCompatible, + inMode: str, + outMode: str, + renderingIntent: Intent = Intent.PERCEPTUAL, + flags: Flags = Flags.NONE, +) -> ImageCmsTransform: + """ + (pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the + ``outputProfile``. Use applyTransform to apply the transform to a given + image. + + If the input or output profiles specified are not valid filenames, a + :exc:`PyCMSError` will be raised. If an error occurs during creation + of the transform, a :exc:`PyCMSError` will be raised. + + If ``inMode`` or ``outMode`` are not a mode supported by the ``outputProfile`` + (or by pyCMS), a :exc:`PyCMSError` will be raised. + + This function builds and returns an ICC transform from the ``inputProfile`` + to the ``outputProfile`` using the ``renderingIntent`` to determine what to do + with out-of-gamut colors. It will ONLY work for converting images that + are in ``inMode`` to images that are in ``outMode`` color format (PIL mode, + i.e. "RGB", "RGBA", "CMYK", etc.). + + Building the transform is a fair part of the overhead in + ImageCms.profileToProfile(), so if you're planning on converting multiple + images using the same input/output settings, this can save you time. + Once you have a transform object, it can be used with + ImageCms.applyProfile() to convert images without the need to re-compute + the lookup table for the transform. + + The reason pyCMS returns a class object rather than a handle directly + to the transform is that it needs to keep track of the PIL input/output + modes that the transform is meant for. These attributes are stored in + the ``inMode`` and ``outMode`` attributes of the object (which can be + manually overridden if you really want to, but I don't know of any + time that would be of use, or would even work). + + :param inputProfile: String, as a valid filename path to the ICC input + profile you wish to use for this transform, or a profile object + :param outputProfile: String, as a valid filename path to the ICC output + profile you wish to use for this transform, or a profile object + :param inMode: String, as a valid PIL mode that the appropriate profile + also supports (i.e. "RGB", "RGBA", "CMYK", etc.) + :param outMode: String, as a valid PIL mode that the appropriate profile + also supports (i.e. "RGB", "RGBA", "CMYK", etc.) + :param renderingIntent: Integer (0-3) specifying the rendering intent you + wish to use for the transform + + ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT) + ImageCms.Intent.RELATIVE_COLORIMETRIC = 1 + ImageCms.Intent.SATURATION = 2 + ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3 + + see the pyCMS documentation for details on rendering intents and what + they do. + :param flags: Integer (0-...) specifying additional flags + :returns: A CmsTransform class object. + :exception PyCMSError: + """ + + if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3): + msg = "renderingIntent must be an integer between 0 and 3" + raise PyCMSError(msg) + + if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG): + msg = f"flags must be an integer between 0 and {_MAX_FLAG}" + raise PyCMSError(msg) + + try: + if not isinstance(inputProfile, ImageCmsProfile): + inputProfile = ImageCmsProfile(inputProfile) + if not isinstance(outputProfile, ImageCmsProfile): + outputProfile = ImageCmsProfile(outputProfile) + return ImageCmsTransform( + inputProfile, outputProfile, inMode, outMode, renderingIntent, flags=flags + ) + except (OSError, TypeError, ValueError) as v: + raise PyCMSError(v) from v + + +def buildProofTransform( + inputProfile: _CmsProfileCompatible, + outputProfile: _CmsProfileCompatible, + proofProfile: _CmsProfileCompatible, + inMode: str, + outMode: str, + renderingIntent: Intent = Intent.PERCEPTUAL, + proofRenderingIntent: Intent = Intent.ABSOLUTE_COLORIMETRIC, + flags: Flags = Flags.SOFTPROOFING, +) -> ImageCmsTransform: + """ + (pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the + ``outputProfile``, but tries to simulate the result that would be + obtained on the ``proofProfile`` device. + + If the input, output, or proof profiles specified are not valid + filenames, a :exc:`PyCMSError` will be raised. + + If an error occurs during creation of the transform, + a :exc:`PyCMSError` will be raised. + + If ``inMode`` or ``outMode`` are not a mode supported by the ``outputProfile`` + (or by pyCMS), a :exc:`PyCMSError` will be raised. + + This function builds and returns an ICC transform from the ``inputProfile`` + to the ``outputProfile``, but tries to simulate the result that would be + obtained on the ``proofProfile`` device using ``renderingIntent`` and + ``proofRenderingIntent`` to determine what to do with out-of-gamut + colors. This is known as "soft-proofing". It will ONLY work for + converting images that are in ``inMode`` to images that are in outMode + color format (PIL mode, i.e. "RGB", "RGBA", "CMYK", etc.). + + Usage of the resulting transform object is exactly the same as with + ImageCms.buildTransform(). + + Proof profiling is generally used when using an output device to get a + good idea of what the final printed/displayed image would look like on + the ``proofProfile`` device when it's quicker and easier to use the + output device for judging color. Generally, this means that the + output device is a monitor, or a dye-sub printer (etc.), and the simulated + device is something more expensive, complicated, or time consuming + (making it difficult to make a real print for color judgement purposes). + + Soft-proofing basically functions by adjusting the colors on the + output device to match the colors of the device being simulated. However, + when the simulated device has a much wider gamut than the output + device, you may obtain marginal results. + + :param inputProfile: String, as a valid filename path to the ICC input + profile you wish to use for this transform, or a profile object + :param outputProfile: String, as a valid filename path to the ICC output + (monitor, usually) profile you wish to use for this transform, or a + profile object + :param proofProfile: String, as a valid filename path to the ICC proof + profile you wish to use for this transform, or a profile object + :param inMode: String, as a valid PIL mode that the appropriate profile + also supports (i.e. "RGB", "RGBA", "CMYK", etc.) + :param outMode: String, as a valid PIL mode that the appropriate profile + also supports (i.e. "RGB", "RGBA", "CMYK", etc.) + :param renderingIntent: Integer (0-3) specifying the rendering intent you + wish to use for the input->proof (simulated) transform + + ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT) + ImageCms.Intent.RELATIVE_COLORIMETRIC = 1 + ImageCms.Intent.SATURATION = 2 + ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3 + + see the pyCMS documentation for details on rendering intents and what + they do. + :param proofRenderingIntent: Integer (0-3) specifying the rendering intent + you wish to use for proof->output transform + + ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT) + ImageCms.Intent.RELATIVE_COLORIMETRIC = 1 + ImageCms.Intent.SATURATION = 2 + ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3 + + see the pyCMS documentation for details on rendering intents and what + they do. + :param flags: Integer (0-...) specifying additional flags + :returns: A CmsTransform class object. + :exception PyCMSError: + """ + + if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3): + msg = "renderingIntent must be an integer between 0 and 3" + raise PyCMSError(msg) + + if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG): + msg = f"flags must be an integer between 0 and {_MAX_FLAG}" + raise PyCMSError(msg) + + try: + if not isinstance(inputProfile, ImageCmsProfile): + inputProfile = ImageCmsProfile(inputProfile) + if not isinstance(outputProfile, ImageCmsProfile): + outputProfile = ImageCmsProfile(outputProfile) + if not isinstance(proofProfile, ImageCmsProfile): + proofProfile = ImageCmsProfile(proofProfile) + return ImageCmsTransform( + inputProfile, + outputProfile, + inMode, + outMode, + renderingIntent, + proofProfile, + proofRenderingIntent, + flags, + ) + except (OSError, TypeError, ValueError) as v: + raise PyCMSError(v) from v + + +buildTransformFromOpenProfiles = buildTransform +buildProofTransformFromOpenProfiles = buildProofTransform + + +def applyTransform( + im: Image.Image, transform: ImageCmsTransform, inPlace: bool = False +) -> Image.Image | None: + """ + (pyCMS) Applies a transform to a given image. + + If ``im.mode != transform.input_mode``, a :exc:`PyCMSError` is raised. + + If ``inPlace`` is ``True`` and ``transform.input_mode != transform.output_mode``, a + :exc:`PyCMSError` is raised. + + If ``im.mode``, ``transform.input_mode`` or ``transform.output_mode`` is not + supported by pyCMSdll or the profiles you used for the transform, a + :exc:`PyCMSError` is raised. + + If an error occurs while the transform is being applied, + a :exc:`PyCMSError` is raised. + + This function applies a pre-calculated transform (from + ImageCms.buildTransform() or ImageCms.buildTransformFromOpenProfiles()) + to an image. The transform can be used for multiple images, saving + considerable calculation time if doing the same conversion multiple times. + + If you want to modify im in-place instead of receiving a new image as + the return value, set ``inPlace`` to ``True``. This can only be done if + ``transform.input_mode`` and ``transform.output_mode`` are the same, because we + can't change the mode in-place (the buffer sizes for some modes are + different). The default behavior is to return a new :py:class:`~PIL.Image.Image` + object of the same dimensions in mode ``transform.output_mode``. + + :param im: An :py:class:`~PIL.Image.Image` object, and ``im.mode`` must be the same + as the ``input_mode`` supported by the transform. + :param transform: A valid CmsTransform class object + :param inPlace: Bool. If ``True``, ``im`` is modified in place and ``None`` is + returned, if ``False``, a new :py:class:`~PIL.Image.Image` object with the + transform applied is returned (and ``im`` is not changed). The default is + ``False``. + :returns: Either ``None``, or a new :py:class:`~PIL.Image.Image` object, + depending on the value of ``inPlace``. The profile will be returned in + the image's ``info['icc_profile']``. + :exception PyCMSError: + """ + + try: + if inPlace: + transform.apply_in_place(im) + imOut = None + else: + imOut = transform.apply(im) + except (TypeError, ValueError) as v: + raise PyCMSError(v) from v + + return imOut + + +def createProfile( + colorSpace: Literal["LAB", "XYZ", "sRGB"], colorTemp: SupportsFloat = 0 +) -> core.CmsProfile: + """ + (pyCMS) Creates a profile. + + If colorSpace not in ``["LAB", "XYZ", "sRGB"]``, + a :exc:`PyCMSError` is raised. + + If using LAB and ``colorTemp`` is not a positive integer, + a :exc:`PyCMSError` is raised. + + If an error occurs while creating the profile, + a :exc:`PyCMSError` is raised. + + Use this function to create common profiles on-the-fly instead of + having to supply a profile on disk and knowing the path to it. It + returns a normal CmsProfile object that can be passed to + ImageCms.buildTransformFromOpenProfiles() to create a transform to apply + to images. + + :param colorSpace: String, the color space of the profile you wish to + create. + Currently only "LAB", "XYZ", and "sRGB" are supported. + :param colorTemp: Positive number for the white point for the profile, in + degrees Kelvin (i.e. 5000, 6500, 9600, etc.). The default is for D50 + illuminant if omitted (5000k). colorTemp is ONLY applied to LAB + profiles, and is ignored for XYZ and sRGB. + :returns: A CmsProfile class object + :exception PyCMSError: + """ + + if colorSpace not in ["LAB", "XYZ", "sRGB"]: + msg = ( + f"Color space not supported for on-the-fly profile creation ({colorSpace})" + ) + raise PyCMSError(msg) + + if colorSpace == "LAB": + try: + colorTemp = float(colorTemp) + except (TypeError, ValueError) as e: + msg = f'Color temperature must be numeric, "{colorTemp}" not valid' + raise PyCMSError(msg) from e + + try: + return core.createProfile(colorSpace, colorTemp) + except (TypeError, ValueError) as v: + raise PyCMSError(v) from v + + +def getProfileName(profile: _CmsProfileCompatible) -> str: + """ + + (pyCMS) Gets the internal product name for the given profile. + + If ``profile`` isn't a valid CmsProfile object or filename to a profile, + a :exc:`PyCMSError` is raised If an error occurs while trying + to obtain the name tag, a :exc:`PyCMSError` is raised. + + Use this function to obtain the INTERNAL name of the profile (stored + in an ICC tag in the profile itself), usually the one used when the + profile was originally created. Sometimes this tag also contains + additional information supplied by the creator. + + :param profile: EITHER a valid CmsProfile object, OR a string of the + filename of an ICC profile. + :returns: A string containing the internal name of the profile as stored + in an ICC tag. + :exception PyCMSError: + """ + + try: + # add an extra newline to preserve pyCMS compatibility + if not isinstance(profile, ImageCmsProfile): + profile = ImageCmsProfile(profile) + # do it in python, not c. + # // name was "%s - %s" (model, manufacturer) || Description , + # // but if the Model and Manufacturer were the same or the model + # // was long, Just the model, in 1.x + model = profile.profile.model + manufacturer = profile.profile.manufacturer + + if not (model or manufacturer): + return (profile.profile.profile_description or "") + "\n" + if not manufacturer or (model and len(model) > 30): + return f"{model}\n" + return f"{model} - {manufacturer}\n" + + except (AttributeError, OSError, TypeError, ValueError) as v: + raise PyCMSError(v) from v + + +def getProfileInfo(profile: _CmsProfileCompatible) -> str: + """ + (pyCMS) Gets the internal product information for the given profile. + + If ``profile`` isn't a valid CmsProfile object or filename to a profile, + a :exc:`PyCMSError` is raised. + + If an error occurs while trying to obtain the info tag, + a :exc:`PyCMSError` is raised. + + Use this function to obtain the information stored in the profile's + info tag. This often contains details about the profile, and how it + was created, as supplied by the creator. + + :param profile: EITHER a valid CmsProfile object, OR a string of the + filename of an ICC profile. + :returns: A string containing the internal profile information stored in + an ICC tag. + :exception PyCMSError: + """ + + try: + if not isinstance(profile, ImageCmsProfile): + profile = ImageCmsProfile(profile) + # add an extra newline to preserve pyCMS compatibility + # Python, not C. the white point bits weren't working well, + # so skipping. + # info was description \r\n\r\n copyright \r\n\r\n K007 tag \r\n\r\n whitepoint + description = profile.profile.profile_description + cpright = profile.profile.copyright + elements = [element for element in (description, cpright) if element] + return "\r\n\r\n".join(elements) + "\r\n\r\n" + + except (AttributeError, OSError, TypeError, ValueError) as v: + raise PyCMSError(v) from v + + +def getProfileCopyright(profile: _CmsProfileCompatible) -> str: + """ + (pyCMS) Gets the copyright for the given profile. + + If ``profile`` isn't a valid CmsProfile object or filename to a profile, a + :exc:`PyCMSError` is raised. + + If an error occurs while trying to obtain the copyright tag, + a :exc:`PyCMSError` is raised. + + Use this function to obtain the information stored in the profile's + copyright tag. + + :param profile: EITHER a valid CmsProfile object, OR a string of the + filename of an ICC profile. + :returns: A string containing the internal profile information stored in + an ICC tag. + :exception PyCMSError: + """ + try: + # add an extra newline to preserve pyCMS compatibility + if not isinstance(profile, ImageCmsProfile): + profile = ImageCmsProfile(profile) + return (profile.profile.copyright or "") + "\n" + except (AttributeError, OSError, TypeError, ValueError) as v: + raise PyCMSError(v) from v + + +def getProfileManufacturer(profile: _CmsProfileCompatible) -> str: + """ + (pyCMS) Gets the manufacturer for the given profile. + + If ``profile`` isn't a valid CmsProfile object or filename to a profile, a + :exc:`PyCMSError` is raised. + + If an error occurs while trying to obtain the manufacturer tag, a + :exc:`PyCMSError` is raised. + + Use this function to obtain the information stored in the profile's + manufacturer tag. + + :param profile: EITHER a valid CmsProfile object, OR a string of the + filename of an ICC profile. + :returns: A string containing the internal profile information stored in + an ICC tag. + :exception PyCMSError: + """ + try: + # add an extra newline to preserve pyCMS compatibility + if not isinstance(profile, ImageCmsProfile): + profile = ImageCmsProfile(profile) + return (profile.profile.manufacturer or "") + "\n" + except (AttributeError, OSError, TypeError, ValueError) as v: + raise PyCMSError(v) from v + + +def getProfileModel(profile: _CmsProfileCompatible) -> str: + """ + (pyCMS) Gets the model for the given profile. + + If ``profile`` isn't a valid CmsProfile object or filename to a profile, a + :exc:`PyCMSError` is raised. + + If an error occurs while trying to obtain the model tag, + a :exc:`PyCMSError` is raised. + + Use this function to obtain the information stored in the profile's + model tag. + + :param profile: EITHER a valid CmsProfile object, OR a string of the + filename of an ICC profile. + :returns: A string containing the internal profile information stored in + an ICC tag. + :exception PyCMSError: + """ + + try: + # add an extra newline to preserve pyCMS compatibility + if not isinstance(profile, ImageCmsProfile): + profile = ImageCmsProfile(profile) + return (profile.profile.model or "") + "\n" + except (AttributeError, OSError, TypeError, ValueError) as v: + raise PyCMSError(v) from v + + +def getProfileDescription(profile: _CmsProfileCompatible) -> str: + """ + (pyCMS) Gets the description for the given profile. + + If ``profile`` isn't a valid CmsProfile object or filename to a profile, a + :exc:`PyCMSError` is raised. + + If an error occurs while trying to obtain the description tag, + a :exc:`PyCMSError` is raised. + + Use this function to obtain the information stored in the profile's + description tag. + + :param profile: EITHER a valid CmsProfile object, OR a string of the + filename of an ICC profile. + :returns: A string containing the internal profile information stored in an + ICC tag. + :exception PyCMSError: + """ + + try: + # add an extra newline to preserve pyCMS compatibility + if not isinstance(profile, ImageCmsProfile): + profile = ImageCmsProfile(profile) + return (profile.profile.profile_description or "") + "\n" + except (AttributeError, OSError, TypeError, ValueError) as v: + raise PyCMSError(v) from v + + +def getDefaultIntent(profile: _CmsProfileCompatible) -> int: + """ + (pyCMS) Gets the default intent name for the given profile. + + If ``profile`` isn't a valid CmsProfile object or filename to a profile, a + :exc:`PyCMSError` is raised. + + If an error occurs while trying to obtain the default intent, a + :exc:`PyCMSError` is raised. + + Use this function to determine the default (and usually best optimized) + rendering intent for this profile. Most profiles support multiple + rendering intents, but are intended mostly for one type of conversion. + If you wish to use a different intent than returned, use + ImageCms.isIntentSupported() to verify it will work first. + + :param profile: EITHER a valid CmsProfile object, OR a string of the + filename of an ICC profile. + :returns: Integer 0-3 specifying the default rendering intent for this + profile. + + ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT) + ImageCms.Intent.RELATIVE_COLORIMETRIC = 1 + ImageCms.Intent.SATURATION = 2 + ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3 + + see the pyCMS documentation for details on rendering intents and what + they do. + :exception PyCMSError: + """ + + try: + if not isinstance(profile, ImageCmsProfile): + profile = ImageCmsProfile(profile) + return profile.profile.rendering_intent + except (AttributeError, OSError, TypeError, ValueError) as v: + raise PyCMSError(v) from v + + +def isIntentSupported( + profile: _CmsProfileCompatible, intent: Intent, direction: Direction +) -> Literal[-1, 1]: + """ + (pyCMS) Checks if a given intent is supported. + + Use this function to verify that you can use your desired + ``intent`` with ``profile``, and that ``profile`` can be used for the + input/output/proof profile as you desire. + + Some profiles are created specifically for one "direction", can cannot + be used for others. Some profiles can only be used for certain + rendering intents, so it's best to either verify this before trying + to create a transform with them (using this function), or catch the + potential :exc:`PyCMSError` that will occur if they don't + support the modes you select. + + :param profile: EITHER a valid CmsProfile object, OR a string of the + filename of an ICC profile. + :param intent: Integer (0-3) specifying the rendering intent you wish to + use with this profile + + ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT) + ImageCms.Intent.RELATIVE_COLORIMETRIC = 1 + ImageCms.Intent.SATURATION = 2 + ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3 + + see the pyCMS documentation for details on rendering intents and what + they do. + :param direction: Integer specifying if the profile is to be used for + input, output, or proof + + INPUT = 0 (or use ImageCms.Direction.INPUT) + OUTPUT = 1 (or use ImageCms.Direction.OUTPUT) + PROOF = 2 (or use ImageCms.Direction.PROOF) + + :returns: 1 if the intent/direction are supported, -1 if they are not. + :exception PyCMSError: + """ + + try: + if not isinstance(profile, ImageCmsProfile): + profile = ImageCmsProfile(profile) + # FIXME: I get different results for the same data w. different + # compilers. Bug in LittleCMS or in the binding? + if profile.profile.is_intent_supported(intent, direction): + return 1 + else: + return -1 + except (AttributeError, OSError, TypeError, ValueError) as v: + raise PyCMSError(v) from v diff --git a/.venv/lib/python3.11/site-packages/PIL/ImageColor.py b/.venv/lib/python3.11/site-packages/PIL/ImageColor.py new file mode 100644 index 0000000000000000000000000000000000000000..9a15a8eb7597998f1bc9a01e8eae3588c087838b --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/ImageColor.py @@ -0,0 +1,320 @@ +# +# The Python Imaging Library +# $Id$ +# +# map CSS3-style colour description strings to RGB +# +# History: +# 2002-10-24 fl Added support for CSS-style color strings +# 2002-12-15 fl Added RGBA support +# 2004-03-27 fl Fixed remaining int() problems for Python 1.5.2 +# 2004-07-19 fl Fixed gray/grey spelling issues +# 2009-03-05 fl Fixed rounding error in grayscale calculation +# +# Copyright (c) 2002-2004 by Secret Labs AB +# Copyright (c) 2002-2004 by Fredrik Lundh +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import re +from functools import lru_cache + +from . import Image + + +@lru_cache +def getrgb(color: str) -> tuple[int, int, int] | tuple[int, int, int, int]: + """ + Convert a color string to an RGB or RGBA tuple. If the string cannot be + parsed, this function raises a :py:exc:`ValueError` exception. + + .. versionadded:: 1.1.4 + + :param color: A color string + :return: ``(red, green, blue[, alpha])`` + """ + if len(color) > 100: + msg = "color specifier is too long" + raise ValueError(msg) + color = color.lower() + + rgb = colormap.get(color, None) + if rgb: + if isinstance(rgb, tuple): + return rgb + rgb_tuple = getrgb(rgb) + assert len(rgb_tuple) == 3 + colormap[color] = rgb_tuple + return rgb_tuple + + # check for known string formats + if re.match("#[a-f0-9]{3}$", color): + return int(color[1] * 2, 16), int(color[2] * 2, 16), int(color[3] * 2, 16) + + if re.match("#[a-f0-9]{4}$", color): + return ( + int(color[1] * 2, 16), + int(color[2] * 2, 16), + int(color[3] * 2, 16), + int(color[4] * 2, 16), + ) + + if re.match("#[a-f0-9]{6}$", color): + return int(color[1:3], 16), int(color[3:5], 16), int(color[5:7], 16) + + if re.match("#[a-f0-9]{8}$", color): + return ( + int(color[1:3], 16), + int(color[3:5], 16), + int(color[5:7], 16), + int(color[7:9], 16), + ) + + m = re.match(r"rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$", color) + if m: + return int(m.group(1)), int(m.group(2)), int(m.group(3)) + + m = re.match(r"rgb\(\s*(\d+)%\s*,\s*(\d+)%\s*,\s*(\d+)%\s*\)$", color) + if m: + return ( + int((int(m.group(1)) * 255) / 100.0 + 0.5), + int((int(m.group(2)) * 255) / 100.0 + 0.5), + int((int(m.group(3)) * 255) / 100.0 + 0.5), + ) + + m = re.match( + r"hsl\(\s*(\d+\.?\d*)\s*,\s*(\d+\.?\d*)%\s*,\s*(\d+\.?\d*)%\s*\)$", color + ) + if m: + from colorsys import hls_to_rgb + + rgb_floats = hls_to_rgb( + float(m.group(1)) / 360.0, + float(m.group(3)) / 100.0, + float(m.group(2)) / 100.0, + ) + return ( + int(rgb_floats[0] * 255 + 0.5), + int(rgb_floats[1] * 255 + 0.5), + int(rgb_floats[2] * 255 + 0.5), + ) + + m = re.match( + r"hs[bv]\(\s*(\d+\.?\d*)\s*,\s*(\d+\.?\d*)%\s*,\s*(\d+\.?\d*)%\s*\)$", color + ) + if m: + from colorsys import hsv_to_rgb + + rgb_floats = hsv_to_rgb( + float(m.group(1)) / 360.0, + float(m.group(2)) / 100.0, + float(m.group(3)) / 100.0, + ) + return ( + int(rgb_floats[0] * 255 + 0.5), + int(rgb_floats[1] * 255 + 0.5), + int(rgb_floats[2] * 255 + 0.5), + ) + + m = re.match(r"rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$", color) + if m: + return int(m.group(1)), int(m.group(2)), int(m.group(3)), int(m.group(4)) + msg = f"unknown color specifier: {repr(color)}" + raise ValueError(msg) + + +@lru_cache +def getcolor(color: str, mode: str) -> int | tuple[int, ...]: + """ + Same as :py:func:`~PIL.ImageColor.getrgb` for most modes. However, if + ``mode`` is HSV, converts the RGB value to a HSV value, or if ``mode`` is + not color or a palette image, converts the RGB value to a grayscale value. + If the string cannot be parsed, this function raises a :py:exc:`ValueError` + exception. + + .. versionadded:: 1.1.4 + + :param color: A color string + :param mode: Convert result to this mode + :return: ``graylevel, (graylevel, alpha) or (red, green, blue[, alpha])`` + """ + # same as getrgb, but converts the result to the given mode + rgb, alpha = getrgb(color), 255 + if len(rgb) == 4: + alpha = rgb[3] + rgb = rgb[:3] + + if mode == "HSV": + from colorsys import rgb_to_hsv + + r, g, b = rgb + h, s, v = rgb_to_hsv(r / 255, g / 255, b / 255) + return int(h * 255), int(s * 255), int(v * 255) + elif Image.getmodebase(mode) == "L": + r, g, b = rgb + # ITU-R Recommendation 601-2 for nonlinear RGB + # scaled to 24 bits to match the convert's implementation. + graylevel = (r * 19595 + g * 38470 + b * 7471 + 0x8000) >> 16 + if mode[-1] == "A": + return graylevel, alpha + return graylevel + elif mode[-1] == "A": + return rgb + (alpha,) + return rgb + + +colormap: dict[str, str | tuple[int, int, int]] = { + # X11 colour table from https://drafts.csswg.org/css-color-4/, with + # gray/grey spelling issues fixed. This is a superset of HTML 4.0 + # colour names used in CSS 1. + "aliceblue": "#f0f8ff", + "antiquewhite": "#faebd7", + "aqua": "#00ffff", + "aquamarine": "#7fffd4", + "azure": "#f0ffff", + "beige": "#f5f5dc", + "bisque": "#ffe4c4", + "black": "#000000", + "blanchedalmond": "#ffebcd", + "blue": "#0000ff", + "blueviolet": "#8a2be2", + "brown": "#a52a2a", + "burlywood": "#deb887", + "cadetblue": "#5f9ea0", + "chartreuse": "#7fff00", + "chocolate": "#d2691e", + "coral": "#ff7f50", + "cornflowerblue": "#6495ed", + "cornsilk": "#fff8dc", + "crimson": "#dc143c", + "cyan": "#00ffff", + "darkblue": "#00008b", + "darkcyan": "#008b8b", + "darkgoldenrod": "#b8860b", + "darkgray": "#a9a9a9", + "darkgrey": "#a9a9a9", + "darkgreen": "#006400", + "darkkhaki": "#bdb76b", + "darkmagenta": "#8b008b", + "darkolivegreen": "#556b2f", + "darkorange": "#ff8c00", + "darkorchid": "#9932cc", + "darkred": "#8b0000", + "darksalmon": "#e9967a", + "darkseagreen": "#8fbc8f", + "darkslateblue": "#483d8b", + "darkslategray": "#2f4f4f", + "darkslategrey": "#2f4f4f", + "darkturquoise": "#00ced1", + "darkviolet": "#9400d3", + "deeppink": "#ff1493", + "deepskyblue": "#00bfff", + "dimgray": "#696969", + "dimgrey": "#696969", + "dodgerblue": "#1e90ff", + "firebrick": "#b22222", + "floralwhite": "#fffaf0", + "forestgreen": "#228b22", + "fuchsia": "#ff00ff", + "gainsboro": "#dcdcdc", + "ghostwhite": "#f8f8ff", + "gold": "#ffd700", + "goldenrod": "#daa520", + "gray": "#808080", + "grey": "#808080", + "green": "#008000", + "greenyellow": "#adff2f", + "honeydew": "#f0fff0", + "hotpink": "#ff69b4", + "indianred": "#cd5c5c", + "indigo": "#4b0082", + "ivory": "#fffff0", + "khaki": "#f0e68c", + "lavender": "#e6e6fa", + "lavenderblush": "#fff0f5", + "lawngreen": "#7cfc00", + "lemonchiffon": "#fffacd", + "lightblue": "#add8e6", + "lightcoral": "#f08080", + "lightcyan": "#e0ffff", + "lightgoldenrodyellow": "#fafad2", + "lightgreen": "#90ee90", + "lightgray": "#d3d3d3", + "lightgrey": "#d3d3d3", + "lightpink": "#ffb6c1", + "lightsalmon": "#ffa07a", + "lightseagreen": "#20b2aa", + "lightskyblue": "#87cefa", + "lightslategray": "#778899", + "lightslategrey": "#778899", + "lightsteelblue": "#b0c4de", + "lightyellow": "#ffffe0", + "lime": "#00ff00", + "limegreen": "#32cd32", + "linen": "#faf0e6", + "magenta": "#ff00ff", + "maroon": "#800000", + "mediumaquamarine": "#66cdaa", + "mediumblue": "#0000cd", + "mediumorchid": "#ba55d3", + "mediumpurple": "#9370db", + "mediumseagreen": "#3cb371", + "mediumslateblue": "#7b68ee", + "mediumspringgreen": "#00fa9a", + "mediumturquoise": "#48d1cc", + "mediumvioletred": "#c71585", + "midnightblue": "#191970", + "mintcream": "#f5fffa", + "mistyrose": "#ffe4e1", + "moccasin": "#ffe4b5", + "navajowhite": "#ffdead", + "navy": "#000080", + "oldlace": "#fdf5e6", + "olive": "#808000", + "olivedrab": "#6b8e23", + "orange": "#ffa500", + "orangered": "#ff4500", + "orchid": "#da70d6", + "palegoldenrod": "#eee8aa", + "palegreen": "#98fb98", + "paleturquoise": "#afeeee", + "palevioletred": "#db7093", + "papayawhip": "#ffefd5", + "peachpuff": "#ffdab9", + "peru": "#cd853f", + "pink": "#ffc0cb", + "plum": "#dda0dd", + "powderblue": "#b0e0e6", + "purple": "#800080", + "rebeccapurple": "#663399", + "red": "#ff0000", + "rosybrown": "#bc8f8f", + "royalblue": "#4169e1", + "saddlebrown": "#8b4513", + "salmon": "#fa8072", + "sandybrown": "#f4a460", + "seagreen": "#2e8b57", + "seashell": "#fff5ee", + "sienna": "#a0522d", + "silver": "#c0c0c0", + "skyblue": "#87ceeb", + "slateblue": "#6a5acd", + "slategray": "#708090", + "slategrey": "#708090", + "snow": "#fffafa", + "springgreen": "#00ff7f", + "steelblue": "#4682b4", + "tan": "#d2b48c", + "teal": "#008080", + "thistle": "#d8bfd8", + "tomato": "#ff6347", + "turquoise": "#40e0d0", + "violet": "#ee82ee", + "wheat": "#f5deb3", + "white": "#ffffff", + "whitesmoke": "#f5f5f5", + "yellow": "#ffff00", + "yellowgreen": "#9acd32", +} diff --git a/.venv/lib/python3.11/site-packages/PIL/ImageDraw.py b/.venv/lib/python3.11/site-packages/PIL/ImageDraw.py new file mode 100644 index 0000000000000000000000000000000000000000..561c44729cfc66e4452d07856f22632680d91e89 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/ImageDraw.py @@ -0,0 +1,1002 @@ +# +# The Python Imaging Library +# $Id$ +# +# drawing interface operations +# +# History: +# 1996-04-13 fl Created (experimental) +# 1996-08-07 fl Filled polygons, ellipses. +# 1996-08-13 fl Added text support +# 1998-06-28 fl Handle I and F images +# 1998-12-29 fl Added arc; use arc primitive to draw ellipses +# 1999-01-10 fl Added shape stuff (experimental) +# 1999-02-06 fl Added bitmap support +# 1999-02-11 fl Changed all primitives to take options +# 1999-02-20 fl Fixed backwards compatibility +# 2000-10-12 fl Copy on write, when necessary +# 2001-02-18 fl Use default ink for bitmap/text also in fill mode +# 2002-10-24 fl Added support for CSS-style color strings +# 2002-12-10 fl Added experimental support for RGBA-on-RGB drawing +# 2002-12-11 fl Refactored low-level drawing API (work in progress) +# 2004-08-26 fl Made Draw() a factory function, added getdraw() support +# 2004-09-04 fl Added width support to line primitive +# 2004-09-10 fl Added font mode handling +# 2006-06-19 fl Added font bearing support (getmask2) +# +# Copyright (c) 1997-2006 by Secret Labs AB +# Copyright (c) 1996-2006 by Fredrik Lundh +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import math +import struct +from collections.abc import Sequence +from typing import cast + +from . import Image, ImageColor, ImageFont, ImageText + +TYPE_CHECKING = False +if TYPE_CHECKING: + from collections.abc import Callable + from types import ModuleType + from typing import Any, AnyStr + + from . import ImageDraw2 + from ._typing import Coords, _Ink + +# experimental access to the outline API +Outline: Callable[[], Image.core._Outline] = Image.core.outline + +""" +A simple 2D drawing interface for PIL images. +

+Application code should use the Draw factory, instead of +directly. +""" + + +class ImageDraw: + font: ImageFont.BaseImageFont | None = None + + def __init__(self, im: Image.Image, mode: str | None = None) -> None: + """ + Create a drawing instance. + + :param im: The image to draw in. + :param mode: Optional mode to use for color values. For RGB + images, this argument can be RGB or RGBA (to blend the + drawing into the image). For all other modes, this argument + must be the same as the image mode. If omitted, the mode + defaults to the mode of the image. + """ + im._ensure_mutable() + blend = 0 + if mode is None: + mode = im.mode + if mode != im.mode: + if mode == "RGBA" and im.mode == "RGB": + blend = 1 + else: + msg = "mode mismatch" + raise ValueError(msg) + if mode == "P": + self.palette = im.palette + else: + self.palette = None + self._image = im + self.im = im.im + self.draw = Image.core.draw(self.im, blend) + self.mode = mode + if mode in ("I", "F"): + self.ink = self.draw.draw_ink(1) + else: + self.ink = self.draw.draw_ink(-1) + if mode in ("1", "P", "I", "F"): + # FIXME: fix Fill2 to properly support matte for I+F images + self.fontmode = "1" + else: + self.fontmode = "L" # aliasing is okay for other modes + self.fill = False + + def getfont( + self, + ) -> ImageFont.BaseImageFont: + """ + Get the current default font. + + To set the default font for this ImageDraw instance:: + + from PIL import ImageDraw, ImageFont + draw.font = ImageFont.truetype("Tests/fonts/FreeMono.ttf") + + To set the default font for all future ImageDraw instances:: + + from PIL import ImageDraw, ImageFont + ImageDraw.ImageDraw.font = ImageFont.truetype("Tests/fonts/FreeMono.ttf") + + If the current default font is ``None``, + it is initialized with ``ImageFont.load_default()``. + + :returns: An image font.""" + if not self.font: + # FIXME: should add a font repository + self.font = ImageFont.load_default() + return self.font + + def _getfont(self, font_size: float | None) -> ImageFont.BaseImageFont: + if font_size is not None: + return ImageFont.load_default(font_size) + else: + return self.getfont() + + def _getink( + self, ink: _Ink | None, fill: _Ink | None = None + ) -> tuple[int | None, int | None]: + result_ink = None + result_fill = None + if ink is None and fill is None: + if self.fill: + result_fill = self.ink + else: + result_ink = self.ink + else: + if ink is not None: + if isinstance(ink, str): + ink = ImageColor.getcolor(ink, self.mode) + if self.palette and isinstance(ink, tuple): + ink = self.palette.getcolor(ink, self._image) + result_ink = self.draw.draw_ink(ink) + if fill is not None: + if isinstance(fill, str): + fill = ImageColor.getcolor(fill, self.mode) + if self.palette and isinstance(fill, tuple): + fill = self.palette.getcolor(fill, self._image) + result_fill = self.draw.draw_ink(fill) + return result_ink, result_fill + + def arc( + self, + xy: Coords, + start: float, + end: float, + fill: _Ink | None = None, + width: int = 1, + ) -> None: + """Draw an arc.""" + ink, fill = self._getink(fill) + if ink is not None and width != 0: + self.draw.draw_arc(xy, start, end, ink, width) + + def bitmap( + self, xy: Sequence[int], bitmap: Image.Image, fill: _Ink | None = None + ) -> None: + """Draw a bitmap.""" + bitmap.load() + ink, fill = self._getink(fill) + if ink is None: + ink = fill + if ink is not None: + self.draw.draw_bitmap(xy, bitmap.im, ink) + + def chord( + self, + xy: Coords, + start: float, + end: float, + fill: _Ink | None = None, + outline: _Ink | None = None, + width: int = 1, + ) -> None: + """Draw a chord.""" + ink, fill_ink = self._getink(outline, fill) + if fill_ink is not None: + self.draw.draw_chord(xy, start, end, fill_ink, 1) + if ink is not None and ink != fill_ink and width != 0: + self.draw.draw_chord(xy, start, end, ink, 0, width) + + def ellipse( + self, + xy: Coords, + fill: _Ink | None = None, + outline: _Ink | None = None, + width: int = 1, + ) -> None: + """Draw an ellipse.""" + ink, fill_ink = self._getink(outline, fill) + if fill_ink is not None: + self.draw.draw_ellipse(xy, fill_ink, 1) + if ink is not None and ink != fill_ink and width != 0: + self.draw.draw_ellipse(xy, ink, 0, width) + + def circle( + self, + xy: Sequence[float], + radius: float, + fill: _Ink | None = None, + outline: _Ink | None = None, + width: int = 1, + ) -> None: + """Draw a circle given center coordinates and a radius.""" + ellipse_xy = (xy[0] - radius, xy[1] - radius, xy[0] + radius, xy[1] + radius) + self.ellipse(ellipse_xy, fill, outline, width) + + def line( + self, + xy: Coords, + fill: _Ink | None = None, + width: int = 1, + joint: str | None = None, + ) -> None: + """Draw a line, or a connected sequence of line segments.""" + ink = self._getink(fill)[0] + if ink is not None and width != 0: + self.draw.draw_lines(xy, ink, width) + if joint == "curve" and width > 4: + points: Sequence[Sequence[float]] + if isinstance(xy[0], (list, tuple)): + points = cast(Sequence[Sequence[float]], xy) + else: + points = [ + cast(Sequence[float], tuple(xy[i : i + 2])) + for i in range(0, len(xy), 2) + ] + for i in range(1, len(points) - 1): + point = points[i] + angles = [ + math.degrees(math.atan2(end[0] - start[0], start[1] - end[1])) + % 360 + for start, end in ( + (points[i - 1], point), + (point, points[i + 1]), + ) + ] + if angles[0] == angles[1]: + # This is a straight line, so no joint is required + continue + + def coord_at_angle( + coord: Sequence[float], angle: float + ) -> tuple[float, ...]: + x, y = coord + angle -= 90 + distance = width / 2 - 1 + return tuple( + p + (math.floor(p_d) if p_d > 0 else math.ceil(p_d)) + for p, p_d in ( + (x, distance * math.cos(math.radians(angle))), + (y, distance * math.sin(math.radians(angle))), + ) + ) + + flipped = ( + angles[1] > angles[0] and angles[1] - 180 > angles[0] + ) or (angles[1] < angles[0] and angles[1] + 180 > angles[0]) + coords = [ + (point[0] - width / 2 + 1, point[1] - width / 2 + 1), + (point[0] + width / 2 - 1, point[1] + width / 2 - 1), + ] + if flipped: + start, end = (angles[1] + 90, angles[0] + 90) + else: + start, end = (angles[0] - 90, angles[1] - 90) + self.pieslice(coords, start - 90, end - 90, fill) + + if width > 8: + # Cover potential gaps between the line and the joint + if flipped: + gap_coords = [ + coord_at_angle(point, angles[0] + 90), + point, + coord_at_angle(point, angles[1] + 90), + ] + else: + gap_coords = [ + coord_at_angle(point, angles[0] - 90), + point, + coord_at_angle(point, angles[1] - 90), + ] + self.line(gap_coords, fill, width=3) + + def shape( + self, + shape: Image.core._Outline, + fill: _Ink | None = None, + outline: _Ink | None = None, + ) -> None: + """(Experimental) Draw a shape.""" + shape.close() + ink, fill_ink = self._getink(outline, fill) + if fill_ink is not None: + self.draw.draw_outline(shape, fill_ink, 1) + if ink is not None and ink != fill_ink: + self.draw.draw_outline(shape, ink, 0) + + def pieslice( + self, + xy: Coords, + start: float, + end: float, + fill: _Ink | None = None, + outline: _Ink | None = None, + width: int = 1, + ) -> None: + """Draw a pieslice.""" + ink, fill_ink = self._getink(outline, fill) + if fill_ink is not None: + self.draw.draw_pieslice(xy, start, end, fill_ink, 1) + if ink is not None and ink != fill_ink and width != 0: + self.draw.draw_pieslice(xy, start, end, ink, 0, width) + + def point(self, xy: Coords, fill: _Ink | None = None) -> None: + """Draw one or more individual pixels.""" + ink, fill = self._getink(fill) + if ink is not None: + self.draw.draw_points(xy, ink) + + def polygon( + self, + xy: Coords, + fill: _Ink | None = None, + outline: _Ink | None = None, + width: int = 1, + ) -> None: + """Draw a polygon.""" + ink, fill_ink = self._getink(outline, fill) + if fill_ink is not None: + self.draw.draw_polygon(xy, fill_ink, 1) + if ink is not None and ink != fill_ink and width != 0: + if width == 1: + self.draw.draw_polygon(xy, ink, 0, width) + elif self.im is not None: + # To avoid expanding the polygon outwards, + # use the fill as a mask + mask = Image.new("1", self.im.size) + mask_ink = self._getink(1)[0] + draw = Draw(mask) + draw.draw.draw_polygon(xy, mask_ink, 1) + + self.draw.draw_polygon(xy, ink, 0, width * 2 - 1, mask.im) + + def regular_polygon( + self, + bounding_circle: Sequence[Sequence[float] | float], + n_sides: int, + rotation: float = 0, + fill: _Ink | None = None, + outline: _Ink | None = None, + width: int = 1, + ) -> None: + """Draw a regular polygon.""" + xy = _compute_regular_polygon_vertices(bounding_circle, n_sides, rotation) + self.polygon(xy, fill, outline, width) + + def rectangle( + self, + xy: Coords, + fill: _Ink | None = None, + outline: _Ink | None = None, + width: int = 1, + ) -> None: + """Draw a rectangle.""" + ink, fill_ink = self._getink(outline, fill) + if fill_ink is not None: + self.draw.draw_rectangle(xy, fill_ink, 1) + if ink is not None and ink != fill_ink and width != 0: + self.draw.draw_rectangle(xy, ink, 0, width) + + def rounded_rectangle( + self, + xy: Coords, + radius: float = 0, + fill: _Ink | None = None, + outline: _Ink | None = None, + width: int = 1, + *, + corners: tuple[bool, bool, bool, bool] | None = None, + ) -> None: + """Draw a rounded rectangle.""" + if isinstance(xy[0], (list, tuple)): + (x0, y0), (x1, y1) = cast(Sequence[Sequence[float]], xy) + else: + x0, y0, x1, y1 = cast(Sequence[float], xy) + if x1 < x0: + msg = "x1 must be greater than or equal to x0" + raise ValueError(msg) + if y1 < y0: + msg = "y1 must be greater than or equal to y0" + raise ValueError(msg) + if corners is None: + corners = (True, True, True, True) + + d = min(x1 - x0, y1 - y0, radius * 2) + + x0 = round(x0) + y0 = round(y0) + x1 = round(x1) + y1 = round(y1) + full_x, full_y = False, False + if all(corners): + full_x = d >= x1 - x0 - 1 + if full_x: + # The two left and two right corners are joined + d = x1 - x0 + full_y = d >= y1 - y0 - 1 + if full_y: + # The two top and two bottom corners are joined + d = y1 - y0 + if full_x and full_y: + # If all corners are joined, that is a circle + return self.ellipse(xy, fill, outline, width) + + if d == 0 or not any(corners): + # If the corners have no curve, + # or there are no corners, + # that is a rectangle + return self.rectangle(xy, fill, outline, width) + + r = int(d // 2) + ink, fill_ink = self._getink(outline, fill) + + def draw_corners(pieslice: bool) -> None: + parts: tuple[tuple[tuple[float, float, float, float], int, int], ...] + if full_x: + # Draw top and bottom halves + parts = ( + ((x0, y0, x0 + d, y0 + d), 180, 360), + ((x0, y1 - d, x0 + d, y1), 0, 180), + ) + elif full_y: + # Draw left and right halves + parts = ( + ((x0, y0, x0 + d, y0 + d), 90, 270), + ((x1 - d, y0, x1, y0 + d), 270, 90), + ) + else: + # Draw four separate corners + parts = tuple( + part + for i, part in enumerate( + ( + ((x0, y0, x0 + d, y0 + d), 180, 270), + ((x1 - d, y0, x1, y0 + d), 270, 360), + ((x1 - d, y1 - d, x1, y1), 0, 90), + ((x0, y1 - d, x0 + d, y1), 90, 180), + ) + ) + if corners[i] + ) + for part in parts: + if pieslice: + self.draw.draw_pieslice(*(part + (fill_ink, 1))) + else: + self.draw.draw_arc(*(part + (ink, width))) + + if fill_ink is not None: + draw_corners(True) + + if full_x: + self.draw.draw_rectangle((x0, y0 + r + 1, x1, y1 - r - 1), fill_ink, 1) + elif x1 - r - 1 >= x0 + r + 1: + self.draw.draw_rectangle((x0 + r + 1, y0, x1 - r - 1, y1), fill_ink, 1) + if not full_x and not full_y: + left = [x0, y0, x0 + r, y1] + if corners[0]: + left[1] += r + 1 + if corners[3]: + left[3] -= r + 1 + self.draw.draw_rectangle(left, fill_ink, 1) + + right = [x1 - r, y0, x1, y1] + if corners[1]: + right[1] += r + 1 + if corners[2]: + right[3] -= r + 1 + self.draw.draw_rectangle(right, fill_ink, 1) + if ink is not None and ink != fill_ink and width != 0: + draw_corners(False) + + if not full_x: + top = [x0, y0, x1, y0 + width - 1] + if corners[0]: + top[0] += r + 1 + if corners[1]: + top[2] -= r + 1 + self.draw.draw_rectangle(top, ink, 1) + + bottom = [x0, y1 - width + 1, x1, y1] + if corners[3]: + bottom[0] += r + 1 + if corners[2]: + bottom[2] -= r + 1 + self.draw.draw_rectangle(bottom, ink, 1) + if not full_y: + left = [x0, y0, x0 + width - 1, y1] + if corners[0]: + left[1] += r + 1 + if corners[3]: + left[3] -= r + 1 + self.draw.draw_rectangle(left, ink, 1) + + right = [x1 - width + 1, y0, x1, y1] + if corners[1]: + right[1] += r + 1 + if corners[2]: + right[3] -= r + 1 + self.draw.draw_rectangle(right, ink, 1) + + def text( + self, + xy: tuple[float, float], + text: AnyStr | ImageText.Text[AnyStr], + fill: _Ink | None = None, + font: ImageFont.BaseImageFont | None = None, + anchor: str | None = None, + spacing: float = 4, + align: str = "left", + direction: str | None = None, + features: list[str] | None = None, + language: str | None = None, + stroke_width: float = 0, + stroke_fill: _Ink | None = None, + embedded_color: bool = False, + *args: Any, + **kwargs: Any, + ) -> None: + """Draw text.""" + if isinstance(text, ImageText.Text): + image_text = text + else: + if font is None: + font = self._getfont(kwargs.get("font_size")) + image_text = ImageText.Text( + text, font, self.mode, spacing, direction, features, language + ) + if embedded_color: + image_text.embed_color() + if stroke_width: + image_text.stroke(stroke_width, stroke_fill) + + def getink(fill: _Ink | None) -> int: + ink, fill_ink = self._getink(fill) + if ink is None: + assert fill_ink is not None + return fill_ink + return ink + + ink = getink(fill) + if ink is None: + return + + stroke_ink = None + if image_text.stroke_width: + stroke_ink = ( + getink(image_text.stroke_fill) + if image_text.stroke_fill is not None + else ink + ) + + for line in image_text._split(xy, anchor, align): + + def draw_text(ink: int, stroke_width: float = 0) -> None: + mode = self.fontmode + if stroke_width == 0 and embedded_color: + mode = "RGBA" + x = int(line.x) + y = int(line.y) + start = (math.modf(line.x)[0], math.modf(line.y)[0]) + if isinstance(image_text.font, ImageFont.FreeTypeFont): + mask, offset = image_text.font.getmask2( + line.text, + mode, + direction, + features, + language, + stroke_width, + line.anchor, + ink, + start, + stroke_filled=True, + *args, + **kwargs, + ) + x += offset[0] + y += offset[1] + else: + try: + mask = image_text.font.getmask( + line.text, + mode, + direction, + features, + language, + stroke_width, + line.anchor, + ink, + start=start, + *args, + **kwargs, + ) + except TypeError: + mask = image_text.font.getmask(line.text) + if mode == "RGBA": + # image_text.font.getmask2(mode="RGBA") + # returns color in RGB bands and mask in A + # extract mask and set text alpha + color, mask = mask, mask.getband(3) + ink_alpha = struct.pack("i", ink)[3] + color.fillband(3, ink_alpha) + if self.im is not None: + self.im.paste( + color, (x, y, x + mask.size[0], y + mask.size[1]), mask + ) + else: + self.draw.draw_bitmap((x, y), mask, ink) + + if stroke_ink is not None: + # Draw stroked text + draw_text(stroke_ink, image_text.stroke_width) + + # Draw normal text + if ink != stroke_ink: + draw_text(ink) + else: + # Only draw normal text + draw_text(ink) + + def multiline_text( + self, + xy: tuple[float, float], + text: AnyStr, + fill: _Ink | None = None, + font: ImageFont.BaseImageFont | None = None, + anchor: str | None = None, + spacing: float = 4, + align: str = "left", + direction: str | None = None, + features: list[str] | None = None, + language: str | None = None, + stroke_width: float = 0, + stroke_fill: _Ink | None = None, + embedded_color: bool = False, + *, + font_size: float | None = None, + ) -> None: + return self.text( + xy, + text, + fill, + font, + anchor, + spacing, + align, + direction, + features, + language, + stroke_width, + stroke_fill, + embedded_color, + font_size=font_size, + ) + + def textlength( + self, + text: AnyStr, + font: ImageFont.BaseImageFont | None = None, + direction: str | None = None, + features: list[str] | None = None, + language: str | None = None, + embedded_color: bool = False, + *, + font_size: float | None = None, + ) -> float: + """Get the length of a given string, in pixels with 1/64 precision.""" + if font is None: + font = self._getfont(font_size) + image_text = ImageText.Text( + text, + font, + self.mode, + direction=direction, + features=features, + language=language, + ) + if embedded_color: + image_text.embed_color() + return image_text.get_length() + + def textbbox( + self, + xy: tuple[float, float], + text: AnyStr, + font: ImageFont.BaseImageFont | None = None, + anchor: str | None = None, + spacing: float = 4, + align: str = "left", + direction: str | None = None, + features: list[str] | None = None, + language: str | None = None, + stroke_width: float = 0, + embedded_color: bool = False, + *, + font_size: float | None = None, + ) -> tuple[float, float, float, float]: + """Get the bounding box of a given string, in pixels.""" + if font is None: + font = self._getfont(font_size) + image_text = ImageText.Text( + text, font, self.mode, spacing, direction, features, language + ) + if embedded_color: + image_text.embed_color() + if stroke_width: + image_text.stroke(stroke_width) + return image_text.get_bbox(xy, anchor, align) + + def multiline_textbbox( + self, + xy: tuple[float, float], + text: AnyStr, + font: ImageFont.BaseImageFont | None = None, + anchor: str | None = None, + spacing: float = 4, + align: str = "left", + direction: str | None = None, + features: list[str] | None = None, + language: str | None = None, + stroke_width: float = 0, + embedded_color: bool = False, + *, + font_size: float | None = None, + ) -> tuple[float, float, float, float]: + return self.textbbox( + xy, + text, + font, + anchor, + spacing, + align, + direction, + features, + language, + stroke_width, + embedded_color, + font_size=font_size, + ) + + +def Draw(im: Image.Image, mode: str | None = None) -> ImageDraw: + """ + A simple 2D drawing interface for PIL images. + + :param im: The image to draw in. + :param mode: Optional mode to use for color values. For RGB + images, this argument can be RGB or RGBA (to blend the + drawing into the image). For all other modes, this argument + must be the same as the image mode. If omitted, the mode + defaults to the mode of the image. + """ + try: + return getattr(im, "getdraw")(mode) + except AttributeError: + return ImageDraw(im, mode) + + +def getdraw(im: Image.Image | None = None) -> tuple[ImageDraw2.Draw | None, ModuleType]: + """ + :param im: The image to draw in. + :returns: A (drawing context, drawing resource factory) tuple. + """ + from . import ImageDraw2 + + draw = ImageDraw2.Draw(im) if im is not None else None + return draw, ImageDraw2 + + +def floodfill( + image: Image.Image, + xy: tuple[int, int], + value: float | tuple[int, ...], + border: float | tuple[int, ...] | None = None, + thresh: float = 0, +) -> None: + """ + .. warning:: This method is experimental. + + Fills a bounded region with a given color. + + :param image: Target image. + :param xy: Seed position (a 2-item coordinate tuple). See + :ref:`coordinate-system`. + :param value: Fill color. + :param border: Optional border value. If given, the region consists of + pixels with a color different from the border color. If not given, + the region consists of pixels having the same color as the seed + pixel. + :param thresh: Optional threshold value which specifies a maximum + tolerable difference of a pixel value from the 'background' in + order for it to be replaced. Useful for filling regions of + non-homogeneous, but similar, colors. + """ + # based on an implementation by Eric S. Raymond + # amended by yo1995 @20180806 + pixel = image.load() + assert pixel is not None + x, y = xy + try: + background = pixel[x, y] + if _color_diff(value, background) <= thresh: + return # seed point already has fill color + pixel[x, y] = value + except (ValueError, IndexError): + return # seed point outside image + edge = {(x, y)} + # use a set to keep record of current and previous edge pixels + # to reduce memory consumption + full_edge = set() + while edge: + new_edge = set() + for x, y in edge: # 4 adjacent method + for s, t in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)): + # If already processed, or if a coordinate is negative, skip + if (s, t) in full_edge or s < 0 or t < 0: + continue + try: + p = pixel[s, t] + except (ValueError, IndexError): + pass + else: + full_edge.add((s, t)) + if border is None: + fill = _color_diff(p, background) <= thresh + else: + fill = p not in (value, border) + if fill: + pixel[s, t] = value + new_edge.add((s, t)) + full_edge = edge # discard pixels processed + edge = new_edge + + +def _compute_regular_polygon_vertices( + bounding_circle: Sequence[Sequence[float] | float], n_sides: int, rotation: float +) -> list[tuple[float, float]]: + """ + Generate a list of vertices for a 2D regular polygon. + + :param bounding_circle: The bounding circle is a sequence defined + by a point and radius. The polygon is inscribed in this circle. + (e.g. ``bounding_circle=(x, y, r)`` or ``((x, y), r)``) + :param n_sides: Number of sides + (e.g. ``n_sides=3`` for a triangle, ``6`` for a hexagon) + :param rotation: Apply an arbitrary rotation to the polygon + (e.g. ``rotation=90``, applies a 90 degree rotation) + :return: List of regular polygon vertices + (e.g. ``[(25, 50), (50, 50), (50, 25), (25, 25)]``) + + How are the vertices computed? + 1. Compute the following variables + - theta: Angle between the apothem & the nearest polygon vertex + - side_length: Length of each polygon edge + - centroid: Center of bounding circle (1st, 2nd elements of bounding_circle) + - polygon_radius: Polygon radius (last element of bounding_circle) + - angles: Location of each polygon vertex in polar grid + (e.g. A square with 0 degree rotation => [225.0, 315.0, 45.0, 135.0]) + + 2. For each angle in angles, get the polygon vertex at that angle + The vertex is computed using the equation below. + X= xcos(φ) + ysin(φ) + Y= −xsin(φ) + ycos(φ) + + Note: + φ = angle in degrees + x = 0 + y = polygon_radius + + The formula above assumes rotation around the origin. + In our case, we are rotating around the centroid. + To account for this, we use the formula below + X = xcos(φ) + ysin(φ) + centroid_x + Y = −xsin(φ) + ycos(φ) + centroid_y + """ + # 1. Error Handling + # 1.1 Check `n_sides` has an appropriate value + if not isinstance(n_sides, int): + msg = "n_sides should be an int" # type: ignore[unreachable] + raise TypeError(msg) + if n_sides < 3: + msg = "n_sides should be an int > 2" + raise ValueError(msg) + + # 1.2 Check `bounding_circle` has an appropriate value + if not isinstance(bounding_circle, (list, tuple)): + msg = "bounding_circle should be a sequence" + raise TypeError(msg) + + if len(bounding_circle) == 3: + if not all(isinstance(i, (int, float)) for i in bounding_circle): + msg = "bounding_circle should only contain numeric data" + raise ValueError(msg) + + *centroid, polygon_radius = cast(list[float], list(bounding_circle)) + elif len(bounding_circle) == 2 and isinstance(bounding_circle[0], (list, tuple)): + if not all( + isinstance(i, (int, float)) for i in bounding_circle[0] + ) or not isinstance(bounding_circle[1], (int, float)): + msg = "bounding_circle should only contain numeric data" + raise ValueError(msg) + + if len(bounding_circle[0]) != 2: + msg = "bounding_circle centre should contain 2D coordinates (e.g. (x, y))" + raise ValueError(msg) + + centroid = cast(list[float], list(bounding_circle[0])) + polygon_radius = cast(float, bounding_circle[1]) + else: + msg = ( + "bounding_circle should contain 2D coordinates " + "and a radius (e.g. (x, y, r) or ((x, y), r) )" + ) + raise ValueError(msg) + + if polygon_radius <= 0: + msg = "bounding_circle radius should be > 0" + raise ValueError(msg) + + # 1.3 Check `rotation` has an appropriate value + if not isinstance(rotation, (int, float)): + msg = "rotation should be an int or float" # type: ignore[unreachable] + raise ValueError(msg) + + # 2. Define Helper Functions + def _apply_rotation(point: list[float], degrees: float) -> tuple[float, float]: + return ( + round( + point[0] * math.cos(math.radians(360 - degrees)) + - point[1] * math.sin(math.radians(360 - degrees)) + + centroid[0], + 2, + ), + round( + point[1] * math.cos(math.radians(360 - degrees)) + + point[0] * math.sin(math.radians(360 - degrees)) + + centroid[1], + 2, + ), + ) + + def _compute_polygon_vertex(angle: float) -> tuple[float, float]: + start_point = [polygon_radius, 0] + return _apply_rotation(start_point, angle) + + def _get_angles(n_sides: int, rotation: float) -> list[float]: + angles = [] + degrees = 360 / n_sides + # Start with the bottom left polygon vertex + current_angle = (270 - 0.5 * degrees) + rotation + for _ in range(n_sides): + angles.append(current_angle) + current_angle += degrees + if current_angle > 360: + current_angle -= 360 + return angles + + # 3. Variable Declarations + angles = _get_angles(n_sides, rotation) + + # 4. Compute Vertices + return [_compute_polygon_vertex(angle) for angle in angles] + + +def _color_diff( + color1: float | tuple[int, ...], color2: float | tuple[int, ...] +) -> float: + """ + Uses 1-norm distance to calculate difference between two values. + """ + first = color1 if isinstance(color1, tuple) else (color1,) + second = color2 if isinstance(color2, tuple) else (color2,) + + return sum(abs(first[i] - second[i]) for i in range(len(second))) diff --git a/.venv/lib/python3.11/site-packages/PIL/ImageDraw2.py b/.venv/lib/python3.11/site-packages/PIL/ImageDraw2.py new file mode 100644 index 0000000000000000000000000000000000000000..2c9e39b2c41d1ad745d208413a640c9cf8b781ec --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/ImageDraw2.py @@ -0,0 +1,244 @@ +# +# The Python Imaging Library +# $Id$ +# +# WCK-style drawing interface operations +# +# History: +# 2003-12-07 fl created +# 2005-05-15 fl updated; added to PIL as ImageDraw2 +# 2005-05-15 fl added text support +# 2005-05-20 fl added arc/chord/pieslice support +# +# Copyright (c) 2003-2005 by Secret Labs AB +# Copyright (c) 2003-2005 by Fredrik Lundh +# +# See the README file for information on usage and redistribution. +# + + +""" +(Experimental) WCK-style drawing interface operations + +.. seealso:: :py:mod:`PIL.ImageDraw` +""" + +from __future__ import annotations + +from typing import Any, AnyStr, BinaryIO + +from . import Image, ImageColor, ImageDraw, ImageFont, ImagePath +from ._typing import Coords, StrOrBytesPath + + +class Pen: + """Stores an outline color and width.""" + + def __init__(self, color: str, width: int = 1, opacity: int = 255) -> None: + self.color = ImageColor.getrgb(color) + self.width = width + + +class Brush: + """Stores a fill color""" + + def __init__(self, color: str, opacity: int = 255) -> None: + self.color = ImageColor.getrgb(color) + + +class Font: + """Stores a TrueType font and color""" + + def __init__( + self, color: str, file: StrOrBytesPath | BinaryIO, size: float = 12 + ) -> None: + # FIXME: add support for bitmap fonts + self.color = ImageColor.getrgb(color) + self.font = ImageFont.truetype(file, size) + + +class Draw: + """ + (Experimental) WCK-style drawing interface + """ + + def __init__( + self, + image: Image.Image | str, + size: tuple[int, int] | list[int] | None = None, + color: float | tuple[float, ...] | str | None = None, + ) -> None: + if isinstance(image, str): + if size is None: + msg = "If image argument is mode string, size must be a list or tuple" + raise ValueError(msg) + image = Image.new(image, size, color) + self.draw = ImageDraw.Draw(image) + self.image = image + self.transform: tuple[float, float, float, float, float, float] | None = None + + def flush(self) -> Image.Image: + return self.image + + def render( + self, + op: str, + xy: Coords, + pen: Pen | Brush | None, + brush: Brush | Pen | None = None, + **kwargs: Any, + ) -> None: + # handle color arguments + outline = fill = None + width = 1 + if isinstance(pen, Pen): + outline = pen.color + width = pen.width + elif isinstance(brush, Pen): + outline = brush.color + width = brush.width + if isinstance(brush, Brush): + fill = brush.color + elif isinstance(pen, Brush): + fill = pen.color + # handle transformation + if self.transform: + path = ImagePath.Path(xy) + path.transform(self.transform) + xy = path + # render the item + if op in ("arc", "line"): + kwargs.setdefault("fill", outline) + else: + kwargs.setdefault("fill", fill) + kwargs.setdefault("outline", outline) + if op == "line": + kwargs.setdefault("width", width) + getattr(self.draw, op)(xy, **kwargs) + + def settransform(self, offset: tuple[float, float]) -> None: + """Sets a transformation offset.""" + xoffset, yoffset = offset + self.transform = (1, 0, xoffset, 0, 1, yoffset) + + def arc( + self, + xy: Coords, + pen: Pen | Brush | None, + start: float, + end: float, + *options: Any, + ) -> None: + """ + Draws an arc (a portion of a circle outline) between the start and end + angles, inside the given bounding box. + + .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.arc` + """ + self.render("arc", xy, pen, *options, start=start, end=end) + + def chord( + self, + xy: Coords, + pen: Pen | Brush | None, + start: float, + end: float, + *options: Any, + ) -> None: + """ + Same as :py:meth:`~PIL.ImageDraw2.Draw.arc`, but connects the end points + with a straight line. + + .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.chord` + """ + self.render("chord", xy, pen, *options, start=start, end=end) + + def ellipse(self, xy: Coords, pen: Pen | Brush | None, *options: Any) -> None: + """ + Draws an ellipse inside the given bounding box. + + .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.ellipse` + """ + self.render("ellipse", xy, pen, *options) + + def line(self, xy: Coords, pen: Pen | Brush | None, *options: Any) -> None: + """ + Draws a line between the coordinates in the ``xy`` list. + + .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.line` + """ + self.render("line", xy, pen, *options) + + def pieslice( + self, + xy: Coords, + pen: Pen | Brush | None, + start: float, + end: float, + *options: Any, + ) -> None: + """ + Same as arc, but also draws straight lines between the end points and the + center of the bounding box. + + .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.pieslice` + """ + self.render("pieslice", xy, pen, *options, start=start, end=end) + + def polygon(self, xy: Coords, pen: Pen | Brush | None, *options: Any) -> None: + """ + Draws a polygon. + + The polygon outline consists of straight lines between the given + coordinates, plus a straight line between the last and the first + coordinate. + + + .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.polygon` + """ + self.render("polygon", xy, pen, *options) + + def rectangle(self, xy: Coords, pen: Pen | Brush | None, *options: Any) -> None: + """ + Draws a rectangle. + + .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.rectangle` + """ + self.render("rectangle", xy, pen, *options) + + def text(self, xy: tuple[float, float], text: AnyStr, font: Font) -> None: + """ + Draws the string at the given position. + + .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.text` + """ + if self.transform: + path = ImagePath.Path(xy) + path.transform(self.transform) + xy = path + self.draw.text(xy, text, font=font.font, fill=font.color) + + def textbbox( + self, xy: tuple[float, float], text: AnyStr, font: Font + ) -> tuple[float, float, float, float]: + """ + Returns bounding box (in pixels) of given text. + + :return: ``(left, top, right, bottom)`` bounding box + + .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.textbbox` + """ + if self.transform: + path = ImagePath.Path(xy) + path.transform(self.transform) + xy = path + return self.draw.textbbox(xy, text, font=font.font) + + def textlength(self, text: AnyStr, font: Font) -> float: + """ + Returns length (in pixels) of given text. + This is the amount by which following text should be offset. + + .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.textlength` + """ + return self.draw.textlength(text, font=font.font) diff --git a/.venv/lib/python3.11/site-packages/PIL/ImageEnhance.py b/.venv/lib/python3.11/site-packages/PIL/ImageEnhance.py new file mode 100644 index 0000000000000000000000000000000000000000..0e7e6dd8ae631ad3577bda1d3e823bd2a3227536 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/ImageEnhance.py @@ -0,0 +1,113 @@ +# +# The Python Imaging Library. +# $Id$ +# +# image enhancement classes +# +# For a background, see "Image Processing By Interpolation and +# Extrapolation", Paul Haeberli and Douglas Voorhies. Available +# at http://www.graficaobscura.com/interp/index.html +# +# History: +# 1996-03-23 fl Created +# 2009-06-16 fl Fixed mean calculation +# +# Copyright (c) Secret Labs AB 1997. +# Copyright (c) Fredrik Lundh 1996. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +from . import Image, ImageFilter, ImageStat + + +class _Enhance: + image: Image.Image + degenerate: Image.Image + + def enhance(self, factor: float) -> Image.Image: + """ + Returns an enhanced image. + + :param factor: A floating point value controlling the enhancement. + Factor 1.0 always returns a copy of the original image, + lower factors mean less color (brightness, contrast, + etc), and higher values more. There are no restrictions + on this value. + :rtype: :py:class:`~PIL.Image.Image` + """ + return Image.blend(self.degenerate, self.image, factor) + + +class Color(_Enhance): + """Adjust image color balance. + + This class can be used to adjust the colour balance of an image, in + a manner similar to the controls on a colour TV set. An enhancement + factor of 0.0 gives a black and white image. A factor of 1.0 gives + the original image. + """ + + def __init__(self, image: Image.Image) -> None: + self.image = image + self.intermediate_mode = "L" + if "A" in image.getbands(): + self.intermediate_mode = "LA" + + if self.intermediate_mode != image.mode: + image = image.convert(self.intermediate_mode).convert(image.mode) + self.degenerate = image + + +class Contrast(_Enhance): + """Adjust image contrast. + + This class can be used to control the contrast of an image, similar + to the contrast control on a TV set. An enhancement factor of 0.0 + gives a solid gray image. A factor of 1.0 gives the original image. + """ + + def __init__(self, image: Image.Image) -> None: + self.image = image + if image.mode != "L": + image = image.convert("L") + mean = int(ImageStat.Stat(image).mean[0] + 0.5) + self.degenerate = Image.new("L", image.size, mean) + if self.degenerate.mode != self.image.mode: + self.degenerate = self.degenerate.convert(self.image.mode) + + if "A" in self.image.getbands(): + self.degenerate.putalpha(self.image.getchannel("A")) + + +class Brightness(_Enhance): + """Adjust image brightness. + + This class can be used to control the brightness of an image. An + enhancement factor of 0.0 gives a black image. A factor of 1.0 gives the + original image. + """ + + def __init__(self, image: Image.Image) -> None: + self.image = image + self.degenerate = Image.new(image.mode, image.size, 0) + + if "A" in image.getbands(): + self.degenerate.putalpha(image.getchannel("A")) + + +class Sharpness(_Enhance): + """Adjust image sharpness. + + This class can be used to adjust the sharpness of an image. An + enhancement factor of 0.0 gives a blurred image, a factor of 1.0 gives the + original image, and a factor of 2.0 gives a sharpened image. + """ + + def __init__(self, image: Image.Image) -> None: + self.image = image + self.degenerate = image.filter(ImageFilter.SMOOTH) + + if "A" in image.getbands(): + self.degenerate.putalpha(image.getchannel("A")) diff --git a/.venv/lib/python3.11/site-packages/PIL/ImageFile.py b/.venv/lib/python3.11/site-packages/PIL/ImageFile.py new file mode 100644 index 0000000000000000000000000000000000000000..2d69225b5c086cf1c98d75ab37a400bd1a2250e7 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/ImageFile.py @@ -0,0 +1,938 @@ +# +# The Python Imaging Library. +# $Id$ +# +# base class for image file handlers +# +# history: +# 1995-09-09 fl Created +# 1996-03-11 fl Fixed load mechanism. +# 1996-04-15 fl Added pcx/xbm decoders. +# 1996-04-30 fl Added encoders. +# 1996-12-14 fl Added load helpers +# 1997-01-11 fl Use encode_to_file where possible +# 1997-08-27 fl Flush output in _save +# 1998-03-05 fl Use memory mapping for some modes +# 1999-02-04 fl Use memory mapping also for "I;16" and "I;16B" +# 1999-05-31 fl Added image parser +# 2000-10-12 fl Set readonly flag on memory-mapped images +# 2002-03-20 fl Use better messages for common decoder errors +# 2003-04-21 fl Fall back on mmap/map_buffer if map is not available +# 2003-10-30 fl Added StubImageFile class +# 2004-02-25 fl Made incremental parser more robust +# +# Copyright (c) 1997-2004 by Secret Labs AB +# Copyright (c) 1995-2004 by Fredrik Lundh +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import abc +import io +import itertools +import logging +import os +import struct +from typing import IO, Any, NamedTuple, cast + +from . import ExifTags, Image +from ._util import DeferredError, is_path + +TYPE_CHECKING = False +if TYPE_CHECKING: + from ._typing import StrOrBytesPath + +logger = logging.getLogger(__name__) + +MAXBLOCK = 65536 +""" +By default, Pillow processes image data in blocks. This helps to prevent excessive use +of resources. Codecs may disable this behaviour with ``_pulls_fd`` or ``_pushes_fd``. + +When reading an image, this is the number of bytes to read at once. + +When writing an image, this is the number of bytes to write at once. +If the image width times 4 is greater, then that will be used instead. +Plugins may also set a greater number. + +User code may set this to another number. +""" + +SAFEBLOCK = 1024 * 1024 + +LOAD_TRUNCATED_IMAGES = False +"""Whether or not to load truncated image files. User code may change this.""" + +ERRORS = { + -1: "image buffer overrun error", + -2: "decoding error", + -3: "unknown error", + -8: "bad configuration", + -9: "out of memory error", +} +""" +Dict of known error codes returned from :meth:`.PyDecoder.decode`, +:meth:`.PyEncoder.encode` :meth:`.PyEncoder.encode_to_pyfd` and +:meth:`.PyEncoder.encode_to_file`. +""" + + +# +# -------------------------------------------------------------------- +# Helpers + + +def _get_oserror(error: int, *, encoder: bool) -> OSError: + try: + msg = Image.core.getcodecstatus(error) + except AttributeError: + msg = ERRORS.get(error) + if not msg: + msg = f"{'encoder' if encoder else 'decoder'} error {error}" + msg += f" when {'writing' if encoder else 'reading'} image file" + return OSError(msg) + + +def _tilesort(t: _Tile) -> int: + # sort on offset + return t[2] + + +class _Tile(NamedTuple): + codec_name: str + extents: tuple[int, int, int, int] | None + offset: int = 0 + args: tuple[Any, ...] | str | None = None + + +# +# -------------------------------------------------------------------- +# ImageFile base class + + +class ImageFile(Image.Image): + """Base class for image file format handlers.""" + + def __init__( + self, fp: StrOrBytesPath | IO[bytes], filename: str | bytes | None = None + ) -> None: + super().__init__() + + self._min_frame = 0 + + self.custom_mimetype: str | None = None + + self.tile: list[_Tile] = [] + """ A list of tile descriptors """ + + self.readonly = 1 # until we know better + + self.decoderconfig: tuple[Any, ...] = () + self.decodermaxblock = MAXBLOCK + + self.fp: IO[bytes] | None + self._fp: IO[bytes] | DeferredError + if is_path(fp): + # filename + self.fp = open(fp, "rb") + self.filename = os.fspath(fp) + self._exclusive_fp = True + else: + # stream + self.fp = cast(IO[bytes], fp) + self.filename = filename if filename is not None else "" + # can be overridden + self._exclusive_fp = False + + try: + try: + self._open() + + if isinstance(self, StubImageFile): + if loader := self._load(): + loader.open(self) + except ( + IndexError, # end of data + TypeError, # end of data (ord) + KeyError, # unsupported mode + EOFError, # got header but not the first frame + struct.error, + ) as v: + raise SyntaxError(v) from v + + if not self.mode or self.size[0] <= 0 or self.size[1] <= 0: + msg = "not identified by this driver" + raise SyntaxError(msg) + except BaseException: + # close the file only if we have opened it this constructor + if self._exclusive_fp: + self.fp.close() + raise + + def _open(self) -> None: + pass + + # Context manager support + def __enter__(self) -> ImageFile: + return self + + def _close_fp(self) -> None: + if getattr(self, "_fp", False) and not isinstance(self._fp, DeferredError): + if self._fp != self.fp: + self._fp.close() + self._fp = DeferredError(ValueError("Operation on closed image")) + if self.fp: + self.fp.close() + + def __exit__(self, *args: object) -> None: + if getattr(self, "_exclusive_fp", False): + self._close_fp() + self.fp = None + + def close(self) -> None: + """ + Closes the file pointer, if possible. + + This operation will destroy the image core and release its memory. + The image data will be unusable afterward. + + This function is required to close images that have multiple frames or + have not had their file read and closed by the + :py:meth:`~PIL.Image.Image.load` method. See :ref:`file-handling` for + more information. + """ + try: + self._close_fp() + self.fp = None + except Exception as msg: + logger.debug("Error closing: %s", msg) + + super().close() + + def get_child_images(self) -> list[ImageFile]: + child_images = [] + exif = self.getexif() + ifds = [] + if ExifTags.Base.SubIFDs in exif: + subifd_offsets = exif[ExifTags.Base.SubIFDs] + if subifd_offsets: + if not isinstance(subifd_offsets, tuple): + subifd_offsets = (subifd_offsets,) + ifds = [ + (exif._get_ifd_dict(subifd_offset), subifd_offset) + for subifd_offset in subifd_offsets + ] + ifd1 = exif.get_ifd(ExifTags.IFD.IFD1) + if ifd1 and ifd1.get(ExifTags.Base.JpegIFOffset): + assert exif._info is not None + ifds.append((ifd1, exif._info.next)) + + offset = None + for ifd, ifd_offset in ifds: + assert self.fp is not None + current_offset = self.fp.tell() + if offset is None: + offset = current_offset + + fp = self.fp + if ifd is not None: + thumbnail_offset = ifd.get(ExifTags.Base.JpegIFOffset) + if thumbnail_offset is not None: + thumbnail_offset += getattr(self, "_exif_offset", 0) + self.fp.seek(thumbnail_offset) + + length = ifd.get(ExifTags.Base.JpegIFByteCount) + assert isinstance(length, int) + data = self.fp.read(length) + fp = io.BytesIO(data) + + with Image.open(fp) as im: + from . import TiffImagePlugin + + if thumbnail_offset is None and isinstance( + im, TiffImagePlugin.TiffImageFile + ): + im._frame_pos = [ifd_offset] + im._seek(0) + im.load() + child_images.append(im) + + if offset is not None: + assert self.fp is not None + self.fp.seek(offset) + return child_images + + def get_format_mimetype(self) -> str | None: + if self.custom_mimetype: + return self.custom_mimetype + if self.format is not None: + return Image.MIME.get(self.format.upper()) + return None + + def __getstate__(self) -> list[Any]: + return super().__getstate__() + [self.filename] + + def __setstate__(self, state: list[Any]) -> None: + self.tile = [] + if len(state) > 5: + self.filename = state[5] + super().__setstate__(state) + + def verify(self) -> None: + """Check file integrity""" + + # raise exception if something's wrong. must be called + # directly after open, and closes file when finished. + if self._exclusive_fp and self.fp: + self.fp.close() + self.fp = None + + def load(self) -> Image.core.PixelAccess | None: + """Load image data based on tile list""" + + if not self.tile and self._im is None: + msg = "cannot load this image" + raise OSError(msg) + + pixel = Image.Image.load(self) + if not self.tile: + return pixel + + self.map: mmap.mmap | None = None + use_mmap = self.filename and len(self.tile) == 1 + + assert self.fp is not None + readonly = 0 + + # look for read/seek overrides + if hasattr(self, "load_read"): + read = self.load_read + # don't use mmap if there are custom read/seek functions + use_mmap = False + else: + read = self.fp.read + + if hasattr(self, "load_seek"): + seek = self.load_seek + use_mmap = False + else: + seek = self.fp.seek + + if use_mmap: + # try memory mapping + decoder_name, extents, offset, args = self.tile[0] + if isinstance(args, str): + args = (args, 0, 1) + if ( + decoder_name == "raw" + and isinstance(args, tuple) + and len(args) >= 3 + and args[0] == self.mode + and args[0] in Image._MAPMODES + ): + if offset < 0: + msg = "Tile offset cannot be negative" + raise ValueError(msg) + try: + # use mmap, if possible + import mmap + + with open(self.filename) as fp: + self.map = mmap.mmap(fp.fileno(), 0, access=mmap.ACCESS_READ) + if offset + self.size[1] * args[1] > self.map.size(): + msg = "buffer is not large enough" + raise OSError(msg) + self.im = Image.core.map_buffer( + self.map, self.size, decoder_name, offset, args + ) + readonly = 1 + # After trashing self.im, + # we might need to reload the palette data. + if self.palette: + self.palette.dirty = 1 + except (AttributeError, OSError, ImportError): + self.map = None + + self.load_prepare() + err_code = -3 # initialize to unknown error + if not self.map: + # sort tiles in file order + self.tile.sort(key=_tilesort) + + # FIXME: This is a hack to handle TIFF's JpegTables tag. + prefix = getattr(self, "tile_prefix", b"") + + # Remove consecutive duplicates that only differ by their offset + self.tile = [ + list(tiles)[-1] + for _, tiles in itertools.groupby( + self.tile, lambda tile: (tile[0], tile[1], tile[3]) + ) + ] + for i, (decoder_name, extents, offset, args) in enumerate(self.tile): + seek(offset) + decoder = Image._getdecoder( + self.mode, decoder_name, args, self.decoderconfig + ) + try: + decoder.setimage(self.im, extents) + if decoder.pulls_fd: + decoder.setfd(self.fp) + err_code = decoder.decode(b"")[1] + else: + b = prefix + while True: + read_bytes = self.decodermaxblock + if i + 1 < len(self.tile): + next_offset = self.tile[i + 1].offset + if next_offset > offset: + read_bytes = next_offset - offset + try: + s = read(read_bytes) + except (IndexError, struct.error) as e: + # truncated png/gif + if LOAD_TRUNCATED_IMAGES: + break + else: + msg = "image file is truncated" + raise OSError(msg) from e + + if not s: # truncated jpeg + if LOAD_TRUNCATED_IMAGES: + break + else: + msg = ( + "image file is truncated " + f"({len(b)} bytes not processed)" + ) + raise OSError(msg) + + b = b + s + n, err_code = decoder.decode(b) + if n < 0: + break + b = b[n:] + finally: + # Need to cleanup here to prevent leaks + decoder.cleanup() + + self.tile = [] + self.readonly = readonly + + self.load_end() + + if self._exclusive_fp and self._close_exclusive_fp_after_loading: + self.fp.close() + self.fp = None + + if not self.map and not LOAD_TRUNCATED_IMAGES and err_code < 0: + # still raised if decoder fails to return anything + raise _get_oserror(err_code, encoder=False) + + return Image.Image.load(self) + + def load_prepare(self) -> None: + # create image memory if necessary + if self._im is None: + self.im = Image.core.new(self.mode, self.size) + # create palette (optional) + if self.mode == "P": + Image.Image.load(self) + + def load_end(self) -> None: + # may be overridden + pass + + # may be defined for contained formats + # def load_seek(self, pos: int) -> None: + # pass + + # may be defined for blocked formats (e.g. PNG) + # def load_read(self, read_bytes: int) -> bytes: + # pass + + def _seek_check(self, frame: int) -> bool: + if ( + frame < self._min_frame + # Only check upper limit on frames if additional seek operations + # are not required to do so + or ( + not (hasattr(self, "_n_frames") and self._n_frames is None) + and frame >= getattr(self, "n_frames") + self._min_frame + ) + ): + msg = "attempt to seek outside sequence" + raise EOFError(msg) + + return self.tell() != frame + + +class StubHandler(abc.ABC): + def open(self, im: StubImageFile) -> None: + pass + + @abc.abstractmethod + def load(self, im: StubImageFile) -> Image.Image: + pass + + +class StubImageFile(ImageFile, metaclass=abc.ABCMeta): + """ + Base class for stub image loaders. + + A stub loader is an image loader that can identify files of a + certain format, but relies on external code to load the file. + """ + + @abc.abstractmethod + def _open(self) -> None: + pass + + def load(self) -> Image.core.PixelAccess | None: + loader = self._load() + if loader is None: + msg = f"cannot find loader for this {self.format} file" + raise OSError(msg) + image = loader.load(self) + assert image is not None + # become the other object (!) + self.__class__ = image.__class__ # type: ignore[assignment] + self.__dict__ = image.__dict__ + return image.load() + + @abc.abstractmethod + def _load(self) -> StubHandler | None: + """(Hook) Find actual image loader.""" + pass + + +class Parser: + """ + Incremental image parser. This class implements the standard + feed/close consumer interface. + """ + + incremental = None + image: Image.Image | None = None + data: bytes | None = None + decoder: Image.core.ImagingDecoder | PyDecoder | None = None + offset = 0 + finished = 0 + + def reset(self) -> None: + """ + (Consumer) Reset the parser. Note that you can only call this + method immediately after you've created a parser; parser + instances cannot be reused. + """ + assert self.data is None, "cannot reuse parsers" + + def feed(self, data: bytes) -> None: + """ + (Consumer) Feed data to the parser. + + :param data: A string buffer. + :exception OSError: If the parser failed to parse the image file. + """ + # collect data + + if self.finished: + return + + if self.data is None: + self.data = data + else: + self.data = self.data + data + + # parse what we have + if self.decoder: + if self.offset > 0: + # skip header + skip = min(len(self.data), self.offset) + self.data = self.data[skip:] + self.offset = self.offset - skip + if self.offset > 0 or not self.data: + return + + n, e = self.decoder.decode(self.data) + + if n < 0: + # end of stream + self.data = None + self.finished = 1 + if e < 0: + # decoding error + self.image = None + raise _get_oserror(e, encoder=False) + else: + # end of image + return + self.data = self.data[n:] + + elif self.image: + # if we end up here with no decoder, this file cannot + # be incrementally parsed. wait until we've gotten all + # available data + pass + + else: + # attempt to open this file + try: + with io.BytesIO(self.data) as fp: + im = Image.open(fp) + except OSError: + pass # not enough data + else: + flag = hasattr(im, "load_seek") or hasattr(im, "load_read") + if not flag and len(im.tile) == 1: + # initialize decoder + im.load_prepare() + d, e, o, a = im.tile[0] + im.tile = [] + self.decoder = Image._getdecoder(im.mode, d, a, im.decoderconfig) + self.decoder.setimage(im.im, e) + + # calculate decoder offset + self.offset = o + if self.offset <= len(self.data): + self.data = self.data[self.offset :] + self.offset = 0 + + self.image = im + + def __enter__(self) -> Parser: + return self + + def __exit__(self, *args: object) -> None: + self.close() + + def close(self) -> Image.Image: + """ + (Consumer) Close the stream. + + :returns: An image object. + :exception OSError: If the parser failed to parse the image file either + because it cannot be identified or cannot be + decoded. + """ + # finish decoding + if self.decoder: + # get rid of what's left in the buffers + self.feed(b"") + self.data = self.decoder = None + if not self.finished: + msg = "image was incomplete" + raise OSError(msg) + if not self.image: + msg = "cannot parse this image" + raise OSError(msg) + if self.data: + # incremental parsing not possible; reopen the file + # not that we have all data + with io.BytesIO(self.data) as fp: + try: + self.image = Image.open(fp) + finally: + self.image.load() + return self.image + + +# -------------------------------------------------------------------- + + +def _save(im: Image.Image, fp: IO[bytes], tile: list[_Tile], bufsize: int = 0) -> None: + """Helper to save image based on tile list + + :param im: Image object. + :param fp: File object. + :param tile: Tile list. + :param bufsize: Optional buffer size + """ + + im.load() + if not hasattr(im, "encoderconfig"): + im.encoderconfig = () + tile.sort(key=_tilesort) + # FIXME: make MAXBLOCK a configuration parameter + # It would be great if we could have the encoder specify what it needs + # But, it would need at least the image size in most cases. RawEncode is + # a tricky case. + bufsize = max(MAXBLOCK, bufsize, im.size[0] * 4) # see RawEncode.c + try: + fh = fp.fileno() + fp.flush() + _encode_tile(im, fp, tile, bufsize, fh) + except (AttributeError, io.UnsupportedOperation) as exc: + _encode_tile(im, fp, tile, bufsize, None, exc) + if hasattr(fp, "flush"): + fp.flush() + + +def _encode_tile( + im: Image.Image, + fp: IO[bytes], + tile: list[_Tile], + bufsize: int, + fh: int | None, + exc: BaseException | None = None, +) -> None: + for encoder_name, extents, offset, args in tile: + if offset > 0: + fp.seek(offset) + encoder = Image._getencoder(im.mode, encoder_name, args, im.encoderconfig) + try: + encoder.setimage(im.im, extents) + if encoder.pushes_fd: + encoder.setfd(fp) + errcode = encoder.encode_to_pyfd()[1] + else: + if exc: + # compress to Python file-compatible object + while True: + errcode, data = encoder.encode(bufsize)[1:] + fp.write(data) + if errcode: + break + else: + # slight speedup: compress to real file object + assert fh is not None + errcode = encoder.encode_to_file(fh, bufsize) + if errcode < 0: + raise _get_oserror(errcode, encoder=True) from exc + finally: + encoder.cleanup() + + +def _safe_read(fp: IO[bytes], size: int) -> bytes: + """ + Reads large blocks in a safe way. Unlike fp.read(n), this function + doesn't trust the user. If the requested size is larger than + SAFEBLOCK, the file is read block by block. + + :param fp: File handle. Must implement a read method. + :param size: Number of bytes to read. + :returns: A string containing size bytes of data. + + Raises an OSError if the file is truncated and the read cannot be completed + + """ + if size <= 0: + return b"" + if size <= SAFEBLOCK: + data = fp.read(size) + if len(data) < size: + msg = "Truncated File Read" + raise OSError(msg) + return data + blocks: list[bytes] = [] + remaining_size = size + while remaining_size > 0: + block = fp.read(min(remaining_size, SAFEBLOCK)) + if not block: + break + blocks.append(block) + remaining_size -= len(block) + if sum(len(block) for block in blocks) < size: + msg = "Truncated File Read" + raise OSError(msg) + return b"".join(blocks) + + +class PyCodecState: + def __init__(self) -> None: + self.xsize = 0 + self.ysize = 0 + self.xoff = 0 + self.yoff = 0 + + def extents(self) -> tuple[int, int, int, int]: + return self.xoff, self.yoff, self.xoff + self.xsize, self.yoff + self.ysize + + +class PyCodec: + fd: IO[bytes] | None + + def __init__(self, mode: str, *args: Any) -> None: + self.im: Image.core.ImagingCore | None = None + self.state = PyCodecState() + self.fd = None + self.mode = mode + self.init(args) + + def init(self, args: tuple[Any, ...]) -> None: + """ + Override to perform codec specific initialization + + :param args: Tuple of arg items from the tile entry + :returns: None + """ + self.args = args + + def cleanup(self) -> None: + """ + Override to perform codec specific cleanup + + :returns: None + """ + pass + + def setfd(self, fd: IO[bytes]) -> None: + """ + Called from ImageFile to set the Python file-like object + + :param fd: A Python file-like object + :returns: None + """ + self.fd = fd + + def setimage( + self, + im: Image.core.ImagingCore, + extents: tuple[int, int, int, int] | None = None, + ) -> None: + """ + Called from ImageFile to set the core output image for the codec + + :param im: A core image object + :param extents: a 4 tuple of (x0, y0, x1, y1) defining the rectangle + for this tile + :returns: None + """ + + # following c code + self.im = im + + if extents: + x0, y0, x1, y1 = extents + + if x0 < 0 or y0 < 0 or x1 > self.im.size[0] or y1 > self.im.size[1]: + msg = "Tile cannot extend outside image" + raise ValueError(msg) + + self.state.xoff = x0 + self.state.yoff = y0 + self.state.xsize = x1 - x0 + self.state.ysize = y1 - y0 + else: + self.state.xsize, self.state.ysize = self.im.size + + if self.state.xsize <= 0 or self.state.ysize <= 0: + msg = "Size must be positive" + raise ValueError(msg) + + +class PyDecoder(PyCodec): + """ + Python implementation of a format decoder. Override this class and + add the decoding logic in the :meth:`decode` method. + + See :ref:`Writing Your Own File Codec in Python` + """ + + _pulls_fd = False + + @property + def pulls_fd(self) -> bool: + return self._pulls_fd + + def decode(self, buffer: Image.DecoderInput) -> tuple[int, int]: + """ + Override to perform the decoding process. + + :param buffer: A bytes object with the data to be decoded. + :returns: A tuple of ``(bytes consumed, errcode)``. + If finished with decoding return -1 for the bytes consumed. + Err codes are from :data:`.ImageFile.ERRORS`. + """ + msg = "unavailable in base decoder" + raise NotImplementedError(msg) + + def set_as_raw( + self, + data: bytes | bytearray, + rawmode: str | None = None, + extra: tuple[Any, ...] = (), + ) -> None: + """ + Convenience method to set the internal image from a stream of raw data + + :param data: Bytes to be set + :param rawmode: The rawmode to be used for the decoder. + If not specified, it will default to the mode of the image + :param extra: Extra arguments for the decoder. + :returns: None + """ + + if not rawmode: + rawmode = self.mode + d = Image._getdecoder(self.mode, "raw", rawmode, extra) + assert self.im is not None + d.setimage(self.im, self.state.extents()) + s = d.decode(data) + + if s[0] >= 0: + msg = "not enough image data" + raise ValueError(msg) + if s[1] != 0: + msg = "cannot decode image data" + raise ValueError(msg) + + +class PyEncoder(PyCodec): + """ + Python implementation of a format encoder. Override this class and + add the decoding logic in the :meth:`encode` method. + + See :ref:`Writing Your Own File Codec in Python` + """ + + _pushes_fd = False + + @property + def pushes_fd(self) -> bool: + return self._pushes_fd + + def encode(self, bufsize: int) -> tuple[int, int, bytes]: + """ + Override to perform the encoding process. + + :param bufsize: Buffer size. + :returns: A tuple of ``(bytes encoded, errcode, bytes)``. + If finished with encoding return 1 for the error code. + Err codes are from :data:`.ImageFile.ERRORS`. + """ + msg = "unavailable in base encoder" + raise NotImplementedError(msg) + + def encode_to_pyfd(self) -> tuple[int, int]: + """ + If ``pushes_fd`` is ``True``, then this method will be used, + and ``encode()`` will only be called once. + + :returns: A tuple of ``(bytes consumed, errcode)``. + Err codes are from :data:`.ImageFile.ERRORS`. + """ + if not self.pushes_fd: + return 0, -8 # bad configuration + bytes_consumed, errcode, data = self.encode(0) + if data: + assert self.fd is not None + self.fd.write(data) + return bytes_consumed, errcode + + def encode_to_file(self, fh: int, bufsize: int) -> int: + """ + :param fh: File handle. + :param bufsize: Buffer size. + + :returns: If finished successfully, return 0. + Otherwise, return an error code. Err codes are from + :data:`.ImageFile.ERRORS`. + """ + errcode = 0 + while errcode == 0: + status, errcode, buf = self.encode(bufsize) + if status > 0: + os.write(fh, buf[status:]) + return errcode diff --git a/.venv/lib/python3.11/site-packages/PIL/ImageFilter.py b/.venv/lib/python3.11/site-packages/PIL/ImageFilter.py new file mode 100644 index 0000000000000000000000000000000000000000..823365af0761cffa69b14f844ce5c7b39f90dbb2 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/ImageFilter.py @@ -0,0 +1,617 @@ +# +# The Python Imaging Library. +# $Id$ +# +# standard filters +# +# History: +# 1995-11-27 fl Created +# 2002-06-08 fl Added rank and mode filters +# 2003-09-15 fl Fixed rank calculation in rank filter; added expand call +# +# Copyright (c) 1997-2003 by Secret Labs AB. +# Copyright (c) 1995-2002 by Fredrik Lundh. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import abc +import functools +from collections.abc import Sequence +from typing import cast + +TYPE_CHECKING = False +if TYPE_CHECKING: + from collections.abc import Callable + from types import ModuleType + from typing import Any + + from . import _imaging + from ._typing import NumpyArray + + +class Filter(abc.ABC): + @abc.abstractmethod + def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore: + pass + + +class MultibandFilter(Filter): + pass + + +class BuiltinFilter(MultibandFilter): + name: str + filterargs: tuple[Any, ...] + + def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore: + if image.mode == "P": + msg = "cannot filter palette images" + raise ValueError(msg) + return image.filter(*self.filterargs) + + +class Kernel(BuiltinFilter): + """ + Create a convolution kernel. This only supports 3x3 and 5x5 integer and floating + point kernels. + + Kernels can only be applied to "L" and "RGB" images. + + :param size: Kernel size, given as (width, height). This must be (3,3) or (5,5). + :param kernel: A sequence containing kernel weights. The kernel will be flipped + vertically before being applied to the image. + :param scale: Scale factor. If given, the result for each pixel is divided by this + value. The default is the sum of the kernel weights. + :param offset: Offset. If given, this value is added to the result, after it has + been divided by the scale factor. + """ + + name = "Kernel" + + def __init__( + self, + size: tuple[int, int], + kernel: Sequence[float], + scale: float | None = None, + offset: float = 0, + ) -> None: + if scale is None: + # default scale is sum of kernel + scale = functools.reduce(lambda a, b: a + b, kernel) + if size[0] * size[1] != len(kernel): + msg = "not enough coefficients in kernel" + raise ValueError(msg) + self.filterargs = size, scale, offset, kernel + + +class RankFilter(Filter): + """ + Create a rank filter. The rank filter sorts all pixels in + a window of the given size, and returns the ``rank``'th value. + + :param size: The kernel size, in pixels. + :param rank: What pixel value to pick. Use 0 for a min filter, + ``size * size / 2`` for a median filter, ``size * size - 1`` + for a max filter, etc. + """ + + name = "Rank" + + def __init__(self, size: int, rank: int) -> None: + if size % 2 == 0: + msg = "bad filter size" + raise ValueError(msg) + if size * size * 4 > (2**31 - 1): + msg = "filter size too large" + raise ValueError(msg) + if rank < 0 or rank >= size * size: + msg = "bad rank value" + raise ValueError(msg) + self.size = size + self.rank = rank + + def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore: + if image.mode == "P": + msg = "cannot filter palette images" + raise ValueError(msg) + image = image.expand(self.size // 2) + return image.rankfilter(self.size, self.rank) + + +class MedianFilter(RankFilter): + """ + Create a median filter. Picks the median pixel value in a window with the + given size. + + :param size: The kernel size, in pixels. + """ + + name = "Median" + + def __init__(self, size: int = 3) -> None: + rank = size * size // 2 + super().__init__(size, rank) + + +class MinFilter(RankFilter): + """ + Create a min filter. Picks the lowest pixel value in a window with the + given size. + + :param size: The kernel size, in pixels. + """ + + name = "Min" + + def __init__(self, size: int = 3) -> None: + rank = 0 + super().__init__(size, rank) + + +class MaxFilter(RankFilter): + """ + Create a max filter. Picks the largest pixel value in a window with the + given size. + + :param size: The kernel size, in pixels. + """ + + name = "Max" + + def __init__(self, size: int = 3) -> None: + rank = size * size - 1 + super().__init__(size, rank) + + +class ModeFilter(Filter): + """ + Create a mode filter. Picks the most frequent pixel value in a box with the + given size. Pixel values that occur only once or twice are ignored; if no + pixel value occurs more than twice, the original pixel value is preserved. + + :param size: The kernel size, in pixels. + """ + + name = "Mode" + + def __init__(self, size: int = 3) -> None: + self.size = size + + def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore: + return image.modefilter(self.size) + + +class GaussianBlur(MultibandFilter): + """Blurs the image with a sequence of extended box filters, which + approximates a Gaussian kernel. For details on accuracy see + + + :param radius: Standard deviation of the Gaussian kernel. Either a sequence of two + numbers for x and y, or a single number for both. + """ + + name = "GaussianBlur" + + def __init__(self, radius: float | Sequence[float] = 2) -> None: + self.radius = radius + + def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore: + xy = self.radius + if xy == (0, 0) or xy == 0: + return image.copy() + if isinstance(xy, (int, float)): + xy = (xy, xy) + return image.gaussian_blur(xy) + + +class BoxBlur(MultibandFilter): + """Blurs the image by setting each pixel to the average value of the pixels + in a square box extending radius pixels in each direction. + Supports float radius of arbitrary size. Uses an optimized implementation + which runs in linear time relative to the size of the image + for any radius value. + + :param radius: Size of the box in a direction. Either a sequence of two numbers for + x and y, or a single number for both. + + Radius 0 does not blur, returns an identical image. + Radius 1 takes 1 pixel in each direction, i.e. 9 pixels in total. + """ + + name = "BoxBlur" + + def __init__(self, radius: float | Sequence[float]) -> None: + xy = radius if isinstance(radius, (tuple, list)) else (radius, radius) + if xy[0] < 0 or xy[1] < 0: + msg = "radius must be >= 0" + raise ValueError(msg) + self.radius = radius + + def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore: + xy = self.radius + if xy == (0, 0) or xy == 0: + return image.copy() + if isinstance(xy, (int, float)): + xy = (xy, xy) + return image.box_blur(xy) + + +class UnsharpMask(MultibandFilter): + """Unsharp mask filter. + + See Wikipedia's entry on `digital unsharp masking`_ for an explanation of + the parameters. + + :param radius: Blur Radius + :param percent: Unsharp strength, in percent + :param threshold: Threshold controls the minimum brightness change that + will be sharpened + + .. _digital unsharp masking: https://en.wikipedia.org/wiki/Unsharp_masking#Digital_unsharp_masking + + """ + + name = "UnsharpMask" + + def __init__( + self, radius: float = 2, percent: int = 150, threshold: int = 3 + ) -> None: + self.radius = radius + self.percent = percent + self.threshold = threshold + + def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore: + return image.unsharp_mask(self.radius, self.percent, self.threshold) + + +class BLUR(BuiltinFilter): + name = "Blur" + # fmt: off + filterargs = (5, 5), 16, 0, ( + 1, 1, 1, 1, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 0, 0, 0, 1, + 1, 1, 1, 1, 1, + ) + # fmt: on + + +class CONTOUR(BuiltinFilter): + name = "Contour" + # fmt: off + filterargs = (3, 3), 1, 255, ( + -1, -1, -1, + -1, 8, -1, + -1, -1, -1, + ) + # fmt: on + + +class DETAIL(BuiltinFilter): + name = "Detail" + # fmt: off + filterargs = (3, 3), 6, 0, ( + 0, -1, 0, + -1, 10, -1, + 0, -1, 0, + ) + # fmt: on + + +class EDGE_ENHANCE(BuiltinFilter): + name = "Edge-enhance" + # fmt: off + filterargs = (3, 3), 2, 0, ( + -1, -1, -1, + -1, 10, -1, + -1, -1, -1, + ) + # fmt: on + + +class EDGE_ENHANCE_MORE(BuiltinFilter): + name = "Edge-enhance More" + # fmt: off + filterargs = (3, 3), 1, 0, ( + -1, -1, -1, + -1, 9, -1, + -1, -1, -1, + ) + # fmt: on + + +class EMBOSS(BuiltinFilter): + name = "Emboss" + # fmt: off + filterargs = (3, 3), 1, 128, ( + -1, 0, 0, + 0, 1, 0, + 0, 0, 0, + ) + # fmt: on + + +class FIND_EDGES(BuiltinFilter): + name = "Find Edges" + # fmt: off + filterargs = (3, 3), 1, 0, ( + -1, -1, -1, + -1, 8, -1, + -1, -1, -1, + ) + # fmt: on + + +class SHARPEN(BuiltinFilter): + name = "Sharpen" + # fmt: off + filterargs = (3, 3), 16, 0, ( + -2, -2, -2, + -2, 32, -2, + -2, -2, -2, + ) + # fmt: on + + +class SMOOTH(BuiltinFilter): + name = "Smooth" + # fmt: off + filterargs = (3, 3), 13, 0, ( + 1, 1, 1, + 1, 5, 1, + 1, 1, 1, + ) + # fmt: on + + +class SMOOTH_MORE(BuiltinFilter): + name = "Smooth More" + # fmt: off + filterargs = (5, 5), 100, 0, ( + 1, 1, 1, 1, 1, + 1, 5, 5, 5, 1, + 1, 5, 44, 5, 1, + 1, 5, 5, 5, 1, + 1, 1, 1, 1, 1, + ) + # fmt: on + + +class Color3DLUT(MultibandFilter): + """Three-dimensional color lookup table. + + Transforms 3-channel pixels using the values of the channels as coordinates + in the 3D lookup table and interpolating the nearest elements. + + This method allows you to apply almost any color transformation + in constant time by using pre-calculated decimated tables. + + .. versionadded:: 5.2.0 + + :param size: Size of the table. One int or tuple of (int, int, int). + Minimal size in any dimension is 2, maximum is 65. + :param table: Flat lookup table. A list of ``channels * size**3`` + float elements or a list of ``size**3`` channels-sized + tuples with floats. Channels are changed first, + then first dimension, then second, then third. + Value 0.0 corresponds lowest value of output, 1.0 highest. + :param channels: Number of channels in the table. Could be 3 or 4. + Default is 3. + :param target_mode: A mode for the result image. Should have not less + than ``channels`` channels. Default is ``None``, + which means that mode wouldn't be changed. + """ + + name = "Color 3D LUT" + + def __init__( + self, + size: int | tuple[int, int, int], + table: Sequence[float] | Sequence[Sequence[int]] | NumpyArray, + channels: int = 3, + target_mode: str | None = None, + **kwargs: bool, + ) -> None: + if channels not in (3, 4): + msg = "Only 3 or 4 output channels are supported" + raise ValueError(msg) + self.size = size = self._check_size(size) + self.channels = channels + self.mode = target_mode + + # Hidden flag `_copy_table=False` could be used to avoid extra copying + # of the table if the table is specially made for the constructor. + copy_table = kwargs.get("_copy_table", True) + items = size[0] * size[1] * size[2] + wrong_size = False + + numpy: ModuleType | None = None + if hasattr(table, "shape"): + try: + import numpy + except ImportError: + pass + + if numpy and isinstance(table, numpy.ndarray): + numpy_table: NumpyArray = table + if copy_table: + numpy_table = numpy_table.copy() + + if numpy_table.shape in [ + (items * channels,), + (items, channels), + (size[2], size[1], size[0], channels), + ]: + table = numpy_table.reshape(items * channels) + else: + wrong_size = True + + else: + if copy_table: + table = list(table) + + # Convert to a flat list + if table and isinstance(table[0], (list, tuple)): + raw_table = cast(Sequence[Sequence[int]], table) + flat_table: list[int] = [] + for pixel in raw_table: + if len(pixel) != channels: + msg = ( + "The elements of the table should " + f"have a length of {channels}." + ) + raise ValueError(msg) + flat_table.extend(pixel) + table = flat_table + + if wrong_size or len(table) != items * channels: + msg = ( + "The table should have either channels * size**3 float items " + "or size**3 items of channels-sized tuples with floats. " + f"Table should be: {channels}x{size[0]}x{size[1]}x{size[2]}. " + f"Actual length: {len(table)}" + ) + raise ValueError(msg) + self.table = table + + @staticmethod + def _check_size(size: Any) -> tuple[int, int, int]: + try: + _, _, _ = size + except ValueError as e: + msg = "Size should be either an integer or a tuple of three integers." + raise ValueError(msg) from e + except TypeError: + size = (size, size, size) + size = tuple(int(x) for x in size) + for size_1d in size: + if not 2 <= size_1d <= 65: + msg = "Size should be in [2, 65] range." + raise ValueError(msg) + return size + + @classmethod + def generate( + cls, + size: int | tuple[int, int, int], + callback: Callable[[float, float, float], tuple[float, ...]], + channels: int = 3, + target_mode: str | None = None, + ) -> Color3DLUT: + """Generates new LUT using provided callback. + + :param size: Size of the table. Passed to the constructor. + :param callback: Function with three parameters which correspond + three color channels. Will be called ``size**3`` + times with values from 0.0 to 1.0 and should return + a tuple with ``channels`` elements. + :param channels: The number of channels which should return callback. + :param target_mode: Passed to the constructor of the resulting + lookup table. + """ + size_1d, size_2d, size_3d = cls._check_size(size) + if channels not in (3, 4): + msg = "Only 3 or 4 output channels are supported" + raise ValueError(msg) + + table: list[float] = [0] * (size_1d * size_2d * size_3d * channels) + idx_out = 0 + for b in range(size_3d): + for g in range(size_2d): + for r in range(size_1d): + table[idx_out : idx_out + channels] = callback( + r / (size_1d - 1), g / (size_2d - 1), b / (size_3d - 1) + ) + idx_out += channels + + return cls( + (size_1d, size_2d, size_3d), + table, + channels=channels, + target_mode=target_mode, + _copy_table=False, + ) + + def transform( + self, + callback: Callable[..., tuple[float, ...]], + with_normals: bool = False, + channels: int | None = None, + target_mode: str | None = None, + ) -> Color3DLUT: + """Transforms the table values using provided callback and returns + a new LUT with altered values. + + :param callback: A function which takes old lookup table values + and returns a new set of values. The number + of arguments which function should take is + ``self.channels`` or ``3 + self.channels`` + if ``with_normals`` flag is set. + Should return a tuple of ``self.channels`` or + ``channels`` elements if it is set. + :param with_normals: If true, ``callback`` will be called with + coordinates in the color cube as the first + three arguments. Otherwise, ``callback`` + will be called only with actual color values. + :param channels: The number of channels in the resulting lookup table. + :param target_mode: Passed to the constructor of the resulting + lookup table. + """ + if channels not in (None, 3, 4): + msg = "Only 3 or 4 output channels are supported" + raise ValueError(msg) + ch_in = self.channels + ch_out = channels or ch_in + size_1d, size_2d, size_3d = self.size + + table: list[float] = [0] * (size_1d * size_2d * size_3d * ch_out) + idx_in = 0 + idx_out = 0 + for b in range(size_3d): + for g in range(size_2d): + for r in range(size_1d): + values = self.table[idx_in : idx_in + ch_in] + if with_normals: + values = callback( + r / (size_1d - 1), + g / (size_2d - 1), + b / (size_3d - 1), + *values, + ) + else: + values = callback(*values) + table[idx_out : idx_out + ch_out] = values + idx_in += ch_in + idx_out += ch_out + + return type(self)( + self.size, + table, + channels=ch_out, + target_mode=target_mode or self.mode, + _copy_table=False, + ) + + def __repr__(self) -> str: + r = [ + f"{self.__class__.__name__} from {self.table.__class__.__name__}", + "size={:d}x{:d}x{:d}".format(*self.size), + f"channels={self.channels:d}", + ] + if self.mode: + r.append(f"target_mode={self.mode}") + return "<{}>".format(" ".join(r)) + + def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore: + from . import Image + + return image.color_lut_3d( + self.mode or image.mode, + Image.Resampling.BILINEAR, + self.channels, + self.size, + self.table, + ) diff --git a/.venv/lib/python3.11/site-packages/PIL/ImageFont.py b/.venv/lib/python3.11/site-packages/PIL/ImageFont.py new file mode 100644 index 0000000000000000000000000000000000000000..65edf5659fab684623ab7120b616d46018f88a6e --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/ImageFont.py @@ -0,0 +1,1330 @@ +# +# The Python Imaging Library. +# $Id$ +# +# PIL raster font management +# +# History: +# 1996-08-07 fl created (experimental) +# 1997-08-25 fl minor adjustments to handle fonts from pilfont 0.3 +# 1999-02-06 fl rewrote most font management stuff in C +# 1999-03-17 fl take pth files into account in load_path (from Richard Jones) +# 2001-02-17 fl added freetype support +# 2001-05-09 fl added TransposedFont wrapper class +# 2002-03-04 fl make sure we have a "L" or "1" font +# 2002-12-04 fl skip non-directory entries in the system path +# 2003-04-29 fl add embedded default font +# 2003-09-27 fl added support for truetype charmap encodings +# +# Todo: +# Adapt to PILFONT2 format (16-bit fonts, compressed, single file) +# +# Copyright (c) 1997-2003 by Secret Labs AB +# Copyright (c) 1996-2003 by Fredrik Lundh +# +# See the README file for information on usage and redistribution. +# + +from __future__ import annotations + +import abc +import base64 +import os +import sys +import warnings +from enum import IntEnum +from io import BytesIO +from types import ModuleType +from typing import IO, Any, BinaryIO, TypedDict, cast + +from . import Image +from ._typing import StrOrBytesPath +from ._util import DeferredError, is_path + +TYPE_CHECKING = False +if TYPE_CHECKING: + from . import ImageFile + from ._imaging import ImagingFont + from ._imagingft import Font + + +class Axis(TypedDict): + minimum: int | None + default: int | None + maximum: int | None + name: bytes | None + + +class Layout(IntEnum): + BASIC = 0 + RAQM = 1 + + +MAX_STRING_LENGTH = 1_000_000 + + +core: ModuleType | DeferredError +try: + from . import _imagingft as core +except ImportError as ex: + core = DeferredError.new(ex) + + +def _string_length_check(text: str | bytes | bytearray) -> None: + if MAX_STRING_LENGTH is not None and len(text) > MAX_STRING_LENGTH: + msg = "too many characters in string" + raise ValueError(msg) + + +# FIXME: add support for pilfont2 format (see FontFile.py) + +# -------------------------------------------------------------------- +# Font metrics format: +# "PILfont" LF +# fontdescriptor LF +# (optional) key=value... LF +# "DATA" LF +# binary data: 256*10*2 bytes (dx, dy, dstbox, srcbox) +# +# To place a character, cut out srcbox and paste at dstbox, +# relative to the character position. Then move the character +# position according to dx, dy. +# -------------------------------------------------------------------- + + +class BaseImageFont(abc.ABC): + """Used by ImageDraw and ImageText""" + + @abc.abstractmethod + def getbbox( + self, text: str | bytes | bytearray, *args: Any, **kwargs: Any + ) -> tuple[float, float, float, float]: + pass + + @abc.abstractmethod + def getmask( + self, text: str | bytes, mode: str = "", *args: Any, **kwargs: Any + ) -> Image.core.ImagingCore: + pass + + @abc.abstractmethod + def getlength(self, text: str | bytes, *args: Any, **kwargs: Any) -> float: + pass + + +class ImageFont(BaseImageFont): + """PIL font wrapper""" + + font: ImagingFont + + def _load_pilfont(self, filename: str) -> None: + with open(filename, "rb") as fp: + image: ImageFile.ImageFile | None = None + root = os.path.splitext(filename)[0] + + for ext in (".png", ".gif", ".pbm"): + if image: + image.close() + try: + fullname = root + ext + image = Image.open(fullname) + except Exception: + pass + else: + if image.mode in ("1", "L"): + break + else: + if image: + image.close() + + msg = f"cannot find glyph data file {root}.{{gif|pbm|png}}" + raise OSError(msg) + + self.file = fullname + + self._load_pilfont_data(fp, image) + image.close() + + def _load_pilfont_data(self, file: IO[bytes], image: Image.Image) -> None: + # check image + if image.mode not in ("1", "L"): + image.close() + + msg = "invalid font image mode" + raise TypeError(msg) + + # read PILfont header + if file.read(8) != b"PILfont\n": + image.close() + + msg = "Not a PILfont file" + raise SyntaxError(msg) + file.readline() + self.info = [] # FIXME: should be a dictionary + while True: + s = file.readline() + if not s or s == b"DATA\n": + break + self.info.append(s) + + # read PILfont metrics + data = file.read(256 * 20) + + self._load(image, data) + + def _load(self, image: Image.Image, data: bytes) -> None: + image.load() + + self.font = Image.core.font(image.im, data) + + def getmask( + self, text: str | bytes, mode: str = "", *args: Any, **kwargs: Any + ) -> Image.core.ImagingCore: + """ + Create a bitmap for the text. + + If the font uses antialiasing, the bitmap should have mode ``L`` and use a + maximum value of 255. Otherwise, it should have mode ``1``. + + :param text: Text to render. + :param mode: Used by some graphics drivers to indicate what mode the + driver prefers; if empty, the renderer may return either + mode. Note that the mode is always a string, to simplify + C-level implementations. + + .. versionadded:: 1.1.5 + + :return: An internal PIL storage memory instance as defined by the + :py:mod:`PIL.Image.core` interface module. + """ + _string_length_check(text) + Image._decompression_bomb_check(self.font.getsize(text)) + return self.font.getmask(text, mode) + + def getbbox( + self, text: str | bytes | bytearray, *args: Any, **kwargs: Any + ) -> tuple[int, int, int, int]: + """ + Returns bounding box (in pixels) of given text. + + .. versionadded:: 9.2.0 + + :param text: Text to render. + + :return: ``(left, top, right, bottom)`` bounding box + """ + _string_length_check(text) + width, height = self.font.getsize(text) + return 0, 0, width, height + + def getlength( + self, text: str | bytes | bytearray, *args: Any, **kwargs: Any + ) -> int: + """ + Returns length (in pixels) of given text. + This is the amount by which following text should be offset. + + .. versionadded:: 9.2.0 + """ + _string_length_check(text) + width, height = self.font.getsize(text) + return width + + +## +# Wrapper for FreeType fonts. Application code should use the +# truetype factory function to create font objects. + + +class FreeTypeFont(BaseImageFont): + """FreeType font wrapper (requires _imagingft service)""" + + font: Font + font_bytes: bytes + + def __init__( + self, + font: StrOrBytesPath | BinaryIO, + size: float = 10, + index: int = 0, + encoding: str = "", + layout_engine: Layout | None = None, + ) -> None: + # FIXME: use service provider instead + + if isinstance(core, DeferredError): + raise core.ex + + if size <= 0: + msg = f"font size must be greater than 0, not {size}" + raise ValueError(msg) + + self.path = font + self.size = size + self.index = index + self.encoding = encoding + + if layout_engine not in (Layout.BASIC, Layout.RAQM): + layout_engine = Layout.BASIC + if core.HAVE_RAQM: + layout_engine = Layout.RAQM + elif layout_engine == Layout.RAQM and not core.HAVE_RAQM: + warnings.warn( + "Raqm layout was requested, but Raqm is not available. " + "Falling back to basic layout." + ) + layout_engine = Layout.BASIC + + self.layout_engine = layout_engine + + def load_from_bytes(f: IO[bytes]) -> None: + self.font_bytes = f.read() + self.font = core.getfont( + "", size, index, encoding, self.font_bytes, layout_engine + ) + + if is_path(font): + font = os.fspath(font) + if sys.platform == "win32": + font_bytes_path = font if isinstance(font, bytes) else font.encode() + try: + font_bytes_path.decode("ascii") + except UnicodeDecodeError: + # FreeType cannot load fonts with non-ASCII characters on Windows + # So load it into memory first + with open(font, "rb") as f: + load_from_bytes(f) + return + self.font = core.getfont( + font, size, index, encoding, layout_engine=layout_engine + ) + else: + load_from_bytes(cast(IO[bytes], font)) + + def __getstate__(self) -> list[Any]: + return [self.path, self.size, self.index, self.encoding, self.layout_engine] + + def __setstate__(self, state: list[Any]) -> None: + path, size, index, encoding, layout_engine = state + FreeTypeFont.__init__(self, path, size, index, encoding, layout_engine) + + def getname(self) -> tuple[str | None, str | None]: + """ + :return: A tuple of the font family (e.g. Helvetica) and the font style + (e.g. Bold) + """ + return self.font.family, self.font.style + + def getmetrics(self) -> tuple[int, int]: + """ + :return: A tuple of the font ascent (the distance from the baseline to + the highest outline point) and descent (the distance from the + baseline to the lowest outline point, a negative value) + """ + return self.font.ascent, self.font.descent + + def getlength( + self, + text: str | bytes, + mode: str = "", + direction: str | None = None, + features: list[str] | None = None, + language: str | None = None, + ) -> float: + """ + Returns length (in pixels with 1/64 precision) of given text when rendered + in font with provided direction, features, and language. + + This is the amount by which following text should be offset. + Text bounding box may extend past the length in some fonts, + e.g. when using italics or accents. + + The result is returned as a float; it is a whole number if using basic layout. + + Note that the sum of two lengths may not equal the length of a concatenated + string due to kerning. If you need to adjust for kerning, include the following + character and subtract its length. + + For example, instead of :: + + hello = font.getlength("Hello") + world = font.getlength("World") + hello_world = hello + world # not adjusted for kerning + assert hello_world == font.getlength("HelloWorld") # may fail + + use :: + + hello = font.getlength("HelloW") - font.getlength("W") # adjusted for kerning + world = font.getlength("World") + hello_world = hello + world # adjusted for kerning + assert hello_world == font.getlength("HelloWorld") # True + + or disable kerning with (requires libraqm) :: + + hello = draw.textlength("Hello", font, features=["-kern"]) + world = draw.textlength("World", font, features=["-kern"]) + hello_world = hello + world # kerning is disabled, no need to adjust + assert hello_world == draw.textlength("HelloWorld", font, features=["-kern"]) + + .. versionadded:: 8.0.0 + + :param text: Text to measure. + :param mode: Used by some graphics drivers to indicate what mode the + driver prefers; if empty, the renderer may return either + mode. Note that the mode is always a string, to simplify + C-level implementations. + + :param direction: Direction of the text. It can be 'rtl' (right to + left), 'ltr' (left to right) or 'ttb' (top to bottom). + Requires libraqm. + + :param features: A list of OpenType font features to be used during text + layout. This is usually used to turn on optional + font features that are not enabled by default, + for example 'dlig' or 'ss01', but can be also + used to turn off default font features for + example '-liga' to disable ligatures or '-kern' + to disable kerning. To get all supported + features, see + https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist + Requires libraqm. + + :param language: Language of the text. Different languages may use + different glyph shapes or ligatures. This parameter tells + the font which language the text is in, and to apply the + correct substitutions as appropriate, if available. + It should be a `BCP 47 language code + `_ + Requires libraqm. + + :return: Either width for horizontal text, or height for vertical text. + """ + _string_length_check(text) + return self.font.getlength(text, mode, direction, features, language) / 64 + + def getbbox( + self, + text: str | bytes | bytearray, + mode: str = "", + direction: str | None = None, + features: list[str] | None = None, + language: str | None = None, + stroke_width: float = 0, + anchor: str | None = None, + ) -> tuple[float, float, float, float]: + """ + Returns bounding box (in pixels) of given text relative to given anchor + when rendered in font with provided direction, features, and language. + + Use :py:meth:`getlength()` to get the offset of following text with + 1/64 pixel precision. The bounding box includes extra margins for + some fonts, e.g. italics or accents. + + .. versionadded:: 8.0.0 + + :param text: Text to render. + :param mode: Used by some graphics drivers to indicate what mode the + driver prefers; if empty, the renderer may return either + mode. Note that the mode is always a string, to simplify + C-level implementations. + + :param direction: Direction of the text. It can be 'rtl' (right to + left), 'ltr' (left to right) or 'ttb' (top to bottom). + Requires libraqm. + + :param features: A list of OpenType font features to be used during text + layout. This is usually used to turn on optional + font features that are not enabled by default, + for example 'dlig' or 'ss01', but can be also + used to turn off default font features for + example '-liga' to disable ligatures or '-kern' + to disable kerning. To get all supported + features, see + https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist + Requires libraqm. + + :param language: Language of the text. Different languages may use + different glyph shapes or ligatures. This parameter tells + the font which language the text is in, and to apply the + correct substitutions as appropriate, if available. + It should be a `BCP 47 language code + `_ + Requires libraqm. + + :param stroke_width: The width of the text stroke. + + :param anchor: The text anchor alignment. Determines the relative location of + the anchor to the text. The default alignment is top left, + specifically ``la`` for horizontal text and ``lt`` for + vertical text. See :ref:`text-anchors` for details. + + :return: ``(left, top, right, bottom)`` bounding box + """ + _string_length_check(text) + size, offset = self.font.getsize( + text, mode, direction, features, language, anchor + ) + left, top = offset[0] - stroke_width, offset[1] - stroke_width + width, height = size[0] + 2 * stroke_width, size[1] + 2 * stroke_width + return left, top, left + width, top + height + + def getmask( + self, + text: str | bytes, + mode: str = "", + direction: str | None = None, + features: list[str] | None = None, + language: str | None = None, + stroke_width: float = 0, + anchor: str | None = None, + ink: int = 0, + start: tuple[float, float] | None = None, + ) -> Image.core.ImagingCore: + """ + Create a bitmap for the text. + + If the font uses antialiasing, the bitmap should have mode ``L`` and use a + maximum value of 255. If the font has embedded color data, the bitmap + should have mode ``RGBA``. Otherwise, it should have mode ``1``. + + :param text: Text to render. + :param mode: Used by some graphics drivers to indicate what mode the + driver prefers; if empty, the renderer may return either + mode. Note that the mode is always a string, to simplify + C-level implementations. + + .. versionadded:: 1.1.5 + + :param direction: Direction of the text. It can be 'rtl' (right to + left), 'ltr' (left to right) or 'ttb' (top to bottom). + Requires libraqm. + + .. versionadded:: 4.2.0 + + :param features: A list of OpenType font features to be used during text + layout. This is usually used to turn on optional + font features that are not enabled by default, + for example 'dlig' or 'ss01', but can be also + used to turn off default font features for + example '-liga' to disable ligatures or '-kern' + to disable kerning. To get all supported + features, see + https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist + Requires libraqm. + + .. versionadded:: 4.2.0 + + :param language: Language of the text. Different languages may use + different glyph shapes or ligatures. This parameter tells + the font which language the text is in, and to apply the + correct substitutions as appropriate, if available. + It should be a `BCP 47 language code + `_ + Requires libraqm. + + .. versionadded:: 6.0.0 + + :param stroke_width: The width of the text stroke. + + .. versionadded:: 6.2.0 + + :param anchor: The text anchor alignment. Determines the relative location of + the anchor to the text. The default alignment is top left, + specifically ``la`` for horizontal text and ``lt`` for + vertical text. See :ref:`text-anchors` for details. + + .. versionadded:: 8.0.0 + + :param ink: Foreground ink for rendering in RGBA mode. + + .. versionadded:: 8.0.0 + + :param start: Tuple of horizontal and vertical offset, as text may render + differently when starting at fractional coordinates. + + .. versionadded:: 9.4.0 + + :return: An internal PIL storage memory instance as defined by the + :py:mod:`PIL.Image.core` interface module. + """ + return self.getmask2( + text, + mode, + direction=direction, + features=features, + language=language, + stroke_width=stroke_width, + anchor=anchor, + ink=ink, + start=start, + )[0] + + def getmask2( + self, + text: str | bytes, + mode: str = "", + direction: str | None = None, + features: list[str] | None = None, + language: str | None = None, + stroke_width: float = 0, + anchor: str | None = None, + ink: int = 0, + start: tuple[float, float] | None = None, + *args: Any, + **kwargs: Any, + ) -> tuple[Image.core.ImagingCore, tuple[int, int]]: + """ + Create a bitmap for the text. + + If the font uses antialiasing, the bitmap should have mode ``L`` and use a + maximum value of 255. If the font has embedded color data, the bitmap + should have mode ``RGBA``. Otherwise, it should have mode ``1``. + + :param text: Text to render. + :param mode: Used by some graphics drivers to indicate what mode the + driver prefers; if empty, the renderer may return either + mode. Note that the mode is always a string, to simplify + C-level implementations. + + .. versionadded:: 1.1.5 + + :param direction: Direction of the text. It can be 'rtl' (right to + left), 'ltr' (left to right) or 'ttb' (top to bottom). + Requires libraqm. + + .. versionadded:: 4.2.0 + + :param features: A list of OpenType font features to be used during text + layout. This is usually used to turn on optional + font features that are not enabled by default, + for example 'dlig' or 'ss01', but can be also + used to turn off default font features for + example '-liga' to disable ligatures or '-kern' + to disable kerning. To get all supported + features, see + https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist + Requires libraqm. + + .. versionadded:: 4.2.0 + + :param language: Language of the text. Different languages may use + different glyph shapes or ligatures. This parameter tells + the font which language the text is in, and to apply the + correct substitutions as appropriate, if available. + It should be a `BCP 47 language code + `_ + Requires libraqm. + + .. versionadded:: 6.0.0 + + :param stroke_width: The width of the text stroke. + + .. versionadded:: 6.2.0 + + :param anchor: The text anchor alignment. Determines the relative location of + the anchor to the text. The default alignment is top left, + specifically ``la`` for horizontal text and ``lt`` for + vertical text. See :ref:`text-anchors` for details. + + .. versionadded:: 8.0.0 + + :param ink: Foreground ink for rendering in RGBA mode. + + .. versionadded:: 8.0.0 + + :param start: Tuple of horizontal and vertical offset, as text may render + differently when starting at fractional coordinates. + + .. versionadded:: 9.4.0 + + :return: A tuple of an internal PIL storage memory instance as defined by the + :py:mod:`PIL.Image.core` interface module, and the text offset, the + gap between the starting coordinate and the first marking + """ + _string_length_check(text) + if start is None: + start = (0, 0) + + def fill(width: int, height: int) -> Image.core.ImagingCore: + size = (width, height) + Image._decompression_bomb_check(size) + return Image.core.fill("RGBA" if mode == "RGBA" else "L", size) + + return self.font.render( + text, + fill, + mode, + direction, + features, + language, + stroke_width, + kwargs.get("stroke_filled", False), + anchor, + ink, + start, + ) + + def font_variant( + self, + font: StrOrBytesPath | BinaryIO | None = None, + size: float | None = None, + index: int | None = None, + encoding: str | None = None, + layout_engine: Layout | None = None, + ) -> FreeTypeFont: + """ + Create a copy of this FreeTypeFont object, + using any specified arguments to override the settings. + + Parameters are identical to the parameters used to initialize this + object. + + :return: A FreeTypeFont object. + """ + if font is None: + try: + font = BytesIO(self.font_bytes) + except AttributeError: + font = self.path + return FreeTypeFont( + font=font, + size=self.size if size is None else size, + index=self.index if index is None else index, + encoding=self.encoding if encoding is None else encoding, + layout_engine=layout_engine or self.layout_engine, + ) + + def get_variation_names(self) -> list[bytes]: + """ + :returns: A list of the named styles in a variation font. + :exception OSError: If the font is not a variation font. + """ + names = [] + for name in self.font.getvarnames(): + name = name.replace(b"\x00", b"") + if name not in names: + names.append(name) + return names + + def set_variation_by_name(self, name: str | bytes) -> None: + """ + :param name: The name of the style. + :exception OSError: If the font is not a variation font. + """ + names = self.get_variation_names() + if not isinstance(name, bytes): + name = name.encode() + index = names.index(name) + 1 + + if index == getattr(self, "_last_variation_index", None): + # When the same name is set twice in a row, + # there is an 'unknown freetype error' + # https://savannah.nongnu.org/bugs/?56186 + return + self._last_variation_index = index + + self.font.setvarname(index) + + def get_variation_axes(self) -> list[Axis]: + """ + :returns: A list of the axes in a variation font. + :exception OSError: If the font is not a variation font. + """ + axes = self.font.getvaraxes() + for axis in axes: + if axis["name"]: + axis["name"] = axis["name"].replace(b"\x00", b"") + return axes + + def set_variation_by_axes(self, axes: list[float]) -> None: + """ + :param axes: A list of values for each axis. + :exception OSError: If the font is not a variation font. + """ + self.font.setvaraxes(axes) + + +class TransposedFont(BaseImageFont): + """Wrapper for writing rotated or mirrored text""" + + def __init__( + self, font: ImageFont | FreeTypeFont, orientation: Image.Transpose | None = None + ): + """ + Wrapper that creates a transposed font from any existing font + object. + + :param font: A font object. + :param orientation: An optional orientation. If given, this should + be one of Image.Transpose.FLIP_LEFT_RIGHT, Image.Transpose.FLIP_TOP_BOTTOM, + Image.Transpose.ROTATE_90, Image.Transpose.ROTATE_180, or + Image.Transpose.ROTATE_270. + """ + self.font = font + self.orientation = orientation # any 'transpose' argument, or None + + def getmask( + self, text: str | bytes, mode: str = "", *args: Any, **kwargs: Any + ) -> Image.core.ImagingCore: + im = self.font.getmask(text, mode, *args, **kwargs) + if self.orientation is not None: + return im.transpose(self.orientation) + return im + + def getbbox( + self, text: str | bytes | bytearray, *args: Any, **kwargs: Any + ) -> tuple[int, int, float, float]: + # TransposedFont doesn't support getmask2, move top-left point to (0, 0) + # this has no effect on ImageFont and simulates anchor="lt" for FreeTypeFont + left, top, right, bottom = self.font.getbbox(text, *args, **kwargs) + width = right - left + height = bottom - top + if self.orientation in (Image.Transpose.ROTATE_90, Image.Transpose.ROTATE_270): + return 0, 0, height, width + return 0, 0, width, height + + def getlength(self, text: str | bytes, *args: Any, **kwargs: Any) -> float: + if self.orientation in (Image.Transpose.ROTATE_90, Image.Transpose.ROTATE_270): + msg = "text length is undefined for text rotated by 90 or 270 degrees" + raise ValueError(msg) + return self.font.getlength(text, *args, **kwargs) + + +def load(filename: str) -> ImageFont: + """ + Load a font file. This function loads a font object from the given + bitmap font file, and returns the corresponding font object. For loading TrueType + or OpenType fonts instead, see :py:func:`~PIL.ImageFont.truetype`. + + :param filename: Name of font file. + :return: A font object. + :exception OSError: If the file could not be read. + """ + f = ImageFont() + f._load_pilfont(filename) + return f + + +def truetype( + font: StrOrBytesPath | BinaryIO, + size: float = 10, + index: int = 0, + encoding: str = "", + layout_engine: Layout | None = None, +) -> FreeTypeFont: + """ + Load a TrueType or OpenType font from a file or file-like object, + and create a font object. This function loads a font object from the given + file or file-like object, and creates a font object for a font of the given + size. For loading bitmap fonts instead, see :py:func:`~PIL.ImageFont.load` + and :py:func:`~PIL.ImageFont.load_path`. + + Pillow uses FreeType to open font files. On Windows, be aware that FreeType + will keep the file open as long as the FreeTypeFont object exists. Windows + limits the number of files that can be open in C at once to 512, so if many + fonts are opened simultaneously and that limit is approached, an + ``OSError`` may be thrown, reporting that FreeType "cannot open resource". + A workaround would be to copy the file(s) into memory, and open that instead. + + This function requires the _imagingft service. + + :param font: A filename or file-like object containing a TrueType font. + If the file is not found in this filename, the loader may also + search in other directories, such as: + + * The :file:`fonts/` directory on Windows, + * :file:`/Library/Fonts/`, :file:`/System/Library/Fonts/` + and :file:`~/Library/Fonts/` on macOS. + * :file:`~/.local/share/fonts`, :file:`/usr/local/share/fonts`, + and :file:`/usr/share/fonts` on Linux; or those specified by + the ``XDG_DATA_HOME`` and ``XDG_DATA_DIRS`` environment variables + for user-installed and system-wide fonts, respectively. + + :param size: The requested size, in pixels. + :param index: Which font face to load (default is first available face). + :param encoding: Which font encoding to use (default is Unicode). Possible + encodings include (see the FreeType documentation for more + information): + + * "unic" (Unicode) + * "symb" (Microsoft Symbol) + * "ADOB" (Adobe Standard) + * "ADBE" (Adobe Expert) + * "ADBC" (Adobe Custom) + * "armn" (Apple Roman) + * "sjis" (Shift JIS) + * "gb " (PRC) + * "big5" + * "wans" (Extended Wansung) + * "joha" (Johab) + * "lat1" (Latin-1) + + This specifies the character set to use. It does not alter the + encoding of any text provided in subsequent operations. + :param layout_engine: Which layout engine to use, if available: + :attr:`.ImageFont.Layout.BASIC` or :attr:`.ImageFont.Layout.RAQM`. + If it is available, Raqm layout will be used by default. + Otherwise, basic layout will be used. + + Raqm layout is recommended for all non-English text. If Raqm layout + is not required, basic layout will have better performance. + + You can check support for Raqm layout using + :py:func:`PIL.features.check_feature` with ``feature="raqm"``. + + .. versionadded:: 4.2.0 + :return: A font object. + :exception OSError: If the file could not be read. + :exception ValueError: If the font size is not greater than zero. + """ + + def freetype(font: StrOrBytesPath | BinaryIO) -> FreeTypeFont: + return FreeTypeFont(font, size, index, encoding, layout_engine) + + try: + return freetype(font) + except OSError: + if not is_path(font): + raise + ttf_filename = os.path.basename(font) + + dirs = [] + if sys.platform == "win32": + # check the windows font repository + # NOTE: must use uppercase WINDIR, to work around bugs in + # 1.5.2's os.environ.get() + windir = os.environ.get("WINDIR") + if windir: + dirs.append(os.path.join(windir, "fonts")) + elif sys.platform in ("linux", "linux2"): + data_home = os.environ.get("XDG_DATA_HOME") + if not data_home: + # The freedesktop spec defines the following default directory for + # when XDG_DATA_HOME is unset or empty. This user-level directory + # takes precedence over system-level directories. + data_home = os.path.expanduser("~/.local/share") + xdg_dirs = [data_home] + + data_dirs = os.environ.get("XDG_DATA_DIRS") + if not data_dirs: + # Similarly, defaults are defined for the system-level directories + data_dirs = "/usr/local/share:/usr/share" + xdg_dirs += data_dirs.split(":") + + dirs += [os.path.join(xdg_dir, "fonts") for xdg_dir in xdg_dirs] + elif sys.platform == "darwin": + dirs += [ + "/Library/Fonts", + "/System/Library/Fonts", + os.path.expanduser("~/Library/Fonts"), + ] + + ext = os.path.splitext(ttf_filename)[1] + first_font_with_a_different_extension = None + for directory in dirs: + for walkroot, walkdir, walkfilenames in os.walk(directory): + for walkfilename in walkfilenames: + if ext and walkfilename == ttf_filename: + return freetype(os.path.join(walkroot, walkfilename)) + elif not ext and os.path.splitext(walkfilename)[0] == ttf_filename: + fontpath = os.path.join(walkroot, walkfilename) + if os.path.splitext(fontpath)[1] == ".ttf": + return freetype(fontpath) + if not ext and first_font_with_a_different_extension is None: + first_font_with_a_different_extension = fontpath + if first_font_with_a_different_extension: + return freetype(first_font_with_a_different_extension) + raise + + +def load_path(filename: str | bytes) -> ImageFont: + """ + Load font file. Same as :py:func:`~PIL.ImageFont.load`, but searches for a + bitmap font along the Python path. + + :param filename: Name of font file. + :return: A font object. + :exception OSError: If the file could not be read. + """ + if not isinstance(filename, str): + filename = filename.decode("utf-8") + for directory in sys.path: + try: + return load(os.path.join(directory, filename)) + except OSError: # noqa: PERF203 + pass + msg = f'cannot find font file "{filename}" in sys.path' + if os.path.exists(filename): + msg += f', did you mean ImageFont.load("{filename}") instead?' + + raise OSError(msg) + + +def load_default_imagefont() -> ImageFont: + f = ImageFont() + f._load_pilfont_data( + # courB08 + BytesIO(base64.b64decode(b""" +UElMZm9udAo7Ozs7OzsxMDsKREFUQQoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAAA//8AAQAAAAAAAAABAAEA +BgAAAAH/+gADAAAAAQAAAAMABgAGAAAAAf/6AAT//QADAAAABgADAAYAAAAA//kABQABAAYAAAAL +AAgABgAAAAD/+AAFAAEACwAAABAACQAGAAAAAP/5AAUAAAAQAAAAFQAHAAYAAP////oABQAAABUA +AAAbAAYABgAAAAH/+QAE//wAGwAAAB4AAwAGAAAAAf/5AAQAAQAeAAAAIQAIAAYAAAAB//kABAAB +ACEAAAAkAAgABgAAAAD/+QAE//0AJAAAACgABAAGAAAAAP/6AAX//wAoAAAALQAFAAYAAAAB//8A +BAACAC0AAAAwAAMABgAAAAD//AAF//0AMAAAADUAAQAGAAAAAf//AAMAAAA1AAAANwABAAYAAAAB +//kABQABADcAAAA7AAgABgAAAAD/+QAFAAAAOwAAAEAABwAGAAAAAP/5AAYAAABAAAAARgAHAAYA +AAAA//kABQAAAEYAAABLAAcABgAAAAD/+QAFAAAASwAAAFAABwAGAAAAAP/5AAYAAABQAAAAVgAH +AAYAAAAA//kABQAAAFYAAABbAAcABgAAAAD/+QAFAAAAWwAAAGAABwAGAAAAAP/5AAUAAABgAAAA +ZQAHAAYAAAAA//kABQAAAGUAAABqAAcABgAAAAD/+QAFAAAAagAAAG8ABwAGAAAAAf/8AAMAAABv +AAAAcQAEAAYAAAAA//wAAwACAHEAAAB0AAYABgAAAAD/+gAE//8AdAAAAHgABQAGAAAAAP/7AAT/ +/gB4AAAAfAADAAYAAAAB//oABf//AHwAAACAAAUABgAAAAD/+gAFAAAAgAAAAIUABgAGAAAAAP/5 +AAYAAQCFAAAAiwAIAAYAAP////oABgAAAIsAAACSAAYABgAA////+gAFAAAAkgAAAJgABgAGAAAA +AP/6AAUAAACYAAAAnQAGAAYAAP////oABQAAAJ0AAACjAAYABgAA////+gAFAAAAowAAAKkABgAG +AAD////6AAUAAACpAAAArwAGAAYAAAAA//oABQAAAK8AAAC0AAYABgAA////+gAGAAAAtAAAALsA +BgAGAAAAAP/6AAQAAAC7AAAAvwAGAAYAAP////oABQAAAL8AAADFAAYABgAA////+gAGAAAAxQAA +AMwABgAGAAD////6AAUAAADMAAAA0gAGAAYAAP////oABQAAANIAAADYAAYABgAA////+gAGAAAA +2AAAAN8ABgAGAAAAAP/6AAUAAADfAAAA5AAGAAYAAP////oABQAAAOQAAADqAAYABgAAAAD/+gAF +AAEA6gAAAO8ABwAGAAD////6AAYAAADvAAAA9gAGAAYAAAAA//oABQAAAPYAAAD7AAYABgAA//// ++gAFAAAA+wAAAQEABgAGAAD////6AAYAAAEBAAABCAAGAAYAAP////oABgAAAQgAAAEPAAYABgAA +////+gAGAAABDwAAARYABgAGAAAAAP/6AAYAAAEWAAABHAAGAAYAAP////oABgAAARwAAAEjAAYA +BgAAAAD/+gAFAAABIwAAASgABgAGAAAAAf/5AAQAAQEoAAABKwAIAAYAAAAA//kABAABASsAAAEv +AAgABgAAAAH/+QAEAAEBLwAAATIACAAGAAAAAP/5AAX//AEyAAABNwADAAYAAAAAAAEABgACATcA +AAE9AAEABgAAAAH/+QAE//wBPQAAAUAAAwAGAAAAAP/7AAYAAAFAAAABRgAFAAYAAP////kABQAA +AUYAAAFMAAcABgAAAAD/+wAFAAABTAAAAVEABQAGAAAAAP/5AAYAAAFRAAABVwAHAAYAAAAA//sA +BQAAAVcAAAFcAAUABgAAAAD/+QAFAAABXAAAAWEABwAGAAAAAP/7AAYAAgFhAAABZwAHAAYAAP// +//kABQAAAWcAAAFtAAcABgAAAAD/+QAGAAABbQAAAXMABwAGAAAAAP/5AAQAAgFzAAABdwAJAAYA +AP////kABgAAAXcAAAF+AAcABgAAAAD/+QAGAAABfgAAAYQABwAGAAD////7AAUAAAGEAAABigAF +AAYAAP////sABQAAAYoAAAGQAAUABgAAAAD/+wAFAAABkAAAAZUABQAGAAD////7AAUAAgGVAAAB +mwAHAAYAAAAA//sABgACAZsAAAGhAAcABgAAAAD/+wAGAAABoQAAAacABQAGAAAAAP/7AAYAAAGn +AAABrQAFAAYAAAAA//kABgAAAa0AAAGzAAcABgAA////+wAGAAABswAAAboABQAGAAD////7AAUA +AAG6AAABwAAFAAYAAP////sABgAAAcAAAAHHAAUABgAAAAD/+wAGAAABxwAAAc0ABQAGAAD////7 +AAYAAgHNAAAB1AAHAAYAAAAA//sABQAAAdQAAAHZAAUABgAAAAH/+QAFAAEB2QAAAd0ACAAGAAAA +Av/6AAMAAQHdAAAB3gAHAAYAAAAA//kABAABAd4AAAHiAAgABgAAAAD/+wAF//0B4gAAAecAAgAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAAB +//sAAwACAecAAAHpAAcABgAAAAD/+QAFAAEB6QAAAe4ACAAGAAAAAP/5AAYAAAHuAAAB9AAHAAYA +AAAA//oABf//AfQAAAH5AAUABgAAAAD/+QAGAAAB+QAAAf8ABwAGAAAAAv/5AAMAAgH/AAACAAAJ +AAYAAAAA//kABQABAgAAAAIFAAgABgAAAAH/+gAE//sCBQAAAggAAQAGAAAAAP/5AAYAAAIIAAAC +DgAHAAYAAAAB//kABf/+Ag4AAAISAAUABgAA////+wAGAAACEgAAAhkABQAGAAAAAP/7AAX//gIZ +AAACHgADAAYAAAAA//wABf/9Ah4AAAIjAAEABgAAAAD/+QAHAAACIwAAAioABwAGAAAAAP/6AAT/ ++wIqAAACLgABAAYAAAAA//kABP/8Ai4AAAIyAAMABgAAAAD/+gAFAAACMgAAAjcABgAGAAAAAf/5 +AAT//QI3AAACOgAEAAYAAAAB//kABP/9AjoAAAI9AAQABgAAAAL/+QAE//sCPQAAAj8AAgAGAAD/ +///7AAYAAgI/AAACRgAHAAYAAAAA//kABgABAkYAAAJMAAgABgAAAAH//AAD//0CTAAAAk4AAQAG +AAAAAf//AAQAAgJOAAACUQADAAYAAAAB//kABP/9AlEAAAJUAAQABgAAAAH/+QAF//4CVAAAAlgA +BQAGAAD////7AAYAAAJYAAACXwAFAAYAAP////kABgAAAl8AAAJmAAcABgAA////+QAGAAACZgAA +Am0ABwAGAAD////5AAYAAAJtAAACdAAHAAYAAAAA//sABQACAnQAAAJ5AAcABgAA////9wAGAAAC +eQAAAoAACQAGAAD////3AAYAAAKAAAAChwAJAAYAAP////cABgAAAocAAAKOAAkABgAA////9wAG +AAACjgAAApUACQAGAAD////4AAYAAAKVAAACnAAIAAYAAP////cABgAAApwAAAKjAAkABgAA//// ++gAGAAACowAAAqoABgAGAAAAAP/6AAUAAgKqAAACrwAIAAYAAP////cABQAAAq8AAAK1AAkABgAA +////9wAFAAACtQAAArsACQAGAAD////3AAUAAAK7AAACwQAJAAYAAP////gABQAAAsEAAALHAAgA +BgAAAAD/9wAEAAACxwAAAssACQAGAAAAAP/3AAQAAALLAAACzwAJAAYAAAAA//cABAAAAs8AAALT +AAkABgAAAAD/+AAEAAAC0wAAAtcACAAGAAD////6AAUAAALXAAAC3QAGAAYAAP////cABgAAAt0A +AALkAAkABgAAAAD/9wAFAAAC5AAAAukACQAGAAAAAP/3AAUAAALpAAAC7gAJAAYAAAAA//cABQAA +Au4AAALzAAkABgAAAAD/9wAFAAAC8wAAAvgACQAGAAAAAP/4AAUAAAL4AAAC/QAIAAYAAAAA//oA +Bf//Av0AAAMCAAUABgAA////+gAGAAADAgAAAwkABgAGAAD////3AAYAAAMJAAADEAAJAAYAAP// +//cABgAAAxAAAAMXAAkABgAA////9wAGAAADFwAAAx4ACQAGAAD////4AAYAAAAAAAoABwASAAYA +AP////cABgAAAAcACgAOABMABgAA////+gAFAAAADgAKABQAEAAGAAD////6AAYAAAAUAAoAGwAQ +AAYAAAAA//gABgAAABsACgAhABIABgAAAAD/+AAGAAAAIQAKACcAEgAGAAAAAP/4AAYAAAAnAAoA +LQASAAYAAAAA//gABgAAAC0ACgAzABIABgAAAAD/+QAGAAAAMwAKADkAEQAGAAAAAP/3AAYAAAA5 +AAoAPwATAAYAAP////sABQAAAD8ACgBFAA8ABgAAAAD/+wAFAAIARQAKAEoAEQAGAAAAAP/4AAUA +AABKAAoATwASAAYAAAAA//gABQAAAE8ACgBUABIABgAAAAD/+AAFAAAAVAAKAFkAEgAGAAAAAP/5 +AAUAAABZAAoAXgARAAYAAAAA//gABgAAAF4ACgBkABIABgAAAAD/+AAGAAAAZAAKAGoAEgAGAAAA +AP/4AAYAAABqAAoAcAASAAYAAAAA//kABgAAAHAACgB2ABEABgAAAAD/+AAFAAAAdgAKAHsAEgAG +AAD////4AAYAAAB7AAoAggASAAYAAAAA//gABQAAAIIACgCHABIABgAAAAD/+AAFAAAAhwAKAIwA +EgAGAAAAAP/4AAUAAACMAAoAkQASAAYAAAAA//gABQAAAJEACgCWABIABgAAAAD/+QAFAAAAlgAK +AJsAEQAGAAAAAP/6AAX//wCbAAoAoAAPAAYAAAAA//oABQABAKAACgClABEABgAA////+AAGAAAA +pQAKAKwAEgAGAAD////4AAYAAACsAAoAswASAAYAAP////gABgAAALMACgC6ABIABgAA////+QAG +AAAAugAKAMEAEQAGAAD////4AAYAAgDBAAoAyAAUAAYAAP////kABQACAMgACgDOABMABgAA//// ++QAGAAIAzgAKANUAEw== +""")), + Image.open(BytesIO(base64.b64decode(b""" +iVBORw0KGgoAAAANSUhEUgAAAx4AAAAUAQAAAAArMtZoAAAEwElEQVR4nABlAJr/AHVE4czCI/4u +Mc4b7vuds/xzjz5/3/7u/n9vMe7vnfH/9++vPn/xyf5zhxzjt8GHw8+2d83u8x27199/nxuQ6Od9 +M43/5z2I+9n9ZtmDBwMQECDRQw/eQIQohJXxpBCNVE6QCCAAAAD//wBlAJr/AgALyj1t/wINwq0g +LeNZUworuN1cjTPIzrTX6ofHWeo3v336qPzfEwRmBnHTtf95/fglZK5N0PDgfRTslpGBvz7LFc4F +IUXBWQGjQ5MGCx34EDFPwXiY4YbYxavpnhHFrk14CDAAAAD//wBlAJr/AgKqRooH2gAgPeggvUAA +Bu2WfgPoAwzRAABAAAAAAACQgLz/3Uv4Gv+gX7BJgDeeGP6AAAD1NMDzKHD7ANWr3loYbxsAD791 +NAADfcoIDyP44K/jv4Y63/Z+t98Ovt+ub4T48LAAAAD//wBlAJr/AuplMlADJAAAAGuAphWpqhMx +in0A/fRvAYBABPgBwBUgABBQ/sYAyv9g0bCHgOLoGAAAAAAAREAAwI7nr0ArYpow7aX8//9LaP/9 +SjdavWA8ePHeBIKB//81/83ndznOaXx379wAAAD//wBlAJr/AqDxW+D3AABAAbUh/QMnbQag/gAY +AYDAAACgtgD/gOqAAAB5IA/8AAAk+n9w0AAA8AAAmFRJuPo27ciC0cD5oeW4E7KA/wD3ECMAn2tt +y8PgwH8AfAxFzC0JzeAMtratAsC/ffwAAAD//wBlAJr/BGKAyCAA4AAAAvgeYTAwHd1kmQF5chkG +ABoMIHcL5xVpTfQbUqzlAAAErwAQBgAAEOClA5D9il08AEh/tUzdCBsXkbgACED+woQg8Si9VeqY +lODCn7lmF6NhnAEYgAAA/NMIAAAAAAD//2JgjLZgVGBg5Pv/Tvpc8hwGBjYGJADjHDrAwPzAjv/H +/Wf3PzCwtzcwHmBgYGcwbZz8wHaCAQMDOwMDQ8MCBgYOC3W7mp+f0w+wHOYxO3OG+e376hsMZjk3 +AAAAAP//YmCMY2A4wMAIN5e5gQETPD6AZisDAwMDgzSDAAPjByiHcQMDAwMDg1nOze1lByRu5/47 +c4859311AYNZzg0AAAAA//9iYGDBYihOIIMuwIjGL39/fwffA8b//xv/P2BPtzzHwCBjUQAAAAD/ +/yLFBrIBAAAA//9i1HhcwdhizX7u8NZNzyLbvT97bfrMf/QHI8evOwcSqGUJAAAA//9iYBB81iSw +pEE170Qrg5MIYydHqwdDQRMrAwcVrQAAAAD//2J4x7j9AAMDn8Q/BgYLBoaiAwwMjPdvMDBYM1Tv +oJodAAAAAP//Yqo/83+dxePWlxl3npsel9lvLfPcqlE9725C+acfVLMEAAAA//9i+s9gwCoaaGMR +evta/58PTEWzr21hufPjA8N+qlnBwAAAAAD//2JiWLci5v1+HmFXDqcnULE/MxgYGBj+f6CaJQAA +AAD//2Ji2FrkY3iYpYC5qDeGgeEMAwPDvwQBBoYvcTwOVLMEAAAA//9isDBgkP///0EOg9z35v// +Gc/eeW7BwPj5+QGZhANUswMAAAD//2JgqGBgYGBgqEMXlvhMPUsAAAAA//8iYDd1AAAAAP//AwDR +w7IkEbzhVQAAAABJRU5ErkJggg== +"""))), + ) + return f + + +def load_default(size: float | None = None) -> FreeTypeFont | ImageFont: + """If FreeType support is available, load a version of Aileron Regular, + https://dotcolon.net/fonts/aileron, with a more limited character set. + + Otherwise, load a "better than nothing" font. + + .. versionadded:: 1.1.4 + + :param size: The font size of Aileron Regular. + + .. versionadded:: 10.1.0 + + :return: A font object. + """ + if isinstance(core, ModuleType) or size is not None: + return truetype( + BytesIO(base64.b64decode(b""" +AAEAAAAPAIAAAwBwRkZUTYwDlUAAADFoAAAAHEdERUYAqADnAAAo8AAAACRHUE9ThhmITwAAKfgAA +AduR1NVQnHxefoAACkUAAAA4k9TLzJovoHLAAABeAAAAGBjbWFw5lFQMQAAA6gAAAGqZ2FzcP//AA +MAACjoAAAACGdseWYmRXoPAAAGQAAAHfhoZWFkE18ayQAAAPwAAAA2aGhlYQboArEAAAE0AAAAJGh +tdHjjERZ8AAAB2AAAAdBsb2NhuOexrgAABVQAAADqbWF4cAC7AEYAAAFYAAAAIG5hbWUr+h5lAAAk +OAAAA6Jwb3N0D3oPTQAAJ9wAAAEKAAEAAAABGhxJDqIhXw889QALA+gAAAAA0Bqf2QAAAADhCh2h/ +2r/LgOxAyAAAAAIAAIAAAAAAAAAAQAAA8r/GgAAA7j/av9qA7EAAQAAAAAAAAAAAAAAAAAAAHQAAQ +AAAHQAQwAFAAAAAAACAAAAAQABAAAAQAAAAAAAAAADAfoBkAAFAAgCigJYAAAASwKKAlgAAAFeADI +BPgAAAAAFAAAAAAAAAAAAAAcAAAAAAAAAAAAAAABVS1dOAEAAIPsCAwL/GgDIA8oA5iAAAJMAAAAA +AhICsgAAACAAAwH0AAAAAAAAAU0AAADYAAAA8gA5AVMAVgJEAEYCRAA1AuQAKQKOAEAAsAArATsAZ +AE7AB4CMABVAkQAUADc/+EBEgAgANwAJQEv//sCRAApAkQAggJEADwCRAAtAkQAIQJEADkCRAArAk +QAMgJEACwCRAAxANwAJQDc/+ECRABnAkQAUAJEAEQB8wAjA1QANgJ/AB0CcwBkArsALwLFAGQCSwB +kAjcAZALGAC8C2gBkAQgAZAIgADcCYQBkAj8AZANiAGQCzgBkAuEALwJWAGQC3QAvAmsAZAJJADQC +ZAAiAqoAXgJuACADuAAaAnEAGQJFABMCTwAuATMAYgEv//sBJwAiAkQAUAH0ADIBLAApAhMAJAJjA +EoCEQAeAmcAHgIlAB4BIgAVAmcAHgJRAEoA7gA+AOn/8wIKAEoA9wBGA1cASgJRAEoCSgAeAmMASg +JnAB4BSgBKAcsAGAE5ABQCUABCAgIAAQMRAAEB4v/6AgEAAQHOABQBLwBAAPoAYAEvACECRABNA0Y +AJAItAHgBKgAcAkQAUAEsAHQAygAgAi0AOQD3ADYA9wAWAaEANgGhABYCbAAlAYMAeAGDADkA6/9q +AhsAFAIKABUB/QAVAAAAAwAAAAMAAAAcAAEAAAAAAKQAAwABAAAAHAAEAIgAAAAeABAAAwAOAH4Aq +QCrALEAtAC3ALsgGSAdICYgOiBEISL7Av//AAAAIACpAKsAsAC0ALcAuyAYIBwgJiA5IEQhIvsB// +//4/+5/7j/tP+y/7D/reBR4E/gR+A14CzfTwVxAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAEGAAABAAAAAAAAAAECAAAAAgAAAAAAAAAAAAAAAAAAAAEAAAMEBQYHCAkKCwwNDg8QERIT +FBUWFxgZGhscHR4fICEiIyQlJicoKSorLC0uLzAxMjM0NTY3ODk6Ozw9Pj9AQUJDREVGR0hJSktMT +U5PUFFSU1RVVldYWVpbXF1eX2BhAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGQAAA +AAAAAAYnFmAAAAAABlAAAAAAAAAAAAAAAAAAAAAAAAAAAAY2htAAAAAAAAAABrbGlqAAAAAHAAbm9 +ycwBnAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAmACYAJgAmAD4AUgCCAMoBCgFO +AVwBcgGIAaYBvAHKAdYB6AH2AgwCIAJKAogCpgLWAw4DIgNkA5wDugPUA+gD/AQQBEYEogS8BPoFJ +gVSBWoFgAWwBcoF1gX6BhQGJAZMBmgGiga0BuIHGgdUB2YHkAeiB8AH3AfyCAoIHAgqCDoITghcCG +oIogjSCPoJKglYCXwJwgnqCgIKKApACl4Klgq8CtwLDAs8C1YLjAuyC9oL7gwMDCYMSAxgDKAMrAz +qDQoNTA1mDYQNoA2uDcAN2g3oDfYODA4iDkoOXA5sDnoOnA7EDvwAAAAFAAAAAAH0ArwAAwAGAAkA +DAAPAAAxESERAxMhExcRASELARETAfT6qv6syKr+jgFUqsiqArz9RAGLAP/+1P8B/v3VAP8BLP4CA +P8AAgA5//IAuQKyAAMACwAANyMDMwIyFhQGIiY0oE4MZk84JCQ4JLQB/v3AJDgkJDgAAgBWAeUBPA +LfAAMABwAAEyMnMxcjJzOmRgpagkYKWgHl+vr6AAAAAAIARgAAAf4CsgAbAB8AAAEHMxUjByM3Iwc +jNyM1MzcjNTM3MwczNzMHMxUrAQczAZgdZXEvOi9bLzovWmYdZXEvOi9bLzovWp9bHlsBn4w429vb +2ziMONvb29s4jAAAAAMANf+mAg4DDAAfACYALAAAJRQGBxUjNS4BJzMeARcRLgE0Njc1MxUeARcjJ +icVHgEBFBYXNQ4BExU+ATU0Ag5xWDpgcgRcBz41Xl9oVTpVYwpcC1ttXP6cLTQuM5szOrVRZwlOTQ +ZqVzZECAEAGlukZAlOTQdrUG8O7iNlAQgxNhDlCDj+8/YGOjReAAAAAAUAKf/yArsCvAAHAAsAFQA +dACcAABIyFhQGIiY0EyMBMwQiBhUUFjI2NTQSMhYUBiImNDYiBhUUFjI2NTR5iFBQiFCVVwHAV/5c +OiMjOiPmiFBQiFCxOiMjOiMCvFaSVlaS/ZoCsjIzMC80NC8w/uNWklZWkhozMC80NC8wAAAAAgBA/ +/ICbgLAACIALgAAARUjEQYjIiY1NDY3LgE1NDYzMhcVJiMiBhUUFhcWOwE1MxUFFBYzMjc1IyIHDg +ECbmBcYYOOVkg7R4hsQjY4Q0RNRD4SLDxW/pJUXzksPCkUUk0BgUb+zBVUZ0BkDw5RO1huCkULQzp +COAMBcHDHRz0J/AIHRQAAAAEAKwHlAIUC3wADAAATIycze0YKWgHl+gAAAAABAGT/sAEXAwwACQAA +EzMGEBcjLgE0Nt06dXU6OUBAAwzG/jDGVePs4wAAAAEAHv+wANEDDAAJAAATMx4BFAYHIzYQHjo5Q +EA5OnUDDFXj7ONVxgHQAAAAAQBVAFIB2wHbAA4AAAE3FwcXBycHJzcnNxcnMwEtmxOfcTJjYzJxnx +ObCj4BKD07KYolmZkliik7PbMAAQBQAFUB9AIlAAsAAAEjFSM1IzUzNTMVMwH0tTq1tTq1AR/Kyjj +OzgAAAAAB/+H/iACMAGQABAAANwcjNzOMWlFOXVrS3AAAAQAgAP8A8gE3AAMAABMjNTPy0tIA/zgA +AQAl//IApQByAAcAADYyFhQGIiY0STgkJDgkciQ4JCQ4AAAAAf/7/+IBNALQAAMAABcjEzM5Pvs+H +gLuAAAAAAIAKf/yAhsCwAADAAcAABIgECA2IBAgKQHy/g5gATL+zgLA/TJEAkYAAAAAAQCCAAABlg +KyAAgAAAERIxEHNTc2MwGWVr6SIygCsv1OAldxW1sWAAEAPAAAAg4CwAAZAAA3IRUhNRM+ATU0JiM +iDwEjNz4BMzIWFRQGB7kBUv4x+kI2QTt+EAFWAQp8aGVtSl5GRjEA/0RVLzlLmAoKa3FsUkNxXQAA +AAEALf/yAhYCwAAqAAABHgEVFAYjIi8BMxceATMyNjU0KwE1MzI2NTQmIyIGDwEjNz4BMzIWFRQGA +YxBSZJo2RUBVgEHV0JBUaQREUBUQzc5TQcBVgEKfGhfcEMBbxJbQl1x0AoKRkZHPn9GSD80QUVCCg +pfbGBPOlgAAAACACEAAAIkArIACgAPAAAlIxUjNSE1ATMRMyMRBg8BAiRXVv6qAVZWV60dHLCurq4 +rAdn+QgFLMibzAAABADn/8gIZArIAHQAAATIWFRQGIyIvATMXFjMyNjU0JiMiByMTIRUhBzc2ATNv +d5Fl1RQBVgIad0VSTkVhL1IwAYj+vh8rMAHHgGdtgcUKCoFXTU5bYgGRRvAuHQAAAAACACv/8gITA +sAAFwAjAAABMhYVFAYjIhE0NjMyFh8BIycmIyIDNzYTMjY1NCYjIgYVFBYBLmp7imr0l3RZdAgBXA +IYZ5wKJzU6QVNJSz5SUAHSgWltiQFGxcNlVQoKdv7sPiz+ZF1LTmJbU0lhAAAAAQAyAAACGgKyAAY +AAAEVASMBITUCGv6oXAFL/oECsij9dgJsRgAAAAMALP/xAhgCwAAWACAALAAAAR4BFRQGIyImNTQ2 +Ny4BNTQ2MhYVFAYmIgYVFBYyNjU0AzI2NTQmIyIGFRQWAZQ5S5BmbIpPOjA7ecp5P2F8Q0J8RIVJS +0pLTEtOAW0TXTxpZ2ZqPF0SE1A3VWVlVTdQ/UU0N0RENzT9/ko+Ok1NOj1LAAIAMf/yAhkCwAAXAC +MAAAEyERQGIyImLwEzFxYzMhMHBiMiJjU0NhMyNjU0JiMiBhUUFgEl9Jd0WXQIAVwCGGecCic1SWp +7imo+UlBAQVNJAsD+usXDZVUKCnYBFD4sgWltif5kW1NJYV1LTmIAAAACACX/8gClAiAABwAPAAAS +MhYUBiImNBIyFhQGIiY0STgkJDgkJDgkJDgkAiAkOCQkOP52JDgkJDgAAAAC/+H/iAClAiAABwAMA +AASMhYUBiImNBMHIzczSTgkJDgkaFpSTl4CICQ4JCQ4/mba5gAAAQBnAB4B+AH0AAYAAAENARUlNS +UB+P6qAVb+bwGRAbCmpkbJRMkAAAIAUAC7AfQBuwADAAcAAAEhNSERITUhAfT+XAGk/lwBpAGDOP8 +AOAABAEQAHgHVAfQABgAAARUFNS0BNQHV/m8BVv6qAStEyUSmpkYAAAAAAgAj//IB1ALAABgAIAAA +ATIWFRQHDgEHIz4BNz4BNTQmIyIGByM+ARIyFhQGIiY0AQRibmktIAJWBSEqNig+NTlHBFoDezQ4J +CQ4JALAZ1BjaS03JS1DMD5LLDQ/SUVgcv2yJDgkJDgAAAAAAgA2/5gDFgKYADYAQgAAAQMGFRQzMj +Y1NCYjIg4CFRQWMzI2NxcGIyImNTQ+AjMyFhUUBiMiJwcGIyImNTQ2MzIfATcHNzYmIyIGFRQzMjY +Cej8EJjJJlnBAfGQ+oHtAhjUYg5OPx0h2k06Os3xRWQsVLjY5VHtdPBwJETcJDyUoOkZEJz8B0f74 +EQ8kZl6EkTFZjVOLlyknMVm1pmCiaTq4lX6CSCknTVRmmR8wPdYnQzxuSWVGAAIAHQAAAncCsgAHA +AoAACUjByMTMxMjATMDAcj+UVz4dO5d/sjPZPT0ArL9TgE6ATQAAAADAGQAAAJMArIAEAAbACcAAA +EeARUUBgcGKwERMzIXFhUUJRUzMjc2NTQnJiMTPgE1NCcmKwEVMzIBvkdHZkwiNt7LOSGq/oeFHBt +hahIlSTM+cB8Yj5UWAW8QT0VYYgwFArIEF5Fv1eMED2NfDAL93AU+N24PBP0AAAAAAQAv//ICjwLA +ABsAAAEyFh8BIycmIyIGFRQWMzI/ATMHDgEjIiY1NDYBdX+PCwFWAiKiaHx5ZaIiAlYBCpWBk6a0A +sCAagoKpqN/gaOmCgplhcicn8sAAAIAZAAAAp8CsgAMABkAAAEeARUUBgcGKwERMzITPgE1NCYnJi +sBETMyAY59lJp8IzXN0jUVWmdjWRs5d3I4Aq4QqJWUug8EArL9mQ+PeHGHDgX92gAAAAABAGQAAAI +vArIACwAAJRUhESEVIRUhFSEVAi/+NQHB/pUBTf6zRkYCskbwRvAAAAABAGQAAAIlArIACQAAExUh +FSERIxEhFboBQ/69VgHBAmzwRv7KArJGAAAAAAEAL//yAo8CwAAfAAABMxEjNQcGIyImNTQ2MzIWH +wEjJyYjIgYVFBYzMjY1IwGP90wfPnWTprSSf48LAVYCIqJofHllVG+hAU3+s3hARsicn8uAagoKpq +N/gaN1XAAAAAEAZAAAAowCsgALAAABESMRIREjETMRIRECjFb+hFZWAXwCsv1OAS7+0gKy/sQBPAA +AAAABAGQAAAC6ArIAAwAAMyMRM7pWVgKyAAABADf/8gHoArIAEwAAAREUBw4BIyImLwEzFxYzMjc2 +NREB6AIFcGpgbQIBVgIHfXQKAQKy/lYxIltob2EpKYyEFD0BpwAAAAABAGQAAAJ0ArIACwAACQEjA +wcVIxEzEQEzATsBJ3ntQlZWAVVlAWH+nwEnR+ACsv6RAW8AAQBkAAACLwKyAAUAACUVIREzEQIv/j +VWRkYCsv2UAAABAGQAAAMUArIAFAAAAREjETQ3BgcDIwMmJxYVESMRMxsBAxRWAiMxemx8NxsCVo7 +MywKy/U4BY7ZLco7+nAFmoFxLtP6dArL9lwJpAAAAAAEAZAAAAoACsgANAAAhIwEWFREjETMBJjUR +MwKAhP67A1aEAUUDVAJeeov+pwKy/aJ5jAFZAAAAAgAv//ICuwLAAAkAEwAAEiAWFRQGICY1NBIyN +jU0JiIGFRTbATSsrP7MrNrYenrYegLAxaKhxsahov47nIeIm5uIhwACAGQAAAJHArIADgAYAAABHg +EVFAYHBisBESMRMzITNjQnJisBETMyAZRUX2VOHzuAVtY7GlxcGDWIiDUCrgtnVlVpCgT+5gKy/rU +V1BUF/vgAAAACAC//zAK9AsAAEgAcAAAlFhcHJiMiBwYjIiY1NDYgFhUUJRQWMjY1NCYiBgI9PUMx +UDcfKh8omqysATSs/dR62Hp62HpICTg7NgkHxqGixcWitbWHnJyHiJubAAIAZAAAAlgCsgAXACMAA +CUWFyMmJyYnJisBESMRMzIXHgEVFAYHFiUzMjc+ATU0JyYrAQIqDCJfGQwNWhAhglbiOx9QXEY1Tv +6bhDATMj1lGSyMtYgtOXR0BwH+1wKyBApbU0BSESRAAgVAOGoQBAABADT/8gIoAsAAJQAAATIWFyM +uASMiBhUUFhceARUUBiMiJiczHgEzMjY1NCYnLgE1NDYBOmd2ClwGS0E6SUNRdW+HZnKKC1wPWkQ9 +Uk1cZGuEAsBwXUJHNjQ3OhIbZVZZbm5kREo+NT5DFRdYUFdrAAAAAAEAIgAAAmQCsgAHAAABIxEjE +SM1IQJk9lb2AkICbP2UAmxGAAEAXv/yAmQCsgAXAAABERQHDgEiJicmNREzERQXHgEyNjc2NRECZA +IIgfCBCAJWAgZYmlgGAgKy/k0qFFxzc1wUKgGz/lUrEkRQUEQSKwGrAAAAAAEAIAAAAnoCsgAGAAA +hIwMzGwEzAYJ07l3N1FwCsv2PAnEAAAEAGgAAA7ECsgAMAAABAyMLASMDMxsBMxsBA7HAcZyicrZi +kaB0nJkCsv1OAlP9rQKy/ZsCW/2kAmYAAAEAGQAAAm8CsgALAAAhCwEjEwMzGwEzAxMCCsrEY/bkY +re+Y/D6AST+3AFcAVb+5gEa/q3+oQAAAQATAAACUQKyAAgAAAERIxEDMxsBMwFdVvRjwLphARD+8A +EQAaL+sQFPAAABAC4AAAI5ArIACQAAJRUhNQEhNSEVAQI5/fUBof57Aen+YUZGQgIqRkX92QAAAAA +BAGL/sAEFAwwABwAAARUjETMVIxEBBWlpowMMOP0UOANcAAAB//v/4gE0AtAAAwAABSMDMwE0Pvs+ +HgLuAAAAAQAi/7AAxQMMAAcAABcjNTMRIzUzxaNpaaNQOALsOAABAFAA1wH0AmgABgAAJQsBIxMzE +wGwjY1GsESw1wFZ/qcBkf5vAAAAAQAy/6oBwv/iAAMAAAUhNSEBwv5wAZBWOAAAAAEAKQJEALYCsg +ADAAATIycztjhVUAJEbgAAAAACACT/8gHQAiAAHQAlAAAhJwcGIyImNTQ2OwE1NCcmIyIHIz4BMzI +XFh0BFBcnMjY9ASYVFAF6CR0wVUtgkJoiAgdgaQlaBm1Zrg4DCuQ9R+5MOSFQR1tbDiwUUXBUXowf +J8c9SjRORzYSgVwAAAAAAgBK//ICRQLfABEAHgAAATIWFRQGIyImLwEVIxEzETc2EzI2NTQmIyIGH +QEUFgFUcYCVbiNJEyNWVigySElcU01JXmECIJd4i5QTEDRJAt/+3jkq/hRuZV55ZWsdX14AAQAe// +IB9wIgABgAAAEyFhcjJiMiBhUUFjMyNjczDgEjIiY1NDYBF152DFocbEJXU0A1Rw1aE3pbaoKQAiB +oWH5qZm1tPDlaXYuLgZcAAAACAB7/8gIZAt8AEQAeAAABESM1BwYjIiY1NDYzMhYfAREDMjY9ATQm +IyIGFRQWAhlWKDJacYCVbiNJEyOnSV5hQUlcUwLf/SFVOSqXeIuUExA0ARb9VWVrHV9ebmVeeQACA +B7/8gH9AiAAFQAbAAABFAchHgEzMjY3Mw4BIyImNTQ2MzIWJyIGByEmAf0C/oAGUkA1SwlaD4FXbI +WObmt45UBVBwEqDQEYFhNjWD84W16Oh3+akU9aU60AAAEAFQAAARoC8gAWAAATBh0BMxUjESMRIzU +zNTQ3PgEzMhcVJqcDbW1WOTkDB0k8Hx5oAngVITRC/jQBzEIsJRs5PwVHEwAAAAIAHv8uAhkCIAAi +AC8AAAERFAcOASMiLwEzFx4BMzI2NzY9AQcGIyImNTQ2MzIWHwE1AzI2PQE0JiMiBhUUFgIZAQSEd +NwRAVcBBU5DTlUDASgyWnGAlW4jSRMjp0leYUFJXFMCEv5wSh1zeq8KCTI8VU0ZIQk5Kpd4i5QTED +RJ/iJlax1fXm5lXnkAAQBKAAACCgLkABcAAAEWFREjETQnLgEHDgEdASMRMxE3NjMyFgIIAlYCBDs +6RVRWViE5UVViAYUbQP7WASQxGzI7AQJyf+kC5P7TPSxUAAACAD4AAACsAsAABwALAAASMhYUBiIm +NBMjETNeLiAgLiBiVlYCwCAuICAu/WACEgAC//P/LgCnAsAABwAVAAASMhYUBiImNBcRFAcGIyInN +RY3NjURWS4gIC4gYgMLcRwNSgYCAsAgLiAgLo79wCUbZAJGBzMOHgJEAAAAAQBKAAACCALfAAsAAC +EnBxUjETMREzMHEwGTwTJWVvdu9/rgN6kC3/4oAQv6/ugAAQBG//wA3gLfAA8AABMRFBceATcVBiM +iJicmNRGcAQIcIxkkKi4CAQLf/bkhERoSBD4EJC8SNAJKAAAAAQBKAAADEAIgACQAAAEWFREjETQn +JiMiFREjETQnJiMiFREjETMVNzYzMhYXNzYzMhYDCwVWBAxedFYEDF50VlYiJko7ThAvJkpEVAGfI +jn+vAEcQyRZ1v76ARxDJFnW/voCEk08HzYtRB9HAAAAAAEASgAAAgoCIAAWAAABFhURIxE0JyYjIg +YdASMRMxU3NjMyFgIIAlYCCXBEVVZWITlRVWIBhRtA/tYBJDEbbHR/6QISWz0sVAAAAAACAB7/8gI +sAiAABwARAAASIBYUBiAmNBIyNjU0JiIGFRSlAQCHh/8Ah7ieWlqeWgIgn/Cfn/D+s3ZfYHV1YF8A +AgBK/zwCRQIgABEAHgAAATIWFRQGIyImLwERIxEzFTc2EzI2NTQmIyIGHQEUFgFUcYCVbiNJEyNWV +igySElcU01JXmECIJd4i5QTEDT+8wLWVTkq/hRuZV55ZWsdX14AAgAe/zwCGQIgABEAHgAAAREjEQ +cGIyImNTQ2MzIWHwE1AzI2PQE0JiMiBhUUFgIZVigyWnGAlW4jSRMjp0leYUFJXFMCEv0qARk5Kpd +4i5QTEDRJ/iJlax1fXm5lXnkAAQBKAAABPgIeAA0AAAEyFxUmBhURIxEzFTc2ARoWDkdXVlYwIwIe +B0EFVlf+0gISU0cYAAEAGP/yAa0CIAAjAAATMhYXIyYjIgYVFBYXHgEVFAYjIiYnMxYzMjY1NCYnL +gE1NDbkV2MJWhNdKy04PF1XbVhWbgxaE2ktOjlEUllkAiBaS2MrJCUoEBlPQkhOVFZoKCUmLhIWSE +BIUwAAAAEAFP/4ARQCiQAXAAATERQXHgE3FQYjIiYnJjURIzUzNTMVMxWxAQMmMx8qMjMEAUdHVmM +BzP7PGw4mFgY/BSwxDjQBNUJ7e0IAAAABAEL/8gICAhIAFwAAAREjNQcGIyImJyY1ETMRFBceATMy +Nj0BAgJWITlRT2EKBVYEBkA1RFECEv3uWj4qTToiOQE+/tIlJC43c4DpAAAAAAEAAQAAAfwCEgAGA +AABAyMDMxsBAfzJaclfop8CEv3uAhL+LQHTAAABAAEAAAMLAhIADAAAAQMjCwEjAzMbATMbAQMLqW +Z2dmapY3t0a3Z7AhL97gG+/kICEv5AAcD+QwG9AAAB//oAAAHWAhIACwAAARMjJwcjEwMzFzczARq +8ZIuKY763ZoWFYwEO/vLV1QEMAQbNzQAAAQAB/y4B+wISABEAAAEDDgEjIic1FjMyNj8BAzMbAQH7 +2iFZQB8NDRIpNhQH02GenQIS/cFVUAJGASozEwIt/i4B0gABABQAAAGxAg4ACQAAJRUhNQEhNSEVA +QGx/mMBNP7iAYL+zkREQgGIREX+ewAAAAABAED/sAEOAwwALAAAASMiBhUUFxYVFAYHHgEVFAcGFR +QWOwEVIyImNTQ3NjU0JzU2NTQnJjU0NjsBAQ4MKiMLDS4pKS4NCyMqDAtERAwLUlILDERECwLUGBk +WTlsgKzUFBTcrIFtOFhkYOC87GFVMIkUIOAhFIkxVGDsvAAAAAAEAYP84AJoDIAADAAAXIxEzmjo6 +yAPoAAEAIf+wAO8DDAAsAAATFQYVFBcWFRQGKwE1MzI2NTQnJjU0NjcuATU0NzY1NCYrATUzMhYVF +AcGFRTvUgsMREQLDCojCw0uKSkuDQsjKgwLREQMCwF6OAhFIkxVGDsvOBgZFk5bICs1BQU3KyBbTh +YZGDgvOxhVTCJFAAABAE0A3wH2AWQAEwAAATMUIyImJyYjIhUjNDMyFhcWMzIBvjhuGywtQR0xOG4 +bLC1BHTEBZIURGCNMhREYIwAAAwAk/94DIgLoAAcAEQApAAAAIBYQBiAmECQgBhUUFiA2NTQlMhYX +IyYjIgYUFjMyNjczDgEjIiY1NDYBAQFE3d3+vN0CB/7wubkBELn+xVBnD1wSWDo+QTcqOQZcEmZWX +HN2Aujg/rbg4AFKpr+Mjb6+jYxbWEldV5ZZNShLVn5na34AAgB4AFIB9AGeAAUACwAAAQcXIyc3Mw +cXIyc3AUqJiUmJifOJiUmJiQGepqampqampqYAAAIAHAHSAQ4CwAAHAA8AABIyFhQGIiY0NiIGFBY +yNjRgakREakSTNCEhNCECwEJqQkJqCiM4IyM4AAAAAAIAUAAAAfQCCwALAA8AAAEzFSMVIzUjNTM1 +MxMhNSEBP7W1OrW1OrX+XAGkAVs4tLQ4sP31OAAAAQB0AkQBAQKyAAMAABMjNzOsOD1QAkRuAAAAA +AEAIADsAKoBdgAHAAASMhYUBiImNEg6KCg6KAF2KDooKDoAAAIAOQBSAbUBngAFAAsAACUHIzcnMw +UHIzcnMwELiUmJiUkBM4lJiYlJ+KampqampqYAAAABADYB5QDhAt8ABAAAEzczByM2Xk1OXQHv8Po +AAQAWAeUAwQLfAAQAABMHIzczwV5NTl0C1fD6AAIANgHlAYsC3wAEAAkAABM3MwcjPwEzByM2Xk1O +XapeTU5dAe/w+grw+gAAAgAWAeUBawLfAAQACQAAEwcjNzMXByM3M8FeTU5dql5NTl0C1fD6CvD6A +AADACX/8gI1AHIABwAPABcAADYyFhQGIiY0NjIWFAYiJjQ2MhYUBiImNEk4JCQ4JOw4JCQ4JOw4JC +Q4JHIkOCQkOCQkOCQkOCQkOCQkOAAAAAEAeABSAUoBngAFAAABBxcjJzcBSomJSYmJAZ6mpqamAAA +AAAEAOQBSAQsBngAFAAAlByM3JzMBC4lJiYlJ+KampgAAAf9qAAABgQKyAAMAACsBATM/VwHAVwKy +AAAAAAIAFAHIAdwClAAHABQAABMVIxUjNSM1BRUjNwcjJxcjNTMXN9pKMkoByDICKzQqATJLKysCl +CmjoykBy46KiY3Lm5sAAQAVAAABvALyABgAAAERIxEjESMRIzUzNTQ3NjMyFxUmBgcGHQEBvFbCVj +k5AxHHHx5iVgcDAg798gHM/jQBzEIOJRuWBUcIJDAVIRYAAAABABX//AHkAvIAJQAAJR4BNxUGIyI +mJyY1ESYjIgcGHQEzFSMRIxEjNTM1NDc2MzIXERQBowIcIxkkKi4CAR4nXgwDbW1WLy8DEbNdOmYa +EQQ/BCQvEjQCFQZWFSEWQv40AcxCDiUblhP9uSEAAAAAAAAWAQ4AAQAAAAAAAAATACgAAQAAAAAAA +QAHAEwAAQAAAAAAAgAHAGQAAQAAAAAAAwAaAKIAAQAAAAAABAAHAM0AAQAAAAAABQA8AU8AAQAAAA +AABgAPAawAAQAAAAAACAALAdQAAQAAAAAACQALAfgAAQAAAAAACwAXAjQAAQAAAAAADAAXAnwAAwA +BBAkAAAAmAAAAAwABBAkAAQAOADwAAwABBAkAAgAOAFQAAwABBAkAAwA0AGwAAwABBAkABAAOAL0A +AwABBAkABQB4ANUAAwABBAkABgAeAYwAAwABBAkACAAWAbwAAwABBAkACQAWAeAAAwABBAkACwAuA +gQAAwABBAkADAAuAkwATgBvACAAUgBpAGcAaAB0AHMAIABSAGUAcwBlAHIAdgBlAGQALgAATm8gUm +lnaHRzIFJlc2VydmVkLgAAQQBpAGwAZQByAG8AbgAAQWlsZXJvbgAAUgBlAGcAdQBsAGEAcgAAUmV +ndWxhcgAAMQAuADEAMAAyADsAVQBLAFcATgA7AEEAaQBsAGUAcgBvAG4ALQBSAGUAZwB1AGwAYQBy +AAAxLjEwMjtVS1dOO0FpbGVyb24tUmVndWxhcgAAQQBpAGwAZQByAG8AbgAAQWlsZXJvbgAAVgBlA +HIAcwBpAG8AbgAgADEALgAxADAAMgA7AFAAUwAgADAAMAAxAC4AMQAwADIAOwBoAG8AdABjAG8Abg +B2ACAAMQAuADAALgA3ADAAOwBtAGEAawBlAG8AdABmAC4AbABpAGIAMgAuADUALgA1ADgAMwAyADk +AAFZlcnNpb24gMS4xMDI7UFMgMDAxLjEwMjtob3Rjb252IDEuMC43MDttYWtlb3RmLmxpYjIuNS41 +ODMyOQAAQQBpAGwAZQByAG8AbgAtAFIAZQBnAHUAbABhAHIAAEFpbGVyb24tUmVndWxhcgAAUwBvA +HIAYQAgAFMAYQBnAGEAbgBvAABTb3JhIFNhZ2FubwAAUwBvAHIAYQAgAFMAYQBnAGEAbgBvAABTb3 +JhIFNhZ2FubwAAaAB0AHQAcAA6AC8ALwB3AHcAdwAuAGQAbwB0AGMAbwBsAG8AbgAuAG4AZQB0AAB +odHRwOi8vd3d3LmRvdGNvbG9uLm5ldAAAaAB0AHQAcAA6AC8ALwB3AHcAdwAuAGQAbwB0AGMAbwBs +AG8AbgAuAG4AZQB0AABodHRwOi8vd3d3LmRvdGNvbG9uLm5ldAAAAAACAAAAAAAA/4MAMgAAAAAAA +AAAAAAAAAAAAAAAAAAAAHQAAAABAAIAAwAEAAUABgAHAAgACQAKAAsADAANAA4ADwAQABEAEgATAB +QAFQAWABcAGAAZABoAGwAcAB0AHgAfACAAIQAiACMAJAAlACYAJwAoACkAKgArACwALQAuAC8AMAA +xADIAMwA0ADUANgA3ADgAOQA6ADsAPAA9AD4APwBAAEEAQgBDAEQARQBGAEcASABJAEoASwBMAE0A +TgBPAFAAUQBSAFMAVABVAFYAVwBYAFkAWgBbAFwAXQBeAF8AYABhAIsAqQCDAJMAjQDDAKoAtgC3A +LQAtQCrAL4AvwC8AIwAwADBAAAAAAAB//8AAgABAAAADAAAABwAAAACAAIAAwBxAAEAcgBzAAIABA +AAAAIAAAABAAAACgBMAGYAAkRGTFQADmxhdG4AGgAEAAAAAP//AAEAAAAWAANDQVQgAB5NT0wgABZ +ST00gABYAAP//AAEAAAAA//8AAgAAAAEAAmxpZ2EADmxvY2wAFAAAAAEAAQAAAAEAAAACAAYAEAAG +AAAAAgASADQABAAAAAEATAADAAAAAgAQABYAAQAcAAAAAQABAE8AAQABAGcAAQABAE8AAwAAAAIAE +AAWAAEAHAAAAAEAAQAvAAEAAQBnAAEAAQAvAAEAGgABAAgAAgAGAAwAcwACAE8AcgACAEwAAQABAE +kAAAABAAAACgBGAGAAAkRGTFQADmxhdG4AHAAEAAAAAP//AAIAAAABABYAA0NBVCAAFk1PTCAAFlJ +PTSAAFgAA//8AAgAAAAEAAmNwc3AADmtlcm4AFAAAAAEAAAAAAAEAAQACAAYADgABAAAAAQASAAIA +AAACAB4ANgABAAoABQAFAAoAAgABACQAPQAAAAEAEgAEAAAAAQAMAAEAOP/nAAEAAQAkAAIGigAEA +AAFJAXKABoAGQAA//gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAD/sv+4/+z/7v/MAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAD/xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/9T/6AAAAAD/8QAA +ABD/vQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/7gAAAAAAAAAAAAAAAAAA//MAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABIAAAAAAAAAAP/5AAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP/gAAD/4AAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//L/9AAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAA/+gAAAAAAAkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP/zAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP/mAAAAAAAAAAAAAAAAAAD +/4gAA//AAAAAA//YAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/+AAAAAAAAP/OAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/zv/qAAAAAP/0AAAACAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP/ZAAD/egAA/1kAAAAA/5D/rgAAAAAAAAAAAA +AAAAAAAAAAAAAAAAD/9AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAD/8AAA/7b/8P+wAAD/8P/E/98AAAAA/8P/+P/0//oAAAAAAAAAAAAA//gA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/+AAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/w//C/9MAAP/SAAD/9wAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAD/yAAA/+kAAAAA//QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/9wAAAAD//QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAP/2AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAP/cAAAAAAAAAAAAAAAA/7YAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAP/8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/6AAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAkAFAAEAAAAAQACwAAABcA +BgAAAAAAAAAIAA4AAAAAAAsAEgAAAAAAAAATABkAAwANAAAAAQAJAAAAAAAAAAAAAAAAAAAAGAAAA +AAABwAAAAAAAAAAAAAAFQAFAAAAAAAYABgAAAAUAAAACgAAAAwAAgAPABEAFgAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAEAEQBdAAYAAAAAAAAAAAAAAAAAAAAAAAA +AAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAcAAAAAAAAABwAAAAAACAAAAAAAAAAAAAcAAAAHAAAAEwAJ +ABUADgAPAAAACwAQAAAAAAAAAAAAAAAAAAUAGAACAAIAAgAAAAIAGAAXAAAAGAAAABYAFgACABYAA +gAWAAAAEQADAAoAFAAMAA0ABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASAAAAEgAGAAEAHgAkAC +YAJwApACoALQAuAC8AMgAzADcAOAA5ADoAPAA9AEUASABOAE8AUgBTAFUAVwBZAFoAWwBcAF0AcwA +AAAAAAQAAAADa3tfFAAAAANAan9kAAAAA4QodoQ== +""")), + 10 if size is None else size, + layout_engine=Layout.BASIC, + ) + return load_default_imagefont() diff --git a/.venv/lib/python3.11/site-packages/PIL/ImageGrab.py b/.venv/lib/python3.11/site-packages/PIL/ImageGrab.py new file mode 100644 index 0000000000000000000000000000000000000000..52cbfea406d3d5d3c422bc280fdc52f84290e245 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/ImageGrab.py @@ -0,0 +1,234 @@ +# +# The Python Imaging Library +# $Id$ +# +# screen grabber +# +# History: +# 2001-04-26 fl created +# 2001-09-17 fl use builtin driver, if present +# 2002-11-19 fl added grabclipboard support +# +# Copyright (c) 2001-2002 by Secret Labs AB +# Copyright (c) 2001-2002 by Fredrik Lundh +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import io +import os +import shutil +import subprocess +import sys +import tempfile + +from . import Image + +TYPE_CHECKING = False +if TYPE_CHECKING: + from . import ImageWin + + +def grab( + bbox: tuple[int, int, int, int] | None = None, + include_layered_windows: bool = False, + all_screens: bool = False, + xdisplay: str | None = None, + window: int | ImageWin.HWND | None = None, + *, + scale_down: bool = False, +) -> Image.Image: + im: Image.Image + if xdisplay is None: + if sys.platform == "darwin": + fh, filepath = tempfile.mkstemp(".png") + os.close(fh) + args = ["screencapture"] + if window is not None: + args += ["-l", str(window)] + elif bbox: + left, top, right, bottom = bbox + args += ["-R", f"{left},{top},{right-left},{bottom-top}"] + args += ["-x", filepath] + retcode = subprocess.call(args) + if retcode: + raise subprocess.CalledProcessError(retcode, args) + im = Image.open(filepath) + im.load() + os.unlink(filepath) + if bbox: + if window is not None: + # Determine if the window was in Retina mode or not + # by capturing it without the shadow, + # and checking how different the width is + fh, filepath = tempfile.mkstemp(".png") + os.close(fh) + args = ["screencapture", "-l", str(window), "-o", "-x", filepath] + retcode = subprocess.call(args) + if retcode: + raise subprocess.CalledProcessError(retcode, args) + with Image.open(filepath) as im_no_shadow: + retina = im.width - im_no_shadow.width > 100 + os.unlink(filepath) + + # Since screencapture's -R does not work with -l, + # crop the image manually + if retina: + left, top, right, bottom = bbox + scale = 1 if scale_down else 2 + im_cropped = im.resize( + ((right - left) * scale, (bottom - top) * scale), + box=tuple(coord * 2 for coord in bbox), + ) + else: + im_cropped = im.crop(bbox) + im.close() + return im_cropped + elif scale_down: + im_resized = im.resize((right - left, bottom - top)) + im.close() + return im_resized + return im + elif sys.platform == "win32": + if window is not None: + all_screens = -1 + offset, size, data = Image.core.grabscreen_win32( + include_layered_windows, + all_screens, + int(window) if window is not None else 0, + ) + im = Image.frombytes( + "RGB", + size, + data, + # RGB, 32-bit line padding, origin lower left corner + "raw", + "BGR", + (size[0] * 3 + 3) & -4, + -1, + ) + if bbox: + x0, y0 = offset + left, top, right, bottom = bbox + im = im.crop((left - x0, top - y0, right - x0, bottom - y0)) + return im + # Cast to Optional[str] needed for Windows and macOS. + display_name: str | None = xdisplay + try: + if not Image.core.HAVE_XCB: + msg = "Pillow was built without XCB support" + raise OSError(msg) + size, data = Image.core.grabscreen_x11(display_name) + except OSError: + if display_name is None and sys.platform not in ("darwin", "win32"): + if shutil.which("gnome-screenshot"): + args = ["gnome-screenshot", "-f"] + elif shutil.which("grim"): + args = ["grim"] + elif shutil.which("spectacle"): + args = ["spectacle", "-n", "-b", "-f", "-o"] + else: + raise + fh, filepath = tempfile.mkstemp(".png") + os.close(fh) + args.append(filepath) + retcode = subprocess.call(args) + if retcode: + raise subprocess.CalledProcessError(retcode, args) + im = Image.open(filepath) + im.load() + os.unlink(filepath) + if bbox: + im_cropped = im.crop(bbox) + im.close() + return im_cropped + return im + else: + raise + else: + im = Image.frombytes("RGB", size, data, "raw", "BGRX", size[0] * 4, 1) + if bbox: + im = im.crop(bbox) + return im + + +def grabclipboard() -> Image.Image | list[str] | None: + if sys.platform == "darwin": + p = subprocess.run( + ["osascript", "-e", "get the clipboard as «class PNGf»"], + capture_output=True, + ) + if p.returncode != 0: + return None + + import binascii + + data = io.BytesIO(binascii.unhexlify(p.stdout[11:-3])) + return Image.open(data) + elif sys.platform == "win32": + fmt, data = Image.core.grabclipboard_win32() + if fmt == "file": # CF_HDROP + import struct + + o = struct.unpack_from("I", data)[0] + if data[16] == 0: + files = data[o:].decode("mbcs").split("\0") + else: + files = data[o:].decode("utf-16le").split("\0") + return files[: files.index("")] + if isinstance(data, bytes): + data = io.BytesIO(data) + if fmt == "png": + from . import PngImagePlugin + + return PngImagePlugin.PngImageFile(data) + elif fmt == "DIB": + from . import BmpImagePlugin + + return BmpImagePlugin.DibImageFile(data) + return None + else: + if os.getenv("WAYLAND_DISPLAY"): + session_type = "wayland" + elif os.getenv("DISPLAY"): + session_type = "x11" + else: # Session type check failed + session_type = None + + if shutil.which("wl-paste") and session_type in ("wayland", None): + args = ["wl-paste", "-t", "image"] + elif shutil.which("xclip") and session_type in ("x11", None): + args = ["xclip", "-selection", "clipboard", "-t", "image/png", "-o"] + else: + msg = "wl-paste or xclip is required for ImageGrab.grabclipboard() on Linux" + raise NotImplementedError(msg) + + p = subprocess.run(args, capture_output=True) + if p.returncode != 0: + err = p.stderr + for silent_error in [ + # wl-paste, when the clipboard is empty + b"Nothing is copied", + # Ubuntu/Debian wl-paste, when the clipboard is empty + b"No selection", + # Ubuntu/Debian wl-paste, when an image isn't available + b"No suitable type of content copied", + # wl-paste or Ubuntu/Debian xclip, when an image isn't available + b" not available", + # xclip, when an image isn't available + b"cannot convert ", + # xclip, when the clipboard isn't initialized + b"xclip: Error: There is no owner for the ", + ]: + if silent_error in err: + return None + msg = f"{args[0]} error" + if err: + msg += f": {err.strip().decode()}" + raise ChildProcessError(msg) + + data = io.BytesIO(p.stdout) + im = Image.open(data) + im.load() + return im diff --git a/.venv/lib/python3.11/site-packages/PIL/ImageMath.py b/.venv/lib/python3.11/site-packages/PIL/ImageMath.py new file mode 100644 index 0000000000000000000000000000000000000000..f62c6a3f84530aeefc162103faa6260050e5e725 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/ImageMath.py @@ -0,0 +1,314 @@ +# +# The Python Imaging Library +# $Id$ +# +# a simple math add-on for the Python Imaging Library +# +# History: +# 1999-02-15 fl Original PIL Plus release +# 2005-05-05 fl Simplified and cleaned up for PIL 1.1.6 +# 2005-09-12 fl Fixed int() and float() for Python 2.4.1 +# +# Copyright (c) 1999-2005 by Secret Labs AB +# Copyright (c) 2005 by Fredrik Lundh +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import builtins + +from . import Image, _imagingmath + +TYPE_CHECKING = False +if TYPE_CHECKING: + from collections.abc import Callable + from types import CodeType + from typing import Any + + +class _Operand: + """Wraps an image operand, providing standard operators""" + + def __init__(self, im: Image.Image): + self.im = im + + def __fixup(self, im1: _Operand | float) -> Image.Image: + # convert image to suitable mode + if isinstance(im1, _Operand): + # argument was an image. + if im1.im.mode in ("1", "L"): + return im1.im.convert("I") + elif im1.im.mode in ("I", "F"): + return im1.im + else: + msg = f"unsupported mode: {im1.im.mode}" + raise ValueError(msg) + else: + # argument was a constant + if isinstance(im1, (int, float)) and self.im.mode in ("1", "L", "I"): + return Image.new("I", self.im.size, im1) + else: + return Image.new("F", self.im.size, im1) + + def apply( + self, + op: str, + im1: _Operand | float, + im2: _Operand | float | None = None, + mode: str | None = None, + ) -> _Operand: + im_1 = self.__fixup(im1) + if im2 is None: + # unary operation + out = Image.new(mode or im_1.mode, im_1.size, None) + try: + op = getattr(_imagingmath, f"{op}_{im_1.mode}") + except AttributeError as e: + msg = f"bad operand type for '{op}'" + raise TypeError(msg) from e + _imagingmath.unop(op, out.getim(), im_1.getim()) + else: + # binary operation + im_2 = self.__fixup(im2) + if im_1.mode != im_2.mode: + # convert both arguments to floating point + if im_1.mode != "F": + im_1 = im_1.convert("F") + if im_2.mode != "F": + im_2 = im_2.convert("F") + if im_1.size != im_2.size: + # crop both arguments to a common size + size = ( + min(im_1.size[0], im_2.size[0]), + min(im_1.size[1], im_2.size[1]), + ) + if im_1.size != size: + im_1 = im_1.crop((0, 0) + size) + if im_2.size != size: + im_2 = im_2.crop((0, 0) + size) + out = Image.new(mode or im_1.mode, im_1.size, None) + try: + op = getattr(_imagingmath, f"{op}_{im_1.mode}") + except AttributeError as e: + msg = f"bad operand type for '{op}'" + raise TypeError(msg) from e + _imagingmath.binop(op, out.getim(), im_1.getim(), im_2.getim()) + return _Operand(out) + + # unary operators + def __bool__(self) -> bool: + # an image is "true" if it contains at least one non-zero pixel + return self.im.getbbox() is not None + + def __abs__(self) -> _Operand: + return self.apply("abs", self) + + def __pos__(self) -> _Operand: + return self + + def __neg__(self) -> _Operand: + return self.apply("neg", self) + + # binary operators + def __add__(self, other: _Operand | float) -> _Operand: + return self.apply("add", self, other) + + def __radd__(self, other: _Operand | float) -> _Operand: + return self.apply("add", other, self) + + def __sub__(self, other: _Operand | float) -> _Operand: + return self.apply("sub", self, other) + + def __rsub__(self, other: _Operand | float) -> _Operand: + return self.apply("sub", other, self) + + def __mul__(self, other: _Operand | float) -> _Operand: + return self.apply("mul", self, other) + + def __rmul__(self, other: _Operand | float) -> _Operand: + return self.apply("mul", other, self) + + def __truediv__(self, other: _Operand | float) -> _Operand: + return self.apply("div", self, other) + + def __rtruediv__(self, other: _Operand | float) -> _Operand: + return self.apply("div", other, self) + + def __mod__(self, other: _Operand | float) -> _Operand: + return self.apply("mod", self, other) + + def __rmod__(self, other: _Operand | float) -> _Operand: + return self.apply("mod", other, self) + + def __pow__(self, other: _Operand | float) -> _Operand: + return self.apply("pow", self, other) + + def __rpow__(self, other: _Operand | float) -> _Operand: + return self.apply("pow", other, self) + + # bitwise + def __invert__(self) -> _Operand: + return self.apply("invert", self) + + def __and__(self, other: _Operand | float) -> _Operand: + return self.apply("and", self, other) + + def __rand__(self, other: _Operand | float) -> _Operand: + return self.apply("and", other, self) + + def __or__(self, other: _Operand | float) -> _Operand: + return self.apply("or", self, other) + + def __ror__(self, other: _Operand | float) -> _Operand: + return self.apply("or", other, self) + + def __xor__(self, other: _Operand | float) -> _Operand: + return self.apply("xor", self, other) + + def __rxor__(self, other: _Operand | float) -> _Operand: + return self.apply("xor", other, self) + + def __lshift__(self, other: _Operand | float) -> _Operand: + return self.apply("lshift", self, other) + + def __rshift__(self, other: _Operand | float) -> _Operand: + return self.apply("rshift", self, other) + + # logical + def __eq__(self, other: _Operand | float) -> _Operand: # type: ignore[override] + return self.apply("eq", self, other) + + def __ne__(self, other: _Operand | float) -> _Operand: # type: ignore[override] + return self.apply("ne", self, other) + + def __lt__(self, other: _Operand | float) -> _Operand: + return self.apply("lt", self, other) + + def __le__(self, other: _Operand | float) -> _Operand: + return self.apply("le", self, other) + + def __gt__(self, other: _Operand | float) -> _Operand: + return self.apply("gt", self, other) + + def __ge__(self, other: _Operand | float) -> _Operand: + return self.apply("ge", self, other) + + +# conversions +def imagemath_int(self: _Operand) -> _Operand: + return _Operand(self.im.convert("I")) + + +def imagemath_float(self: _Operand) -> _Operand: + return _Operand(self.im.convert("F")) + + +# logical +def imagemath_equal(self: _Operand, other: _Operand | float | None) -> _Operand: + return self.apply("eq", self, other, mode="I") + + +def imagemath_notequal(self: _Operand, other: _Operand | float | None) -> _Operand: + return self.apply("ne", self, other, mode="I") + + +def imagemath_min(self: _Operand, other: _Operand | float | None) -> _Operand: + return self.apply("min", self, other) + + +def imagemath_max(self: _Operand, other: _Operand | float | None) -> _Operand: + return self.apply("max", self, other) + + +def imagemath_convert(self: _Operand, mode: str) -> _Operand: + return _Operand(self.im.convert(mode)) + + +ops = { + "int": imagemath_int, + "float": imagemath_float, + "equal": imagemath_equal, + "notequal": imagemath_notequal, + "min": imagemath_min, + "max": imagemath_max, + "convert": imagemath_convert, +} + + +def lambda_eval(expression: Callable[[dict[str, Any]], Any], **kw: Any) -> Any: + """ + Returns the result of an image function. + + :py:mod:`~PIL.ImageMath` only supports single-layer images. To process multi-band + images, use the :py:meth:`~PIL.Image.Image.split` method or + :py:func:`~PIL.Image.merge` function. + + :param expression: A function that receives a dictionary. + :param **kw: Values to add to the function's dictionary. + :return: The expression result. This is usually an image object, but can + also be an integer, a floating point value, or a pixel tuple, + depending on the expression. + """ + + args: dict[str, Any] = ops.copy() + args.update(kw) + for k, v in args.items(): + if isinstance(v, Image.Image): + args[k] = _Operand(v) + + out = expression(args) + try: + return out.im + except AttributeError: + return out + + +def unsafe_eval(expression: str, **kw: Any) -> Any: + """ + Evaluates an image expression. This uses Python's ``eval()`` function to process + the expression string, and carries the security risks of doing so. It is not + recommended to process expressions without considering this. + :py:meth:`~lambda_eval` is a more secure alternative. + + :py:mod:`~PIL.ImageMath` only supports single-layer images. To process multi-band + images, use the :py:meth:`~PIL.Image.Image.split` method or + :py:func:`~PIL.Image.merge` function. + + :param expression: A string containing a Python-style expression. + :param **kw: Values to add to the evaluation context. + :return: The evaluated expression. This is usually an image object, but can + also be an integer, a floating point value, or a pixel tuple, + depending on the expression. + """ + + # build execution namespace + args: dict[str, Any] = ops.copy() + for k in kw: + if "__" in k or hasattr(builtins, k): + msg = f"'{k}' not allowed" + raise ValueError(msg) + + args.update(kw) + for k, v in args.items(): + if isinstance(v, Image.Image): + args[k] = _Operand(v) + + compiled_code = compile(expression, "", "eval") + + def scan(code: CodeType) -> None: + for const in code.co_consts: + if type(const) is type(compiled_code): + scan(const) + + for name in code.co_names: + if name not in args and name != "abs": + msg = f"'{name}' not allowed" + raise ValueError(msg) + + scan(compiled_code) + out = builtins.eval(expression, None, args) + try: + return out.im + except AttributeError: + return out diff --git a/.venv/lib/python3.11/site-packages/PIL/ImageMode.py b/.venv/lib/python3.11/site-packages/PIL/ImageMode.py new file mode 100644 index 0000000000000000000000000000000000000000..b7c6c863659b93416cac4acd8d8d31587566a9e6 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/ImageMode.py @@ -0,0 +1,85 @@ +# +# The Python Imaging Library. +# $Id$ +# +# standard mode descriptors +# +# History: +# 2006-03-20 fl Added +# +# Copyright (c) 2006 by Secret Labs AB. +# Copyright (c) 2006 by Fredrik Lundh. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import sys +from functools import lru_cache +from typing import NamedTuple + + +class ModeDescriptor(NamedTuple): + """Wrapper for mode strings.""" + + mode: str + bands: tuple[str, ...] + basemode: str + basetype: str + typestr: str + + def __str__(self) -> str: + return self.mode + + +@lru_cache +def getmode(mode: str) -> ModeDescriptor: + """Gets a mode descriptor for the given mode.""" + endian = "<" if sys.byteorder == "little" else ">" + + modes = { + # core modes + # Bits need to be extended to bytes + "1": ("L", "L", ("1",), "|b1"), + "L": ("L", "L", ("L",), "|u1"), + "I": ("L", "I", ("I",), f"{endian}i4"), + "F": ("L", "F", ("F",), f"{endian}f4"), + "P": ("P", "L", ("P",), "|u1"), + "RGB": ("RGB", "L", ("R", "G", "B"), "|u1"), + "RGBX": ("RGB", "L", ("R", "G", "B", "X"), "|u1"), + "RGBA": ("RGB", "L", ("R", "G", "B", "A"), "|u1"), + "CMYK": ("RGB", "L", ("C", "M", "Y", "K"), "|u1"), + "YCbCr": ("RGB", "L", ("Y", "Cb", "Cr"), "|u1"), + # UNDONE - unsigned |u1i1i1 + "LAB": ("RGB", "L", ("L", "A", "B"), "|u1"), + "HSV": ("RGB", "L", ("H", "S", "V"), "|u1"), + # extra experimental modes + "RGBa": ("RGB", "L", ("R", "G", "B", "a"), "|u1"), + "LA": ("L", "L", ("L", "A"), "|u1"), + "La": ("L", "L", ("L", "a"), "|u1"), + "PA": ("RGB", "L", ("P", "A"), "|u1"), + } + if mode in modes: + base_mode, base_type, bands, type_str = modes[mode] + return ModeDescriptor(mode, bands, base_mode, base_type, type_str) + + mapping_modes = { + # I;16 == I;16L, and I;32 == I;32L + "I;16": "u2", + "I;16BS": ">i2", + "I;16N": f"{endian}u2", + "I;16NS": f"{endian}i2", + "I;32": "u4", + "I;32L": "i4", + "I;32LS": " +from __future__ import annotations + +import re + +from . import Image, _imagingmorph + +LUT_SIZE = 1 << 9 + +# fmt: off +ROTATION_MATRIX = [ + 6, 3, 0, + 7, 4, 1, + 8, 5, 2, +] +MIRROR_MATRIX = [ + 2, 1, 0, + 5, 4, 3, + 8, 7, 6, +] +# fmt: on + + +class LutBuilder: + """A class for building a MorphLut from a descriptive language + + The input patterns is a list of a strings sequences like these:: + + 4:(... + .1. + 111)->1 + + (whitespaces including linebreaks are ignored). The option 4 + describes a series of symmetry operations (in this case a + 4-rotation), the pattern is described by: + + - . or X - Ignore + - 1 - Pixel is on + - 0 - Pixel is off + + The result of the operation is described after "->" string. + + The default is to return the current pixel value, which is + returned if no other match is found. + + Operations: + + - 4 - 4 way rotation + - N - Negate + - 1 - Dummy op for no other operation (an op must always be given) + - M - Mirroring + + Example:: + + lb = LutBuilder(patterns = ["4:(... .1. 111)->1"]) + lut = lb.build_lut() + + """ + + def __init__( + self, patterns: list[str] | None = None, op_name: str | None = None + ) -> None: + """ + :param patterns: A list of input patterns, or None. + :param op_name: The name of a known pattern. One of "corner", "dilation4", + "dilation8", "erosion4", "erosion8" or "edge". + :exception Exception: If the op_name is not recognized. + """ + self.lut: bytearray | None = None + if op_name is not None: + known_patterns = { + "corner": ["1:(... ... ...)->0", "4:(00. 01. ...)->1"], + "dilation4": ["4:(... .0. .1.)->1"], + "dilation8": ["4:(... .0. .1.)->1", "4:(... .0. ..1)->1"], + "erosion4": ["4:(... .1. .0.)->0"], + "erosion8": ["4:(... .1. .0.)->0", "4:(... .1. ..0)->0"], + "edge": [ + "1:(... ... ...)->0", + "4:(.0. .1. ...)->1", + "4:(01. .1. ...)->1", + ], + } + if op_name not in known_patterns: + msg = f"Unknown pattern {op_name}!" + raise Exception(msg) + + self.patterns = known_patterns[op_name] + elif patterns is not None: + self.patterns = patterns + else: + self.patterns = [] + + def add_patterns(self, patterns: list[str]) -> None: + """ + Append to list of patterns. + + :param patterns: Additional patterns. + """ + self.patterns += patterns + + def build_default_lut(self) -> bytearray: + """ + Set the current LUT, and return it. + + This is the default LUT that patterns will be applied against when building. + """ + symbols = [0, 1] + m = 1 << 4 # pos of current pixel + self.lut = bytearray(symbols[(i & m) > 0] for i in range(LUT_SIZE)) + return self.lut + + def get_lut(self) -> bytearray | None: + """ + Returns the current LUT + """ + return self.lut + + def _string_permute(self, pattern: str, permutation: list[int]) -> str: + """Takes a pattern and a permutation and returns the + string permuted according to the permutation list. + """ + assert len(permutation) == 9 + return "".join(pattern[p] for p in permutation) + + def _pattern_permute( + self, basic_pattern: str, options: str, basic_result: int + ) -> list[tuple[str, int]]: + """Takes a basic pattern and its result and clones + the pattern according to the modifications described in the $options + parameter. It returns a list of all cloned patterns.""" + patterns = [(basic_pattern, basic_result)] + + # rotations + if "4" in options: + res = patterns[-1][1] + for i in range(4): + patterns.append( + (self._string_permute(patterns[-1][0], ROTATION_MATRIX), res) + ) + # mirror + if "M" in options: + n = len(patterns) + for pattern, res in patterns[:n]: + patterns.append((self._string_permute(pattern, MIRROR_MATRIX), res)) + + # negate + if "N" in options: + n = len(patterns) + for pattern, res in patterns[:n]: + # Swap 0 and 1 + pattern = pattern.replace("0", "Z").replace("1", "0").replace("Z", "1") + res = 1 - int(res) + patterns.append((pattern, res)) + + return patterns + + def build_lut(self) -> bytearray: + """Compile all patterns into a morphology LUT, and return it. + + This is the data to be passed into MorphOp.""" + self.build_default_lut() + assert self.lut is not None + patterns = [] + + # Parse and create symmetries of the patterns strings + for p in self.patterns: + m = re.search(r"(\w):?\s*\((.+?)\)\s*->\s*(\d)", p.replace("\n", "")) + if not m: + msg = 'Syntax error in pattern "' + p + '"' + raise Exception(msg) + options = m.group(1) + pattern = m.group(2) + result = int(m.group(3)) + + # Get rid of spaces + pattern = pattern.replace(" ", "").replace("\n", "") + + patterns += self._pattern_permute(pattern, options, result) + + # Compile the patterns into regular expressions for speed + compiled_patterns = [] + for pattern in patterns: + p = pattern[0].replace(".", "X").replace("X", "[01]") + compiled_patterns.append((re.compile(p), pattern[1])) + + # Step through table and find patterns that match. + # Note that all the patterns are searched. The last one found takes priority + for i in range(LUT_SIZE): + # Build the bit pattern + bitpattern = bin(i)[2:] + bitpattern = ("0" * (9 - len(bitpattern)) + bitpattern)[::-1] + + for pattern, r in compiled_patterns: + if pattern.match(bitpattern): + self.lut[i] = [0, 1][r] + + return self.lut + + +class MorphOp: + """A class for binary morphological operators""" + + def __init__( + self, + lut: bytearray | None = None, + op_name: str | None = None, + patterns: list[str] | None = None, + ) -> None: + """Create a binary morphological operator. + + If the LUT is not provided, then it is built using LutBuilder from the op_name + or the patterns. + + :param lut: The LUT data. + :param patterns: A list of input patterns, or None. + :param op_name: The name of a known pattern. One of "corner", "dilation4", + "dilation8", "erosion4", "erosion8", "edge". + :exception Exception: If the op_name is not recognized. + """ + if patterns is None and op_name is None: + self.lut = lut + else: + self.lut = LutBuilder(patterns, op_name).build_lut() + + def apply(self, image: Image.Image) -> tuple[int, Image.Image]: + """Run a single morphological operation on an image. + + Returns a tuple of the number of changed pixels and the + morphed image. + + :param image: A 1-mode or L-mode image. + :exception Exception: If the current operator is None. + :exception ValueError: If the image is not 1 or L mode.""" + if self.lut is None: + msg = "No operator loaded" + raise Exception(msg) + + if image.mode not in ("1", "L"): + msg = "Image mode must be 1 or L" + raise ValueError(msg) + outimage = Image.new(image.mode, image.size) + count = _imagingmorph.apply(bytes(self.lut), image.getim(), outimage.getim()) + return count, outimage + + def match(self, image: Image.Image) -> list[tuple[int, int]]: + """Get a list of coordinates matching the morphological operation on + an image. + + Returns a list of tuples of (x,y) coordinates of all matching pixels. See + :ref:`coordinate-system`. + + :param image: A 1-mode or L-mode image. + :exception Exception: If the current operator is None. + :exception ValueError: If the image is not 1 or L mode.""" + if self.lut is None: + msg = "No operator loaded" + raise Exception(msg) + + if image.mode not in ("1", "L"): + msg = "Image mode must be 1 or L" + raise ValueError(msg) + return _imagingmorph.match(bytes(self.lut), image.getim()) + + def get_on_pixels(self, image: Image.Image) -> list[tuple[int, int]]: + """Get a list of all turned on pixels in a 1 or L mode image. + + Returns a list of tuples of (x,y) coordinates of all non-empty pixels. See + :ref:`coordinate-system`. + + :param image: A 1-mode or L-mode image. + :exception ValueError: If the image is not 1 or L mode.""" + + if image.mode not in ("1", "L"): + msg = "Image mode must be 1 or L" + raise ValueError(msg) + return _imagingmorph.get_on_pixels(image.getim()) + + def load_lut(self, filename: str) -> None: + """ + Load an operator from an mrl file + + :param filename: The file to read from. + :exception Exception: If the length of the file data is not 512. + """ + with open(filename, "rb") as f: + self.lut = bytearray(f.read()) + + if len(self.lut) != LUT_SIZE: + self.lut = None + msg = "Wrong size operator file!" + raise Exception(msg) + + def save_lut(self, filename: str) -> None: + """ + Save an operator to an mrl file. + + :param filename: The destination file. + :exception Exception: If the current operator is None. + """ + if self.lut is None: + msg = "No operator loaded" + raise Exception(msg) + with open(filename, "wb") as f: + f.write(self.lut) + + def set_lut(self, lut: bytearray | None) -> None: + """ + Set the LUT from an external source + + :param lut: A new LUT. + """ + self.lut = lut diff --git a/.venv/lib/python3.11/site-packages/PIL/ImageOps.py b/.venv/lib/python3.11/site-packages/PIL/ImageOps.py new file mode 100644 index 0000000000000000000000000000000000000000..f0ae142b9ba99e3bac5b1537a80ebceb8fdf56b2 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/ImageOps.py @@ -0,0 +1,749 @@ +# +# The Python Imaging Library. +# $Id$ +# +# standard image operations +# +# History: +# 2001-10-20 fl Created +# 2001-10-23 fl Added autocontrast operator +# 2001-12-18 fl Added Kevin's fit operator +# 2004-03-14 fl Fixed potential division by zero in equalize +# 2005-05-05 fl Fixed equalize for low number of values +# +# Copyright (c) 2001-2004 by Secret Labs AB +# Copyright (c) 2001-2004 by Fredrik Lundh +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import functools +import operator +import re +from collections.abc import Sequence +from typing import Literal, Protocol, cast, overload + +from . import ExifTags, Image, ImagePalette + +# +# helpers + + +def _border(border: int | tuple[int, ...]) -> tuple[int, int, int, int]: + if isinstance(border, tuple): + if len(border) == 2: + left, top = right, bottom = border + elif len(border) == 4: + left, top, right, bottom = border + else: + msg = "border must be an integer, or a tuple of two or four elements" + raise ValueError(msg) + else: + left = top = right = bottom = border + return left, top, right, bottom + + +def _color(color: str | int | tuple[int, ...], mode: str) -> int | tuple[int, ...]: + if isinstance(color, str): + from . import ImageColor + + color = ImageColor.getcolor(color, mode) + return color + + +def _lut(image: Image.Image, lut: list[int]) -> Image.Image: + if image.mode == "P": + # FIXME: apply to lookup table, not image data + msg = "mode P support coming soon" + raise NotImplementedError(msg) + elif image.mode in ("L", "RGB"): + if image.mode == "RGB" and len(lut) == 256: + lut = lut + lut + lut + return image.point(lut) + else: + msg = f"not supported for mode {image.mode}" + raise OSError(msg) + + +# +# actions + + +def autocontrast( + image: Image.Image, + cutoff: float | tuple[float, float] = 0, + ignore: int | Sequence[int] | None = None, + mask: Image.Image | None = None, + preserve_tone: bool = False, +) -> Image.Image: + """ + Maximize (normalize) image contrast. This function calculates a + histogram of the input image (or mask region), removes ``cutoff`` percent of the + lightest and darkest pixels from the histogram, and remaps the image + so that the darkest pixel becomes black (0), and the lightest + becomes white (255). + + :param image: The image to process. + :param cutoff: The percent to cut off from the histogram on the low and + high ends. Either a tuple of (low, high), or a single + number for both. + :param ignore: The background pixel value (use None for no background). + :param mask: Histogram used in contrast operation is computed using pixels + within the mask. If no mask is given the entire image is used + for histogram computation. + :param preserve_tone: Preserve image tone in Photoshop-like style autocontrast. + + .. versionadded:: 8.2.0 + + :return: An image. + """ + if preserve_tone: + histogram = image.convert("L").histogram(mask) + else: + histogram = image.histogram(mask) + + lut = [] + for layer in range(0, len(histogram), 256): + h = histogram[layer : layer + 256] + if ignore is not None: + # get rid of outliers + if isinstance(ignore, int): + h[ignore] = 0 + else: + for ix in ignore: + h[ix] = 0 + if cutoff: + # cut off pixels from both ends of the histogram + if not isinstance(cutoff, tuple): + cutoff = (cutoff, cutoff) + # get number of pixels + n = 0 + for ix in range(256): + n = n + h[ix] + # remove cutoff% pixels from the low end + cut = int(n * cutoff[0] // 100) + for lo in range(256): + if cut > h[lo]: + cut = cut - h[lo] + h[lo] = 0 + else: + h[lo] -= cut + cut = 0 + if cut <= 0: + break + # remove cutoff% samples from the high end + cut = int(n * cutoff[1] // 100) + for hi in range(255, -1, -1): + if cut > h[hi]: + cut = cut - h[hi] + h[hi] = 0 + else: + h[hi] -= cut + cut = 0 + if cut <= 0: + break + # find lowest/highest samples after preprocessing + for lo in range(256): + if h[lo]: + break + for hi in range(255, -1, -1): + if h[hi]: + break + if hi <= lo: + # don't bother + lut.extend(list(range(256))) + else: + scale = 255.0 / (hi - lo) + offset = -lo * scale + for ix in range(256): + ix = int(ix * scale + offset) + if ix < 0: + ix = 0 + elif ix > 255: + ix = 255 + lut.append(ix) + return _lut(image, lut) + + +def colorize( + image: Image.Image, + black: str | tuple[int, ...], + white: str | tuple[int, ...], + mid: str | int | tuple[int, ...] | None = None, + blackpoint: int = 0, + whitepoint: int = 255, + midpoint: int = 127, +) -> Image.Image: + """ + Colorize grayscale image. + This function calculates a color wedge which maps all black pixels in + the source image to the first color and all white pixels to the + second color. If ``mid`` is specified, it uses three-color mapping. + The ``black`` and ``white`` arguments should be RGB tuples or color names; + optionally you can use three-color mapping by also specifying ``mid``. + Mapping positions for any of the colors can be specified + (e.g. ``blackpoint``), where these parameters are the integer + value corresponding to where the corresponding color should be mapped. + These parameters must have logical order, such that + ``blackpoint <= midpoint <= whitepoint`` (if ``mid`` is specified). + + :param image: The image to colorize. + :param black: The color to use for black input pixels. + :param white: The color to use for white input pixels. + :param mid: The color to use for midtone input pixels. + :param blackpoint: an int value [0, 255] for the black mapping. + :param whitepoint: an int value [0, 255] for the white mapping. + :param midpoint: an int value [0, 255] for the midtone mapping. + :return: An image. + """ + + # Initial asserts + assert image.mode == "L" + if mid is None: + assert 0 <= blackpoint <= whitepoint <= 255 + else: + assert 0 <= blackpoint <= midpoint <= whitepoint <= 255 + + # Define colors from arguments + rgb_black = cast(Sequence[int], _color(black, "RGB")) + rgb_white = cast(Sequence[int], _color(white, "RGB")) + rgb_mid = cast(Sequence[int], _color(mid, "RGB")) if mid is not None else None + + # Empty lists for the mapping + red = [] + green = [] + blue = [] + + # Create the low-end values + for i in range(blackpoint): + red.append(rgb_black[0]) + green.append(rgb_black[1]) + blue.append(rgb_black[2]) + + # Create the mapping (2-color) + if rgb_mid is None: + range_map = range(whitepoint - blackpoint) + + for i in range_map: + red.append( + rgb_black[0] + i * (rgb_white[0] - rgb_black[0]) // len(range_map) + ) + green.append( + rgb_black[1] + i * (rgb_white[1] - rgb_black[1]) // len(range_map) + ) + blue.append( + rgb_black[2] + i * (rgb_white[2] - rgb_black[2]) // len(range_map) + ) + + # Create the mapping (3-color) + else: + range_map1 = range(midpoint - blackpoint) + range_map2 = range(whitepoint - midpoint) + + for i in range_map1: + red.append( + rgb_black[0] + i * (rgb_mid[0] - rgb_black[0]) // len(range_map1) + ) + green.append( + rgb_black[1] + i * (rgb_mid[1] - rgb_black[1]) // len(range_map1) + ) + blue.append( + rgb_black[2] + i * (rgb_mid[2] - rgb_black[2]) // len(range_map1) + ) + for i in range_map2: + red.append(rgb_mid[0] + i * (rgb_white[0] - rgb_mid[0]) // len(range_map2)) + green.append( + rgb_mid[1] + i * (rgb_white[1] - rgb_mid[1]) // len(range_map2) + ) + blue.append(rgb_mid[2] + i * (rgb_white[2] - rgb_mid[2]) // len(range_map2)) + + # Create the high-end values + for i in range(256 - whitepoint): + red.append(rgb_white[0]) + green.append(rgb_white[1]) + blue.append(rgb_white[2]) + + # Return converted image + image = image.convert("RGB") + return _lut(image, red + green + blue) + + +def contain( + image: Image.Image, size: tuple[int, int], method: int = Image.Resampling.BICUBIC +) -> Image.Image: + """ + Returns a resized version of the image, set to the maximum width and height + within the requested size, while maintaining the original aspect ratio. + + :param image: The image to resize. + :param size: The requested output size in pixels, given as a + (width, height) tuple. + :param method: Resampling method to use. Default is + :py:attr:`~PIL.Image.Resampling.BICUBIC`. + See :ref:`concept-filters`. + :return: An image. + """ + + im_ratio = image.width / image.height + dest_ratio = size[0] / size[1] + + if im_ratio != dest_ratio: + if im_ratio > dest_ratio: + new_height = round(image.height / image.width * size[0]) + if new_height != size[1]: + size = (size[0], new_height) + else: + new_width = round(image.width / image.height * size[1]) + if new_width != size[0]: + size = (new_width, size[1]) + return image.resize(size, resample=method) + + +def cover( + image: Image.Image, size: tuple[int, int], method: int = Image.Resampling.BICUBIC +) -> Image.Image: + """ + Returns a resized version of the image, so that the requested size is + covered, while maintaining the original aspect ratio. + + :param image: The image to resize. + :param size: The requested output size in pixels, given as a + (width, height) tuple. + :param method: Resampling method to use. Default is + :py:attr:`~PIL.Image.Resampling.BICUBIC`. + See :ref:`concept-filters`. + :return: An image. + """ + + im_ratio = image.width / image.height + dest_ratio = size[0] / size[1] + + if im_ratio != dest_ratio: + if im_ratio < dest_ratio: + new_height = round(image.height / image.width * size[0]) + if new_height != size[1]: + size = (size[0], new_height) + else: + new_width = round(image.width / image.height * size[1]) + if new_width != size[0]: + size = (new_width, size[1]) + return image.resize(size, resample=method) + + +def pad( + image: Image.Image, + size: tuple[int, int], + method: int = Image.Resampling.BICUBIC, + color: str | int | tuple[int, ...] | None = None, + centering: tuple[float, float] = (0.5, 0.5), +) -> Image.Image: + """ + Returns a resized and padded version of the image, expanded to fill the + requested aspect ratio and size. + + :param image: The image to resize and crop. + :param size: The requested output size in pixels, given as a + (width, height) tuple. + :param method: Resampling method to use. Default is + :py:attr:`~PIL.Image.Resampling.BICUBIC`. + See :ref:`concept-filters`. + :param color: The background color of the padded image. + :param centering: Control the position of the original image within the + padded version. + + (0.5, 0.5) will keep the image centered + (0, 0) will keep the image aligned to the top left + (1, 1) will keep the image aligned to the bottom + right + :return: An image. + """ + + resized = contain(image, size, method) + if resized.size == size: + out = resized + else: + out = Image.new(image.mode, size, color) + if resized.palette: + palette = resized.getpalette() + if palette is not None: + out.putpalette(palette) + if resized.width != size[0]: + x = round((size[0] - resized.width) * max(0, min(centering[0], 1))) + out.paste(resized, (x, 0)) + else: + y = round((size[1] - resized.height) * max(0, min(centering[1], 1))) + out.paste(resized, (0, y)) + return out + + +def crop(image: Image.Image, border: int = 0) -> Image.Image: + """ + Remove border from image. The same amount of pixels are removed + from all four sides. This function works on all image modes. + + .. seealso:: :py:meth:`~PIL.Image.Image.crop` + + :param image: The image to crop. + :param border: The number of pixels to remove. + :return: An image. + """ + left, top, right, bottom = _border(border) + return image.crop((left, top, image.size[0] - right, image.size[1] - bottom)) + + +def scale( + image: Image.Image, factor: float, resample: int = Image.Resampling.BICUBIC +) -> Image.Image: + """ + Returns a rescaled image by a specific factor given in parameter. + A factor greater than 1 expands the image, between 0 and 1 contracts the + image. + + :param image: The image to rescale. + :param factor: The expansion factor, as a float. + :param resample: Resampling method to use. Default is + :py:attr:`~PIL.Image.Resampling.BICUBIC`. + See :ref:`concept-filters`. + :returns: An :py:class:`~PIL.Image.Image` object. + """ + if factor == 1: + return image.copy() + elif factor <= 0: + msg = "the factor must be greater than 0" + raise ValueError(msg) + else: + size = (round(factor * image.width), round(factor * image.height)) + return image.resize(size, resample) + + +class SupportsGetMesh(Protocol): + """ + An object that supports the ``getmesh`` method, taking an image as an + argument, and returning a list of tuples. Each tuple contains two tuples, + the source box as a tuple of 4 integers, and a tuple of 8 integers for the + final quadrilateral, in order of top left, bottom left, bottom right, top + right. + """ + + def getmesh( + self, image: Image.Image + ) -> list[ + tuple[tuple[int, int, int, int], tuple[int, int, int, int, int, int, int, int]] + ]: ... + + +def deform( + image: Image.Image, + deformer: SupportsGetMesh, + resample: int = Image.Resampling.BILINEAR, +) -> Image.Image: + """ + Deform the image. + + :param image: The image to deform. + :param deformer: A deformer object. Any object that implements a + ``getmesh`` method can be used. + :param resample: An optional resampling filter. Same values possible as + in the PIL.Image.transform function. + :return: An image. + """ + return image.transform( + image.size, Image.Transform.MESH, deformer.getmesh(image), resample + ) + + +def equalize(image: Image.Image, mask: Image.Image | None = None) -> Image.Image: + """ + Equalize the image histogram. This function applies a non-linear + mapping to the input image, in order to create a uniform + distribution of grayscale values in the output image. + + :param image: The image to equalize. + :param mask: An optional mask. If given, only the pixels selected by + the mask are included in the analysis. + :return: An image. + """ + if image.mode == "P": + image = image.convert("RGB") + h = image.histogram(mask) + lut = [] + for b in range(0, len(h), 256): + histo = [_f for _f in h[b : b + 256] if _f] + if len(histo) <= 1: + lut.extend(list(range(256))) + else: + step = (functools.reduce(operator.add, histo) - histo[-1]) // 255 + if not step: + lut.extend(list(range(256))) + else: + n = step // 2 + for i in range(256): + lut.append(n // step) + n = n + h[i + b] + return _lut(image, lut) + + +def expand( + image: Image.Image, + border: int | tuple[int, ...] = 0, + fill: str | int | tuple[int, ...] = 0, +) -> Image.Image: + """ + Add border to the image + + :param image: The image to expand. + :param border: Border width, in pixels. + :param fill: Pixel fill value (a color value). Default is 0 (black). + :return: An image. + """ + left, top, right, bottom = _border(border) + width = left + image.size[0] + right + height = top + image.size[1] + bottom + color = _color(fill, image.mode) + if image.palette: + mode = image.palette.mode + palette = ImagePalette.ImagePalette(mode, image.getpalette(mode)) + if isinstance(color, tuple) and (len(color) == 3 or len(color) == 4): + color = palette.getcolor(color) + else: + palette = None + out = Image.new(image.mode, (width, height), color) + if palette: + out.putpalette(palette.palette, mode) + out.paste(image, (left, top)) + return out + + +def fit( + image: Image.Image, + size: tuple[int, int], + method: int = Image.Resampling.BICUBIC, + bleed: float = 0.0, + centering: tuple[float, float] = (0.5, 0.5), +) -> Image.Image: + """ + Returns a resized and cropped version of the image, cropped to the + requested aspect ratio and size. + + This function was contributed by Kevin Cazabon. + + :param image: The image to resize and crop. + :param size: The requested output size in pixels, given as a + (width, height) tuple. + :param method: Resampling method to use. Default is + :py:attr:`~PIL.Image.Resampling.BICUBIC`. + See :ref:`concept-filters`. + :param bleed: Remove a border around the outside of the image from all + four edges. The value is a decimal percentage (use 0.01 for + one percent). The default value is 0 (no border). + Cannot be greater than or equal to 0.5. + :param centering: Control the cropping position. Use (0.5, 0.5) for + center cropping (e.g. if cropping the width, take 50% off + of the left side, and therefore 50% off the right side). + (0.0, 0.0) will crop from the top left corner (i.e. if + cropping the width, take all of the crop off of the right + side, and if cropping the height, take all of it off the + bottom). (1.0, 0.0) will crop from the bottom left + corner, etc. (i.e. if cropping the width, take all of the + crop off the left side, and if cropping the height take + none from the top, and therefore all off the bottom). + :return: An image. + """ + + # by Kevin Cazabon, Feb 17/2000 + # kevin@cazabon.com + # https://www.cazabon.com + + centering_x, centering_y = centering + + if not 0.0 <= centering_x <= 1.0: + centering_x = 0.5 + if not 0.0 <= centering_y <= 1.0: + centering_y = 0.5 + + if not 0.0 <= bleed < 0.5: + bleed = 0.0 + + # calculate the area to use for resizing and cropping, subtracting + # the 'bleed' around the edges + + # number of pixels to trim off on Top and Bottom, Left and Right + bleed_pixels = (bleed * image.size[0], bleed * image.size[1]) + + live_size = ( + image.size[0] - bleed_pixels[0] * 2, + image.size[1] - bleed_pixels[1] * 2, + ) + + # calculate the aspect ratio of the live_size + live_size_ratio = live_size[0] / live_size[1] + + # calculate the aspect ratio of the output image + output_ratio = size[0] / size[1] + + # figure out if the sides or top/bottom will be cropped off + if live_size_ratio == output_ratio: + # live_size is already the needed ratio + crop_width = live_size[0] + crop_height = live_size[1] + elif live_size_ratio >= output_ratio: + # live_size is wider than what's needed, crop the sides + crop_width = output_ratio * live_size[1] + crop_height = live_size[1] + else: + # live_size is taller than what's needed, crop the top and bottom + crop_width = live_size[0] + crop_height = live_size[0] / output_ratio + + # make the crop + crop_left = bleed_pixels[0] + (live_size[0] - crop_width) * centering_x + crop_top = bleed_pixels[1] + (live_size[1] - crop_height) * centering_y + + crop = (crop_left, crop_top, crop_left + crop_width, crop_top + crop_height) + + # resize the image and return it + return image.resize(size, method, box=crop) + + +def flip(image: Image.Image) -> Image.Image: + """ + Flip the image vertically (top to bottom). + + :param image: The image to flip. + :return: An image. + """ + return image.transpose(Image.Transpose.FLIP_TOP_BOTTOM) + + +def grayscale(image: Image.Image) -> Image.Image: + """ + Convert the image to grayscale. + + :param image: The image to convert. + :return: An image. + """ + return image.convert("L") + + +def invert(image: Image.Image) -> Image.Image: + """ + Invert (negate) the image. + + :param image: The image to invert. + :return: An image. + """ + lut = list(range(255, -1, -1)) + return image.point(lut) if image.mode == "1" else _lut(image, lut) + + +def mirror(image: Image.Image) -> Image.Image: + """ + Flip image horizontally (left to right). + + :param image: The image to mirror. + :return: An image. + """ + return image.transpose(Image.Transpose.FLIP_LEFT_RIGHT) + + +def posterize(image: Image.Image, bits: int) -> Image.Image: + """ + Reduce the number of bits for each color channel. + + :param image: The image to posterize. + :param bits: The number of bits to keep for each channel (1-8). + :return: An image. + """ + mask = ~(2 ** (8 - bits) - 1) + lut = [i & mask for i in range(256)] + return _lut(image, lut) + + +def solarize(image: Image.Image, threshold: int = 128) -> Image.Image: + """ + Invert all pixel values above a threshold. + + :param image: The image to solarize. + :param threshold: All pixels above this grayscale level are inverted. + :return: An image. + """ + lut = [] + for i in range(256): + if i < threshold: + lut.append(i) + else: + lut.append(255 - i) + return _lut(image, lut) + + +@overload +def exif_transpose(image: Image.Image, *, in_place: Literal[True]) -> None: ... + + +@overload +def exif_transpose( + image: Image.Image, *, in_place: Literal[False] = False +) -> Image.Image: ... + + +def exif_transpose(image: Image.Image, *, in_place: bool = False) -> Image.Image | None: + """ + If an image has an EXIF Orientation tag, other than 1, transpose the image + accordingly, and remove the orientation data. + + :param image: The image to transpose. + :param in_place: Boolean. Keyword-only argument. + If ``True``, the original image is modified in-place, and ``None`` is returned. + If ``False`` (default), a new :py:class:`~PIL.Image.Image` object is returned + with the transposition applied. If there is no transposition, a copy of the + image will be returned. + """ + image.load() + image_exif = image.getexif() + orientation = image_exif.get(ExifTags.Base.Orientation, 1) + method = { + 2: Image.Transpose.FLIP_LEFT_RIGHT, + 3: Image.Transpose.ROTATE_180, + 4: Image.Transpose.FLIP_TOP_BOTTOM, + 5: Image.Transpose.TRANSPOSE, + 6: Image.Transpose.ROTATE_270, + 7: Image.Transpose.TRANSVERSE, + 8: Image.Transpose.ROTATE_90, + }.get(orientation) + if method is not None: + if in_place: + image.im = image.im.transpose(method) + image._size = image.im.size + else: + transposed_image = image.transpose(method) + exif_image = image if in_place else transposed_image + + exif = exif_image.getexif() + if ExifTags.Base.Orientation in exif: + del exif[ExifTags.Base.Orientation] + if "exif" in exif_image.info: + exif_image.info["exif"] = exif.tobytes() + elif "Raw profile type exif" in exif_image.info: + exif_image.info["Raw profile type exif"] = exif.tobytes().hex() + for key in ("XML:com.adobe.xmp", "xmp"): + if key in exif_image.info: + for pattern in ( + r'tiff:Orientation="([0-9])"', + r"([0-9])", + ): + value = exif_image.info[key] + if isinstance(value, str): + value = re.sub(pattern, "", value) + elif isinstance(value, tuple): + value = tuple( + re.sub(pattern.encode(), b"", v) for v in value + ) + else: + value = re.sub(pattern.encode(), b"", value) + exif_image.info[key] = value + if not in_place: + return transposed_image + elif not in_place: + return image.copy() + return None diff --git a/.venv/lib/python3.11/site-packages/PIL/ImagePalette.py b/.venv/lib/python3.11/site-packages/PIL/ImagePalette.py new file mode 100644 index 0000000000000000000000000000000000000000..2abbd46eaf1550eb3598c3550adf629f8742cd09 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/ImagePalette.py @@ -0,0 +1,290 @@ +# +# The Python Imaging Library. +# $Id$ +# +# image palette object +# +# History: +# 1996-03-11 fl Rewritten. +# 1997-01-03 fl Up and running. +# 1997-08-23 fl Added load hack +# 2001-04-16 fl Fixed randint shadow bug in random() +# +# Copyright (c) 1997-2001 by Secret Labs AB +# Copyright (c) 1996-1997 by Fredrik Lundh +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import array +from collections.abc import Sequence +from typing import IO + +from . import GimpGradientFile, GimpPaletteFile, ImageColor, PaletteFile + +TYPE_CHECKING = False +if TYPE_CHECKING: + from . import Image + + +class ImagePalette: + """ + Color palette for palette mapped images + + :param mode: The mode to use for the palette. See: + :ref:`concept-modes`. Defaults to "RGB" + :param palette: An optional palette. If given, it must be a bytearray, + an array or a list of ints between 0-255. The list must consist of + all channels for one color followed by the next color (e.g. RGBRGBRGB). + Defaults to an empty palette. + """ + + def __init__( + self, + mode: str = "RGB", + palette: Sequence[int] | bytes | bytearray | None = None, + ) -> None: + self.mode = mode + self.rawmode: str | None = None # if set, palette contains raw data + self.palette = palette or bytearray() + self.dirty: int | None = None + + @property + def palette(self) -> Sequence[int] | bytes | bytearray: + return self._palette + + @palette.setter + def palette(self, palette: Sequence[int] | bytes | bytearray) -> None: + self._colors: dict[tuple[int, ...], int] | None = None + self._palette = palette + + @property + def colors(self) -> dict[tuple[int, ...], int]: + if self._colors is None: + mode_len = len(self.mode) + self._colors = {} + for i in range(0, len(self.palette), mode_len): + color = tuple(self.palette[i : i + mode_len]) + if color in self._colors: + continue + self._colors[color] = i // mode_len + return self._colors + + @colors.setter + def colors(self, colors: dict[tuple[int, ...], int]) -> None: + self._colors = colors + + def copy(self) -> ImagePalette: + new = ImagePalette() + + new.mode = self.mode + new.rawmode = self.rawmode + if self.palette is not None: + new.palette = self.palette[:] + new.dirty = self.dirty + + return new + + def getdata(self) -> tuple[str, Sequence[int] | bytes | bytearray]: + """ + Get palette contents in format suitable for the low-level + ``im.putpalette`` primitive. + + .. warning:: This method is experimental. + """ + if self.rawmode: + return self.rawmode, self.palette + return self.mode, self.tobytes() + + def tobytes(self) -> bytes: + """Convert palette to bytes. + + .. warning:: This method is experimental. + """ + if self.rawmode: + msg = "palette contains raw palette data" + raise ValueError(msg) + if isinstance(self.palette, bytes): + return self.palette + arr = array.array("B", self.palette) + return arr.tobytes() + + # Declare tostring as an alias for tobytes + tostring = tobytes + + def _new_color_index( + self, image: Image.Image | None = None, e: Exception | None = None + ) -> int: + if not isinstance(self.palette, bytearray): + self._palette = bytearray(self.palette) + index = len(self.palette) // len(self.mode) + special_colors: tuple[int | tuple[int, ...] | None, ...] = () + if image: + special_colors = ( + image.info.get("background"), + image.info.get("transparency"), + ) + while index in special_colors: + index += 1 + if index >= 256: + if image: + # Search for an unused index + for i, count in reversed(list(enumerate(image.histogram()))): + if count == 0 and i not in special_colors: + index = i + break + if index >= 256: + msg = "cannot allocate more than 256 colors" + raise ValueError(msg) from e + return index + + def getcolor( + self, + color: tuple[int, ...], + image: Image.Image | None = None, + ) -> int: + """Given an rgb tuple, allocate palette entry. + + .. warning:: This method is experimental. + """ + if self.rawmode: + msg = "palette contains raw palette data" + raise ValueError(msg) + if isinstance(color, tuple): + if self.mode == "RGB": + if len(color) == 4: + if color[3] != 255: + msg = "cannot add non-opaque RGBA color to RGB palette" + raise ValueError(msg) + color = color[:3] + elif self.mode == "RGBA": + if len(color) == 3: + color += (255,) + try: + return self.colors[color] + except KeyError as e: + # allocate new color slot + index = self._new_color_index(image, e) + assert isinstance(self._palette, bytearray) + self.colors[color] = index + mode_len = len(self.mode) + if index * mode_len < len(self.palette): + self._palette = ( + self._palette[: index * mode_len] + + bytes(color) + + self._palette[index * mode_len + mode_len :] + ) + else: + self._palette += bytes(color) + self.dirty = 1 + return index + else: + msg = f"unknown color specifier: {repr(color)}" # type: ignore[unreachable] + raise ValueError(msg) + + def save(self, fp: str | IO[str]) -> None: + """Save palette to text file. + + .. warning:: This method is experimental. + """ + if self.rawmode: + msg = "palette contains raw palette data" + raise ValueError(msg) + open_fp = False + if isinstance(fp, str): + fp = open(fp, "w") + open_fp = True + try: + fp.write("# Palette\n") + fp.write(f"# Mode: {self.mode}\n") + palette_len = len(self.palette) + for i in range(256): + fp.write(f"{i}") + for j in range(i * len(self.mode), (i + 1) * len(self.mode)): + fp.write(f" {self.palette[j] if j < palette_len else 0}") + fp.write("\n") + finally: + if open_fp: + fp.close() + + +# -------------------------------------------------------------------- +# Internal + + +def raw(rawmode: str, data: Sequence[int] | bytes | bytearray) -> ImagePalette: + palette = ImagePalette() + palette.rawmode = rawmode + palette.palette = data + palette.dirty = 1 + return palette + + +# -------------------------------------------------------------------- +# Factories + + +def make_linear_lut(black: int, white: float) -> list[int]: + if black == 0: + return [int(white * i // 255) for i in range(256)] + + msg = "unavailable when black is non-zero" + raise NotImplementedError(msg) # FIXME + + +def make_gamma_lut(exp: float) -> list[int]: + return [int(((i / 255.0) ** exp) * 255.0 + 0.5) for i in range(256)] + + +def negative(mode: str = "RGB") -> ImagePalette: + palette = list(range(256 * len(mode))) + palette.reverse() + return ImagePalette(mode, [i // len(mode) for i in palette]) + + +def random(mode: str = "RGB") -> ImagePalette: + from random import randint + + palette = [randint(0, 255) for _ in range(256 * len(mode))] + return ImagePalette(mode, palette) + + +def sepia(white: str = "#fff0c0") -> ImagePalette: + bands = [make_linear_lut(0, band) for band in ImageColor.getrgb(white)] + return ImagePalette("RGB", [bands[i % 3][i // 3] for i in range(256 * 3)]) + + +def wedge(mode: str = "RGB") -> ImagePalette: + palette = list(range(256 * len(mode))) + return ImagePalette(mode, [i // len(mode) for i in palette]) + + +def load(filename: str) -> tuple[bytes, str]: + # FIXME: supports GIMP gradients only + + with open(filename, "rb") as fp: + paletteHandlers: list[ + type[ + GimpPaletteFile.GimpPaletteFile + | GimpGradientFile.GimpGradientFile + | PaletteFile.PaletteFile + ] + ] = [ + GimpPaletteFile.GimpPaletteFile, + GimpGradientFile.GimpGradientFile, + PaletteFile.PaletteFile, + ] + for paletteHandler in paletteHandlers: + try: + fp.seek(0) + lut = paletteHandler(fp).getpalette() + if lut: + break + except (SyntaxError, ValueError): + pass + else: + msg = "cannot load palette" + raise OSError(msg) + + return lut # data, rawmode diff --git a/.venv/lib/python3.11/site-packages/PIL/ImagePath.py b/.venv/lib/python3.11/site-packages/PIL/ImagePath.py new file mode 100644 index 0000000000000000000000000000000000000000..77e8a609a552ae7d8c6b87e78a36ecbfc1cdce89 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/ImagePath.py @@ -0,0 +1,20 @@ +# +# The Python Imaging Library +# $Id$ +# +# path interface +# +# History: +# 1996-11-04 fl Created +# 2002-04-14 fl Added documentation stub class +# +# Copyright (c) Secret Labs AB 1997. +# Copyright (c) Fredrik Lundh 1996. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +from . import Image + +Path = Image.core.path diff --git a/.venv/lib/python3.11/site-packages/PIL/ImageQt.py b/.venv/lib/python3.11/site-packages/PIL/ImageQt.py new file mode 100644 index 0000000000000000000000000000000000000000..af4d0742d6bc5f434cf47ae7a629bf08e23fd3a2 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/ImageQt.py @@ -0,0 +1,219 @@ +# +# The Python Imaging Library. +# $Id$ +# +# a simple Qt image interface. +# +# history: +# 2006-06-03 fl: created +# 2006-06-04 fl: inherit from QImage instead of wrapping it +# 2006-06-05 fl: removed toimage helper; move string support to ImageQt +# 2013-11-13 fl: add support for Qt5 (aurelien.ballier@cyclonit.com) +# +# Copyright (c) 2006 by Secret Labs AB +# Copyright (c) 2006 by Fredrik Lundh +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import sys +from io import BytesIO + +from . import Image +from ._util import is_path + +TYPE_CHECKING = False +if TYPE_CHECKING: + from collections.abc import Callable + from typing import Any + + from . import ImageFile + + QBuffer: type + +qt_version: str | None +qt_versions = [ + ["6", "PyQt6"], + ["side6", "PySide6"], +] + +# If a version has already been imported, attempt it first +qt_versions.sort(key=lambda version: version[1] in sys.modules, reverse=True) +for version, qt_module in qt_versions: + try: + qRgba: Callable[[int, int, int, int], int] + if qt_module == "PyQt6": + from PyQt6.QtCore import QBuffer, QByteArray, QIODevice + from PyQt6.QtGui import QImage, QPixmap, qRgba + elif qt_module == "PySide6": + from PySide6.QtCore import ( # type: ignore[assignment] + QBuffer, + QByteArray, + QIODevice, + ) + from PySide6.QtGui import QImage, QPixmap, qRgba # type: ignore[assignment] + except (ImportError, RuntimeError): + continue + qt_is_installed = True + qt_version = version + break +else: + qt_is_installed = False + qt_version = None + + +def rgb(r: int, g: int, b: int, a: int = 255) -> int: + """(Internal) Turns an RGB color into a Qt compatible color integer.""" + # use qRgb to pack the colors, and then turn the resulting long + # into a negative integer with the same bitpattern. + return qRgba(r, g, b, a) & 0xFFFFFFFF + + +def fromqimage(im: QImage | QPixmap) -> ImageFile.ImageFile: + """ + :param im: QImage or PIL ImageQt object + """ + buffer = QBuffer() + qt_openmode: object + if qt_version == "6": + try: + qt_openmode = getattr(QIODevice, "OpenModeFlag") + except AttributeError: + qt_openmode = getattr(QIODevice, "OpenMode") + else: + qt_openmode = QIODevice + buffer.open(getattr(qt_openmode, "ReadWrite")) + # preserve alpha channel with png + # otherwise ppm is more friendly with Image.open + if im.hasAlphaChannel(): + im.save(buffer, "png") + else: + im.save(buffer, "ppm") + + b = BytesIO() + b.write(buffer.data()) + buffer.close() + b.seek(0) + + return Image.open(b) + + +def fromqpixmap(im: QPixmap) -> ImageFile.ImageFile: + return fromqimage(im) + + +def align8to32(bytes: bytes, width: int, mode: str) -> bytes: + """ + converts each scanline of data from 8 bit to 32 bit aligned + """ + + bits_per_pixel = {"1": 1, "L": 8, "P": 8, "I;16": 16}[mode] + + # calculate bytes per line and the extra padding if needed + bits_per_line = bits_per_pixel * width + full_bytes_per_line, remaining_bits_per_line = divmod(bits_per_line, 8) + bytes_per_line = full_bytes_per_line + (1 if remaining_bits_per_line else 0) + + extra_padding = -bytes_per_line % 4 + + # already 32 bit aligned by luck + if not extra_padding: + return bytes + + new_data = [ + bytes[i * bytes_per_line : (i + 1) * bytes_per_line] + b"\x00" * extra_padding + for i in range(len(bytes) // bytes_per_line) + ] + + return b"".join(new_data) + + +def _toqclass_helper(im: Image.Image | str | QByteArray) -> dict[str, Any]: + data = None + colortable = None + exclusive_fp = False + + # handle filename, if given instead of image name + if hasattr(im, "toUtf8"): + # FIXME - is this really the best way to do this? + im = str(im.toUtf8(), "utf-8") + if is_path(im): + im = Image.open(im) + exclusive_fp = True + assert isinstance(im, Image.Image) + + qt_format = getattr(QImage, "Format") if qt_version == "6" else QImage + if im.mode == "1": + format = getattr(qt_format, "Format_Mono") + elif im.mode == "L": + format = getattr(qt_format, "Format_Indexed8") + colortable = [rgb(i, i, i) for i in range(256)] + elif im.mode == "P": + format = getattr(qt_format, "Format_Indexed8") + palette = im.getpalette() + assert palette is not None + colortable = [rgb(*palette[i : i + 3]) for i in range(0, len(palette), 3)] + elif im.mode == "RGB": + # Populate the 4th channel with 255 + im = im.convert("RGBA") + + data = im.tobytes("raw", "BGRA") + format = getattr(qt_format, "Format_RGB32") + elif im.mode == "RGBA": + data = im.tobytes("raw", "BGRA") + format = getattr(qt_format, "Format_ARGB32") + elif im.mode == "I;16": + im = im.point(lambda i: i * 256) + + format = getattr(qt_format, "Format_Grayscale16") + else: + if exclusive_fp: + im.close() + msg = f"unsupported image mode {repr(im.mode)}" + raise ValueError(msg) + + size = im.size + __data = data or align8to32(im.tobytes(), size[0], im.mode) + if exclusive_fp: + im.close() + return {"data": __data, "size": size, "format": format, "colortable": colortable} + + +if qt_is_installed: + + class ImageQt(QImage): + def __init__(self, im: Image.Image | str | QByteArray) -> None: + """ + An PIL image wrapper for Qt. This is a subclass of PyQt's QImage + class. + + :param im: A PIL Image object, or a file name (given either as + Python string or a PyQt string object). + """ + im_data = _toqclass_helper(im) + # must keep a reference, or Qt will crash! + # All QImage constructors that take data operate on an existing + # buffer, so this buffer has to hang on for the life of the image. + # Fixes https://github.com/python-pillow/Pillow/issues/1370 + self.__data = im_data["data"] + super().__init__( + self.__data, + im_data["size"][0], + im_data["size"][1], + im_data["format"], + ) + if im_data["colortable"]: + self.setColorTable(im_data["colortable"]) + + +def toqimage(im: Image.Image | str | QByteArray) -> ImageQt: + return ImageQt(im) + + +def toqpixmap(im: Image.Image | str | QByteArray) -> QPixmap: + qimage = toqimage(im) + pixmap = getattr(QPixmap, "fromImage")(qimage) + if qt_version == "6": + pixmap.detach() + return pixmap diff --git a/.venv/lib/python3.11/site-packages/PIL/ImageSequence.py b/.venv/lib/python3.11/site-packages/PIL/ImageSequence.py new file mode 100644 index 0000000000000000000000000000000000000000..361be48971e0446ef39e2428b613f75951e04e87 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/ImageSequence.py @@ -0,0 +1,88 @@ +# +# The Python Imaging Library. +# $Id$ +# +# sequence support classes +# +# history: +# 1997-02-20 fl Created +# +# Copyright (c) 1997 by Secret Labs AB. +# Copyright (c) 1997 by Fredrik Lundh. +# +# See the README file for information on usage and redistribution. +# + +## +from __future__ import annotations + +from . import Image + +TYPE_CHECKING = False +if TYPE_CHECKING: + from collections.abc import Callable + + +class Iterator: + """ + This class implements an iterator object that can be used to loop + over an image sequence. + + You can use the ``[]`` operator to access elements by index. This operator + will raise an :py:exc:`IndexError` if you try to access a nonexistent + frame. + + :param im: An image object. + """ + + def __init__(self, im: Image.Image) -> None: + if not hasattr(im, "seek"): + msg = "im must have seek method" + raise AttributeError(msg) + self.im = im + self.position = getattr(self.im, "_min_frame", 0) + + def __getitem__(self, ix: int) -> Image.Image: + try: + self.im.seek(ix) + return self.im + except EOFError as e: + msg = "end of sequence" + raise IndexError(msg) from e + + def __iter__(self) -> Iterator: + return self + + def __next__(self) -> Image.Image: + try: + self.im.seek(self.position) + self.position += 1 + return self.im + except EOFError as e: + msg = "end of sequence" + raise StopIteration(msg) from e + + +def all_frames( + im: Image.Image | list[Image.Image], + func: Callable[[Image.Image], Image.Image] | None = None, +) -> list[Image.Image]: + """ + Applies a given function to all frames in an image or a list of images. + The frames are returned as a list of separate images. + + :param im: An image, or a list of images. + :param func: The function to apply to all of the image frames. + :returns: A list of images. + """ + if not isinstance(im, list): + im = [im] + + ims = [] + for imSequence in im: + current = imSequence.tell() + + ims += [im_frame.copy() for im_frame in Iterator(imSequence)] + + imSequence.seek(current) + return [func(im) for im in ims] if func else ims diff --git a/.venv/lib/python3.11/site-packages/PIL/ImageShow.py b/.venv/lib/python3.11/site-packages/PIL/ImageShow.py new file mode 100644 index 0000000000000000000000000000000000000000..dd8aa0d36c25d470477a2aa23960babd3b782c55 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/ImageShow.py @@ -0,0 +1,367 @@ +# +# The Python Imaging Library. +# $Id$ +# +# im.show() drivers +# +# History: +# 2008-04-06 fl Created +# +# Copyright (c) Secret Labs AB 2008. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import abc +import os +import shutil +import subprocess +import sys +from shlex import quote +from typing import Any + +from . import Image + +_viewers: list[Viewer] = [] + + +def register(viewer: type[Viewer] | Viewer, order: int = 1) -> None: + """ + The :py:func:`register` function is used to register additional viewers:: + + from PIL import ImageShow + ImageShow.register(MyViewer()) # MyViewer will be used as a last resort + ImageShow.register(MySecondViewer(), 0) # MySecondViewer will be prioritised + ImageShow.register(ImageShow.XVViewer(), 0) # XVViewer will be prioritised + + :param viewer: The viewer to be registered. + :param order: + Zero or a negative integer to prepend this viewer to the list, + a positive integer to append it. + """ + if isinstance(viewer, type) and issubclass(viewer, Viewer): + viewer = viewer() + if order > 0: + _viewers.append(viewer) + else: + _viewers.insert(0, viewer) + + +def show(image: Image.Image, title: str | None = None, **options: Any) -> bool: + r""" + Display a given image. + + :param image: An image object. + :param title: Optional title. Not all viewers can display the title. + :param \**options: Additional viewer options. + :returns: ``True`` if a suitable viewer was found, ``False`` otherwise. + """ + for viewer in _viewers: + if viewer.show(image, title=title, **options): + return True + return False + + +class Viewer: + """Base class for viewers.""" + + # main api + + def show(self, image: Image.Image, **options: Any) -> int: + """ + The main function for displaying an image. + Converts the given image to the target format and displays it. + """ + + if not ( + image.mode in ("1", "RGBA") + or (self.format == "PNG" and image.mode in ("I;16", "LA")) + ): + base = Image.getmodebase(image.mode) + if image.mode != base: + image = image.convert(base) + + return self.show_image(image, **options) + + # hook methods + + format: str | None = None + """The format to convert the image into.""" + options: dict[str, Any] = {} + """Additional options used to convert the image.""" + + def get_format(self, image: Image.Image) -> str | None: + """Return format name, or ``None`` to save as PGM/PPM.""" + return self.format + + def get_command(self, file: str, **options: Any) -> str: + """ + Returns the command used to display the file. + Not implemented in the base class. + """ + msg = "unavailable in base viewer" + raise NotImplementedError(msg) + + def save_image(self, image: Image.Image) -> str: + """Save to temporary file and return filename.""" + return image._dump(format=self.get_format(image), **self.options) + + def show_image(self, image: Image.Image, **options: Any) -> int: + """Display the given image.""" + return self.show_file(self.save_image(image), **options) + + def show_file(self, path: str, **options: Any) -> int: + """ + Display given file. + """ + if not os.path.exists(path): + raise FileNotFoundError + os.system(self.get_command(path, **options)) # nosec + return 1 + + def _remove_path_after_delay(self, path: str) -> None: + pyinstaller = getattr(sys, "frozen", False) and hasattr(sys, "_MEIPASS") + executable = (not pyinstaller and sys.executable) or shutil.which("python3") + + if executable: + subprocess.Popen( + [ + executable, + "-c", + "import os, sys, time; time.sleep(20); os.remove(sys.argv[1])", + path, + ] + ) + + +# -------------------------------------------------------------------- + + +class WindowsViewer(Viewer): + """The default viewer on Windows is the default system application for PNG files.""" + + format = "PNG" + options = {"compress_level": 1, "save_all": True} + + def get_command(self, file: str, **options: Any) -> str: + if '"' in file: + msg = "Windows filenames cannot contain double quotes" + raise ValueError(msg) + file = file.replace("%", '"%"') + return ( + f'start "Pillow" /WAIT "{file}" ' + "&& ping -n 4 127.0.0.1 >NUL " + f'&& del /f "{file}"' + ) + + def show_file(self, path: str, **options: Any) -> int: + """ + Display given file. + """ + if not os.path.exists(path): + raise FileNotFoundError + if sys.platform == "win32": + os.startfile(path) + self._remove_path_after_delay(path) + return 1 + + +if sys.platform == "win32": + register(WindowsViewer) + + +class MacViewer(Viewer): + """The default viewer on macOS using ``Preview.app``.""" + + format = "PNG" + options = {"compress_level": 1, "save_all": True} + + def get_command(self, file: str, **options: Any) -> str: + # on darwin open returns immediately resulting in the temp + # file removal while app is opening + command = "open -a Preview.app" + command = f"({command} {quote(file)}; sleep 20; rm -f {quote(file)})&" + return command + + def show_file(self, path: str, **options: Any) -> int: + """ + Display given file. + """ + if not os.path.exists(path): + raise FileNotFoundError + subprocess.call(["open", "-a", "Preview.app", path]) + self._remove_path_after_delay(path) + return 1 + + +if sys.platform == "darwin": + register(MacViewer) + + +class UnixViewer(abc.ABC, Viewer): + format = "PNG" + options = {"compress_level": 1, "save_all": True} + + @abc.abstractmethod + def get_command_ex(self, file: str, **options: Any) -> tuple[str, str]: + pass + + def get_command(self, file: str, **options: Any) -> str: + command = self.get_command_ex(file, **options)[0] + return f"{command} {quote(file)}" + + +class XDGViewer(UnixViewer): + """ + The freedesktop.org ``xdg-open`` command. + """ + + def get_command_ex(self, file: str, **options: Any) -> tuple[str, str]: + command = executable = "xdg-open" + return command, executable + + def show_file(self, path: str, **options: Any) -> int: + """ + Display given file. + """ + if not os.path.exists(path): + raise FileNotFoundError + subprocess.Popen(["xdg-open", path]) + return 1 + + +class DisplayViewer(UnixViewer): + """ + The ImageMagick ``display`` command. + This viewer supports the ``title`` parameter. + """ + + def get_command_ex( + self, file: str, title: str | None = None, **options: Any + ) -> tuple[str, str]: + command = executable = "display" + if title: + command += f" -title {quote(title)}" + return command, executable + + def show_file(self, path: str, **options: Any) -> int: + """ + Display given file. + """ + if not os.path.exists(path): + raise FileNotFoundError + args = ["display"] + title = options.get("title") + if title: + args += ["-title", title] + args.append(path) + + subprocess.Popen(args) + return 1 + + +class GmDisplayViewer(UnixViewer): + """The GraphicsMagick ``gm display`` command.""" + + def get_command_ex(self, file: str, **options: Any) -> tuple[str, str]: + executable = "gm" + command = "gm display" + return command, executable + + def show_file(self, path: str, **options: Any) -> int: + """ + Display given file. + """ + if not os.path.exists(path): + raise FileNotFoundError + subprocess.Popen(["gm", "display", path]) + return 1 + + +class EogViewer(UnixViewer): + """The GNOME Image Viewer ``eog`` command.""" + + def get_command_ex(self, file: str, **options: Any) -> tuple[str, str]: + executable = "eog" + command = "eog -n" + return command, executable + + def show_file(self, path: str, **options: Any) -> int: + """ + Display given file. + """ + if not os.path.exists(path): + raise FileNotFoundError + subprocess.Popen(["eog", "-n", path]) + return 1 + + +class XVViewer(UnixViewer): + """ + The X Viewer ``xv`` command. + This viewer supports the ``title`` parameter. + """ + + def get_command_ex( + self, file: str, title: str | None = None, **options: Any + ) -> tuple[str, str]: + # note: xv is pretty outdated. most modern systems have + # imagemagick's display command instead. + command = executable = "xv" + if title: + command += f" -name {quote(title)}" + return command, executable + + def show_file(self, path: str, **options: Any) -> int: + """ + Display given file. + """ + if not os.path.exists(path): + raise FileNotFoundError + args = ["xv"] + title = options.get("title") + if title: + args += ["-name", title] + args.append(path) + + subprocess.Popen(args) + return 1 + + +if sys.platform not in ("win32", "darwin"): # unixoids + if shutil.which("xdg-open"): + register(XDGViewer) + if shutil.which("display"): + register(DisplayViewer) + if shutil.which("gm"): + register(GmDisplayViewer) + if shutil.which("eog"): + register(EogViewer) + if shutil.which("xv"): + register(XVViewer) + + +class IPythonViewer(Viewer): + """The viewer for IPython frontends.""" + + def show_image(self, image: Image.Image, **options: Any) -> int: + ipython_display(image) + return 1 + + +try: + from IPython.display import display as ipython_display +except ImportError: + pass +else: + register(IPythonViewer) + + +if __name__ == "__main__": + if len(sys.argv) < 2: + print("Syntax: python3 ImageShow.py imagefile [title]") + sys.exit() + + with Image.open(sys.argv[1]) as im: + print(show(im, *sys.argv[2:])) diff --git a/.venv/lib/python3.11/site-packages/PIL/ImageStat.py b/.venv/lib/python3.11/site-packages/PIL/ImageStat.py new file mode 100644 index 0000000000000000000000000000000000000000..3a1044ba449408cd038e81bb4f6cc45a2149e3ce --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/ImageStat.py @@ -0,0 +1,167 @@ +# +# The Python Imaging Library. +# $Id$ +# +# global image statistics +# +# History: +# 1996-04-05 fl Created +# 1997-05-21 fl Added mask; added rms, var, stddev attributes +# 1997-08-05 fl Added median +# 1998-07-05 hk Fixed integer overflow error +# +# Notes: +# This class shows how to implement delayed evaluation of attributes. +# To get a certain value, simply access the corresponding attribute. +# The __getattr__ dispatcher takes care of the rest. +# +# Copyright (c) Secret Labs AB 1997. +# Copyright (c) Fredrik Lundh 1996-97. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import math +from functools import cached_property + +from . import Image + + +class Stat: + def __init__( + self, image_or_list: Image.Image | list[int], mask: Image.Image | None = None + ) -> None: + """ + Calculate statistics for the given image. If a mask is included, + only the regions covered by that mask are included in the + statistics. You can also pass in a previously calculated histogram. + + :param image: A PIL image, or a precalculated histogram. + + .. note:: + + For a PIL image, calculations rely on the + :py:meth:`~PIL.Image.Image.histogram` method. The pixel counts are + grouped into 256 bins, even if the image has more than 8 bits per + channel. So ``I`` and ``F`` mode images have a maximum ``mean``, + ``median`` and ``rms`` of 255, and cannot have an ``extrema`` maximum + of more than 255. + + :param mask: An optional mask. + """ + if isinstance(image_or_list, Image.Image): + self.h = image_or_list.histogram(mask) + elif isinstance(image_or_list, list): + self.h = image_or_list + else: + msg = "first argument must be image or list" # type: ignore[unreachable] + raise TypeError(msg) + self.bands = list(range(len(self.h) // 256)) + + @cached_property + def extrema(self) -> list[tuple[int, int]]: + """ + Min/max values for each band in the image. + + .. note:: + This relies on the :py:meth:`~PIL.Image.Image.histogram` method, and + simply returns the low and high bins used. This is correct for + images with 8 bits per channel, but fails for other modes such as + ``I`` or ``F``. Instead, use :py:meth:`~PIL.Image.Image.getextrema` to + return per-band extrema for the image. This is more correct and + efficient because, for non-8-bit modes, the histogram method uses + :py:meth:`~PIL.Image.Image.getextrema` to determine the bins used. + """ + + def minmax(histogram: list[int]) -> tuple[int, int]: + res_min, res_max = 255, 0 + for i in range(256): + if histogram[i]: + res_min = i + break + for i in range(255, -1, -1): + if histogram[i]: + res_max = i + break + return res_min, res_max + + return [minmax(self.h[i:]) for i in range(0, len(self.h), 256)] + + @cached_property + def count(self) -> list[int]: + """Total number of pixels for each band in the image.""" + return [sum(self.h[i : i + 256]) for i in range(0, len(self.h), 256)] + + @cached_property + def sum(self) -> list[float]: + """Sum of all pixels for each band in the image.""" + + v = [] + for i in range(0, len(self.h), 256): + layer_sum = 0.0 + for j in range(256): + layer_sum += j * self.h[i + j] + v.append(layer_sum) + return v + + @cached_property + def sum2(self) -> list[float]: + """Squared sum of all pixels for each band in the image.""" + + v = [] + for i in range(0, len(self.h), 256): + sum2 = 0.0 + for j in range(256): + sum2 += (j**2) * float(self.h[i + j]) + v.append(sum2) + return v + + @cached_property + def mean(self) -> list[float]: + """Average (arithmetic mean) pixel level for each band in the image.""" + return [self.sum[i] / self.count[i] if self.count[i] else 0 for i in self.bands] + + @cached_property + def median(self) -> list[int]: + """Median pixel level for each band in the image.""" + + v = [] + for i in self.bands: + s = 0 + half = self.count[i] // 2 + b = i * 256 + for j in range(256): + s = s + self.h[b + j] + if s > half: + break + v.append(j) + return v + + @cached_property + def rms(self) -> list[float]: + """RMS (root-mean-square) for each band in the image.""" + return [ + math.sqrt(self.sum2[i] / self.count[i]) if self.count[i] else 0 + for i in self.bands + ] + + @cached_property + def var(self) -> list[float]: + """Variance for each band in the image.""" + return [ + ( + (self.sum2[i] - (self.sum[i] ** 2.0) / self.count[i]) / self.count[i] + if self.count[i] + else 0 + ) + for i in self.bands + ] + + @cached_property + def stddev(self) -> list[float]: + """Standard deviation for each band in the image.""" + return [math.sqrt(self.var[i]) for i in self.bands] + + +Global = Stat # compatibility diff --git a/.venv/lib/python3.11/site-packages/PIL/ImageText.py b/.venv/lib/python3.11/site-packages/PIL/ImageText.py new file mode 100644 index 0000000000000000000000000000000000000000..96601813ce0b47d4ae4c2304ad0eab9cbd597b5e --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/ImageText.py @@ -0,0 +1,509 @@ +from __future__ import annotations + +import math +import re +from typing import AnyStr, Generic, NamedTuple + +from . import ImageFont +from ._typing import _Ink + + +class _Line(NamedTuple): + x: float + y: float + anchor: str + text: str | bytes + + +class _Wrap(Generic[AnyStr]): + lines: list[AnyStr] = [] + position = 0 + offset = 0 + + def __init__( + self, + text: Text[AnyStr], + width: int, + height: int | None = None, + font: ImageFont.BaseImageFont | None = None, + ) -> None: + self.text: Text[AnyStr] = text + self.width = width + self.height = height + self.font = font + + input_text = self.text.text + emptystring = "" if isinstance(input_text, str) else b"" + line = emptystring + + for word in re.findall( + r"\s*\S+" if isinstance(input_text, str) else rb"\s*\S+", input_text + ): + newlines = re.findall( + r"[^\S\n]*\n" if isinstance(input_text, str) else rb"[^\S\n]*\n", word + ) + if newlines: + if not self.add_line(line): + break + for i, line in enumerate(newlines): + if i != 0 and not self.add_line(emptystring): + break + self.position += len(line) + word = word[len(line) :] + line = emptystring + + new_line = line + word + if self.text._get_bbox(new_line, self.font)[2] <= width: + # This word fits on the line + line = new_line + continue + + # This word does not fit on the line + if line and not self.add_line(line): + break + + original_length = len(word) + word = word.lstrip() + self.offset = original_length - len(word) + + if self.text._get_bbox(word, self.font)[2] > width: + if font is None: + msg = "Word does not fit within line" + raise ValueError(msg) + break + line = word + else: + if line: + self.add_line(line) + self.remaining_text: AnyStr = input_text[self.position :] + + def add_line(self, line: AnyStr) -> bool: + lines = self.lines + [line] + if self.height is not None: + last_line_y = self.text._split(lines=lines)[-1].y + last_line_height = self.text._get_bbox(line, self.font)[3] + if last_line_y + last_line_height > self.height: + return False + + self.lines = lines + self.position += len(line) + self.offset + self.offset = 0 + return True + + +class Text(Generic[AnyStr]): + def __init__( + self, + text: AnyStr, + font: ImageFont.BaseImageFont | None = None, + mode: str = "RGB", + spacing: float = 4, + direction: str | None = None, + features: list[str] | None = None, + language: str | None = None, + ) -> None: + """ + :param text: String to be drawn. + :param font: Either an :py:class:`~PIL.ImageFont.ImageFont` instance, + :py:class:`~PIL.ImageFont.FreeTypeFont` instance, + :py:class:`~PIL.ImageFont.TransposedFont` instance or ``None``. If + ``None``, the default font from :py:meth:`.ImageFont.load_default` + will be used. + :param mode: The image mode this will be used with. + :param spacing: The number of pixels between lines. + :param direction: Direction of the text. It can be ``"rtl"`` (right to left), + ``"ltr"`` (left to right) or ``"ttb"`` (top to bottom). + Requires libraqm. + :param features: A list of OpenType font features to be used during text + layout. This is usually used to turn on optional font features + that are not enabled by default, for example ``"dlig"`` or + ``"ss01"``, but can be also used to turn off default font + features, for example ``"-liga"`` to disable ligatures or + ``"-kern"`` to disable kerning. To get all supported + features, see `OpenType docs`_. + Requires libraqm. + :param language: Language of the text. Different languages may use + different glyph shapes or ligatures. This parameter tells + the font which language the text is in, and to apply the + correct substitutions as appropriate, if available. + It should be a `BCP 47 language code`_. + Requires libraqm. + """ + self.text: AnyStr = text + self.font = font or ImageFont.load_default() + + self.mode = mode + self.spacing = spacing + self.direction = direction + self.features = features + self.language = language + + self.embedded_color = False + + self.stroke_width: float = 0 + self.stroke_fill: _Ink | None = None + + def embed_color(self) -> None: + """ + Use embedded color glyphs (COLR, CBDT, SBIX). + """ + if self.mode not in ("RGB", "RGBA"): + msg = "Embedded color supported only in RGB and RGBA modes" + raise ValueError(msg) + self.embedded_color = True + + def stroke(self, width: float = 0, fill: _Ink | None = None) -> None: + """ + :param width: The width of the text stroke. + :param fill: Color to use for the text stroke when drawing. If not given, will + default to the ``fill`` parameter from + :py:meth:`.ImageDraw.ImageDraw.text`. + """ + self.stroke_width = width + self.stroke_fill = fill + + def _get_fontmode(self) -> str: + if self.mode in ("1", "P", "I", "F"): + return "1" + elif self.embedded_color: + return "RGBA" + else: + return "L" + + def wrap( + self, + width: int, + height: int | None = None, + scaling: str | tuple[str, int] | None = None, + ) -> Text[AnyStr] | None: + """ + Wrap text to fit within a given width. + + :param width: The width to fit within. + :param height: An optional height limit. Any text that does not fit within this + will be returned as a new :py:class:`.Text` object. + :param scaling: An optional directive to scale the text, either "grow" as much + as possible within the given dimensions, or "shrink" until it + fits. It can also be a tuple of (direction, limit), with an + integer limit to stop scaling at. + + :returns: An :py:class:`.Text` object, or None. + """ + if isinstance(self.font, ImageFont.TransposedFont): + msg = "TransposedFont not supported" + raise ValueError(msg) + if self.direction not in (None, "ltr"): + msg = "Only ltr direction supported" + raise ValueError(msg) + + if scaling is None: + wrap = _Wrap(self, width, height) + else: + if not isinstance(self.font, ImageFont.FreeTypeFont): + msg = "'scaling' only supports FreeTypeFont" + raise ValueError(msg) + if height is None: + msg = "'scaling' requires 'height'" + raise ValueError(msg) + + if isinstance(scaling, str): + limit = 1 + else: + scaling, limit = scaling + + font = self.font + wrap = _Wrap(self, width, height, font) + if scaling == "shrink": + if not wrap.remaining_text: + return None + + size = math.ceil(font.size) + while wrap.remaining_text: + if size == max(limit, 1): + msg = "Text could not be scaled" + raise ValueError(msg) + size -= 1 + font = self.font.font_variant(size=size) + wrap = _Wrap(self, width, height, font) + self.font = font + else: + if wrap.remaining_text: + msg = "Text could not be scaled" + raise ValueError(msg) + + size = math.floor(font.size) + while not wrap.remaining_text: + if size == limit: + msg = "Text could not be scaled" + raise ValueError(msg) + size += 1 + font = self.font.font_variant(size=size) + last_wrap = wrap + wrap = _Wrap(self, width, height, font) + size -= 1 + if size != self.font.size: + self.font = self.font.font_variant(size=size) + wrap = last_wrap + + if wrap.remaining_text: + text = Text( + text=wrap.remaining_text, + font=self.font, + mode=self.mode, + spacing=self.spacing, + direction=self.direction, + features=self.features, + language=self.language, + ) + text.embedded_color = self.embedded_color + text.stroke_width = self.stroke_width + text.stroke_fill = self.stroke_fill + else: + text = None + + newline = "\n" if isinstance(self.text, str) else b"\n" + self.text = newline.join(wrap.lines) + return text + + def get_length(self) -> float: + """ + Returns length (in pixels with 1/64 precision) of text. + + This is the amount by which following text should be offset. + Text bounding box may extend past the length in some fonts, + e.g. when using italics or accents. + + The result is returned as a float; it is a whole number if using basic layout. + + Note that the sum of two lengths may not equal the length of a concatenated + string due to kerning. If you need to adjust for kerning, include the following + character and subtract its length. + + For example, instead of:: + + hello = ImageText.Text("Hello", font).get_length() + world = ImageText.Text("World", font).get_length() + helloworld = ImageText.Text("HelloWorld", font).get_length() + assert hello + world == helloworld + + use:: + + hello = ( + ImageText.Text("HelloW", font).get_length() - + ImageText.Text("W", font).get_length() + ) # adjusted for kerning + world = ImageText.Text("World", font).get_length() + helloworld = ImageText.Text("HelloWorld", font).get_length() + assert hello + world == helloworld + + or disable kerning with (requires libraqm):: + + hello = ImageText.Text("Hello", font, features=["-kern"]).get_length() + world = ImageText.Text("World", font, features=["-kern"]).get_length() + helloworld = ImageText.Text( + "HelloWorld", font, features=["-kern"] + ).get_length() + assert hello + world == helloworld + + :return: Either width for horizontal text, or height for vertical text. + """ + if isinstance(self.text, str): + multiline = "\n" in self.text + else: + multiline = b"\n" in self.text + if multiline: + msg = "can't measure length of multiline text" + raise ValueError(msg) + return self.font.getlength( + self.text, + self._get_fontmode(), + self.direction, + self.features, + self.language, + ) + + def _split( + self, + xy: tuple[float, float] = (0, 0), + anchor: str | None = None, + align: str = "left", + lines: list[str] | list[bytes] | None = None, + ) -> list[_Line]: + if anchor is None: + anchor = "lt" if self.direction == "ttb" else "la" + elif len(anchor) != 2: + msg = "anchor must be a 2 character string" + raise ValueError(msg) + + if lines is None: + lines = ( + self.text.split("\n") + if isinstance(self.text, str) + else self.text.split(b"\n") + ) + if len(lines) == 1: + return [_Line(xy[0], xy[1], anchor, lines[0])] + + if anchor[1] in "tb" and self.direction != "ttb": + msg = "anchor not supported for multiline text" + raise ValueError(msg) + + fontmode = self._get_fontmode() + line_spacing = ( + self.font.getbbox( + "A", + fontmode, + None, + self.features, + self.language, + self.stroke_width, + )[3] + + self.stroke_width + + self.spacing + ) + + top = xy[1] + parts = [] + if self.direction == "ttb": + left = xy[0] + for line in lines: + parts.append(_Line(left, top, anchor, line)) + left += line_spacing + else: + widths = [] + max_width: float = 0 + for line in lines: + line_width = self.font.getlength( + line, fontmode, self.direction, self.features, self.language + ) + widths.append(line_width) + max_width = max(max_width, line_width) + + if anchor[1] == "m": + top -= (len(lines) - 1) * line_spacing / 2.0 + elif anchor[1] == "d": + top -= (len(lines) - 1) * line_spacing + + idx = -1 + for line in lines: + left = xy[0] + idx += 1 + width_difference = max_width - widths[idx] + + # align by align parameter + if align in ("left", "justify"): + pass + elif align == "center": + left += width_difference / 2.0 + elif align == "right": + left += width_difference + else: + msg = 'align must be "left", "center", "right" or "justify"' + raise ValueError(msg) + + if ( + align == "justify" + and width_difference != 0 + and idx != len(lines) - 1 + ): + words = ( + line.split(" ") if isinstance(line, str) else line.split(b" ") + ) + if len(words) > 1: + # align left by anchor + if anchor[0] == "m": + left -= max_width / 2.0 + elif anchor[0] == "r": + left -= max_width + + word_widths = [ + self.font.getlength( + word, + fontmode, + self.direction, + self.features, + self.language, + ) + for word in words + ] + word_anchor = "l" + anchor[1] + width_difference = max_width - sum(word_widths) + i = 0 + for word in words: + parts.append(_Line(left, top, word_anchor, word)) + left += word_widths[i] + width_difference / (len(words) - 1) + i += 1 + top += line_spacing + continue + + # align left by anchor + if anchor[0] == "m": + left -= width_difference / 2.0 + elif anchor[0] == "r": + left -= width_difference + parts.append(_Line(left, top, anchor, line)) + top += line_spacing + + return parts + + def _get_bbox( + self, + text: str | bytes, + font: ImageFont.BaseImageFont | None = None, + anchor: str | None = None, + ) -> tuple[float, float, float, float]: + return (font or self.font).getbbox( + text, + self._get_fontmode(), + self.direction, + self.features, + self.language, + self.stroke_width, + anchor, + ) + + def get_bbox( + self, + xy: tuple[float, float] = (0, 0), + anchor: str | None = None, + align: str = "left", + ) -> tuple[float, float, float, float]: + """ + Returns bounding box (in pixels) of text. + + Use :py:meth:`get_length` to get the offset of following text with 1/64 pixel + precision. The bounding box includes extra margins for some fonts, e.g. italics + or accents. + + :param xy: The anchor coordinates of the text. + :param anchor: The text anchor alignment. Determines the relative location of + the anchor to the text. The default alignment is top left, + specifically ``la`` for horizontal text and ``lt`` for + vertical text. See :ref:`text-anchors` for details. + :param align: For multiline text, ``"left"``, ``"center"``, ``"right"`` or + ``"justify"`` determines the relative alignment of lines. Use the + ``anchor`` parameter to specify the alignment to ``xy``. + + :return: ``(left, top, right, bottom)`` bounding box + """ + bbox: tuple[float, float, float, float] | None = None + for x, y, anchor, text in self._split(xy, anchor, align): + bbox_line = self._get_bbox(text, anchor=anchor) + bbox_line = ( + bbox_line[0] + x, + bbox_line[1] + y, + bbox_line[2] + x, + bbox_line[3] + y, + ) + if bbox is None: + bbox = bbox_line + else: + bbox = ( + min(bbox[0], bbox_line[0]), + min(bbox[1], bbox_line[1]), + max(bbox[2], bbox_line[2]), + max(bbox[3], bbox_line[3]), + ) + + assert bbox is not None + return bbox diff --git a/.venv/lib/python3.11/site-packages/PIL/ImageTk.py b/.venv/lib/python3.11/site-packages/PIL/ImageTk.py new file mode 100644 index 0000000000000000000000000000000000000000..3a4cb81e9ef5ef4abe617d4a364074c2203571ad --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/ImageTk.py @@ -0,0 +1,266 @@ +# +# The Python Imaging Library. +# $Id$ +# +# a Tk display interface +# +# History: +# 96-04-08 fl Created +# 96-09-06 fl Added getimage method +# 96-11-01 fl Rewritten, removed image attribute and crop method +# 97-05-09 fl Use PyImagingPaste method instead of image type +# 97-05-12 fl Minor tweaks to match the IFUNC95 interface +# 97-05-17 fl Support the "pilbitmap" booster patch +# 97-06-05 fl Added file= and data= argument to image constructors +# 98-03-09 fl Added width and height methods to Image classes +# 98-07-02 fl Use default mode for "P" images without palette attribute +# 98-07-02 fl Explicitly destroy Tkinter image objects +# 99-07-24 fl Support multiple Tk interpreters (from Greg Couch) +# 99-07-26 fl Automatically hook into Tkinter (if possible) +# 99-08-15 fl Hook uses _imagingtk instead of _imaging +# +# Copyright (c) 1997-1999 by Secret Labs AB +# Copyright (c) 1996-1997 by Fredrik Lundh +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import tkinter +from io import BytesIO +from typing import Any + +from . import Image, ImageFile + +TYPE_CHECKING = False +if TYPE_CHECKING: + from ._typing import CapsuleType + +# -------------------------------------------------------------------- +# Check for Tkinter interface hooks + + +def _get_image_from_kw(kw: dict[str, Any]) -> ImageFile.ImageFile | None: + source = None + if "file" in kw: + source = kw.pop("file") + elif "data" in kw: + source = BytesIO(kw.pop("data")) + if not source: + return None + return Image.open(source) + + +def _pyimagingtkcall( + command: str, photo: PhotoImage | tkinter.PhotoImage, ptr: CapsuleType +) -> None: + tk = photo.tk + try: + tk.call(command, photo, repr(ptr)) + except tkinter.TclError: + # activate Tkinter hook + # may raise an error if it cannot attach to Tkinter + from . import _imagingtk + + _imagingtk.tkinit(tk.interpaddr()) + tk.call(command, photo, repr(ptr)) + + +# -------------------------------------------------------------------- +# PhotoImage + + +class PhotoImage: + """ + A Tkinter-compatible photo image. This can be used + everywhere Tkinter expects an image object. If the image is an RGBA + image, pixels having alpha 0 are treated as transparent. + + The constructor takes either a PIL image, or a mode and a size. + Alternatively, you can use the ``file`` or ``data`` options to initialize + the photo image object. + + :param image: Either a PIL image, or a mode string. If a mode string is + used, a size must also be given. + :param size: If the first argument is a mode string, this defines the size + of the image. + :keyword file: A filename to load the image from (using + ``Image.open(file)``). + :keyword data: An 8-bit string containing image data (as loaded from an + image file). + """ + + def __init__( + self, + image: Image.Image | str | None = None, + size: tuple[int, int] | None = None, + **kw: Any, + ) -> None: + # Tk compatibility: file or data + if image is None: + image = _get_image_from_kw(kw) + + if image is None: + msg = "Image is required" + raise ValueError(msg) + elif isinstance(image, str): + mode = image + image = None + + if size is None: + msg = "If first argument is mode, size is required" + raise ValueError(msg) + else: + # got an image instead of a mode + mode = image.mode + if mode == "P": + # palette mapped data + image.apply_transparency() + image.load() + mode = image.palette.mode if image.palette else "RGB" + size = image.size + kw["width"], kw["height"] = size + + if mode not in ["1", "L", "RGB", "RGBA"]: + mode = Image.getmodebase(mode) + + self.__mode = mode + self.__size = size + self.__photo = tkinter.PhotoImage(**kw) + self.tk = self.__photo.tk + if image: + self.paste(image) + + def __del__(self) -> None: + try: + name = self.__photo.name + except AttributeError: + return + self.__photo.name = None + try: + self.__photo.tk.call("image", "delete", name) + except Exception: + pass # ignore internal errors + + def __str__(self) -> str: + """ + Get the Tkinter photo image identifier. This method is automatically + called by Tkinter whenever a PhotoImage object is passed to a Tkinter + method. + + :return: A Tkinter photo image identifier (a string). + """ + return str(self.__photo) + + def width(self) -> int: + """ + Get the width of the image. + + :return: The width, in pixels. + """ + return self.__size[0] + + def height(self) -> int: + """ + Get the height of the image. + + :return: The height, in pixels. + """ + return self.__size[1] + + def paste(self, im: Image.Image) -> None: + """ + Paste a PIL image into the photo image. Note that this can + be very slow if the photo image is displayed. + + :param im: A PIL image. The size must match the target region. If the + mode does not match, the image is converted to the mode of + the bitmap image. + """ + # convert to blittable + ptr = im.getim() + image = im.im + if not image.isblock() or im.mode != self.__mode: + block = Image.core.new_block(self.__mode, im.size) + image.convert2(block, image) # convert directly between buffers + ptr = block.ptr + + _pyimagingtkcall("PyImagingPhoto", self.__photo, ptr) + + +# -------------------------------------------------------------------- +# BitmapImage + + +class BitmapImage: + """ + A Tkinter-compatible bitmap image. This can be used everywhere Tkinter + expects an image object. + + The given image must have mode "1". Pixels having value 0 are treated as + transparent. Options, if any, are passed on to Tkinter. The most commonly + used option is ``foreground``, which is used to specify the color for the + non-transparent parts. See the Tkinter documentation for information on + how to specify colours. + + :param image: A PIL image. + """ + + def __init__(self, image: Image.Image | None = None, **kw: Any) -> None: + # Tk compatibility: file or data + if image is None: + image = _get_image_from_kw(kw) + + if image is None: + msg = "Image is required" + raise ValueError(msg) + self.__mode = image.mode + self.__size = image.size + + self.__photo = tkinter.BitmapImage(data=image.tobitmap(), **kw) + + def __del__(self) -> None: + try: + name = self.__photo.name + except AttributeError: + return + self.__photo.name = None + try: + self.__photo.tk.call("image", "delete", name) + except Exception: + pass # ignore internal errors + + def width(self) -> int: + """ + Get the width of the image. + + :return: The width, in pixels. + """ + return self.__size[0] + + def height(self) -> int: + """ + Get the height of the image. + + :return: The height, in pixels. + """ + return self.__size[1] + + def __str__(self) -> str: + """ + Get the Tkinter bitmap image identifier. This method is automatically + called by Tkinter whenever a BitmapImage object is passed to a Tkinter + method. + + :return: A Tkinter bitmap image identifier (a string). + """ + return str(self.__photo) + + +def getimage(photo: PhotoImage) -> Image.Image: + """Copies the contents of a PhotoImage to a PIL image memory.""" + im = Image.new("RGBA", (photo.width(), photo.height())) + + _pyimagingtkcall("PyImagingPhotoGet", photo, im.getim()) + + return im diff --git a/.venv/lib/python3.11/site-packages/PIL/ImageTransform.py b/.venv/lib/python3.11/site-packages/PIL/ImageTransform.py new file mode 100644 index 0000000000000000000000000000000000000000..fb144ff38a1ee7ff77cc01f3b941756a60b2b4cd --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/ImageTransform.py @@ -0,0 +1,136 @@ +# +# The Python Imaging Library. +# $Id$ +# +# transform wrappers +# +# History: +# 2002-04-08 fl Created +# +# Copyright (c) 2002 by Secret Labs AB +# Copyright (c) 2002 by Fredrik Lundh +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +from collections.abc import Sequence +from typing import Any + +from . import Image + + +class Transform(Image.ImageTransformHandler): + """Base class for other transforms defined in :py:mod:`~PIL.ImageTransform`.""" + + method: Image.Transform + + def __init__(self, data: Sequence[Any]) -> None: + self.data = data + + def getdata(self) -> tuple[Image.Transform, Sequence[int]]: + return self.method, self.data + + def transform( + self, + size: tuple[int, int], + image: Image.Image, + **options: Any, + ) -> Image.Image: + """Perform the transform. Called from :py:meth:`.Image.transform`.""" + # can be overridden + method, data = self.getdata() + return image.transform(size, method, data, **options) + + +class AffineTransform(Transform): + """ + Define an affine image transform. + + This function takes a 6-tuple (a, b, c, d, e, f) which contain the first + two rows from the inverse of an affine transform matrix. For each pixel + (x, y) in the output image, the new value is taken from a position (a x + + b y + c, d x + e y + f) in the input image, rounded to nearest pixel. + + This function can be used to scale, translate, rotate, and shear the + original image. + + See :py:meth:`.Image.transform` + + :param matrix: A 6-tuple (a, b, c, d, e, f) containing the first two rows + from the inverse of an affine transform matrix. + """ + + method = Image.Transform.AFFINE + + +class PerspectiveTransform(Transform): + """ + Define a perspective image transform. + + This function takes an 8-tuple (a, b, c, d, e, f, g, h). For each pixel + (x, y) in the output image, the new value is taken from a position + ((a x + b y + c) / (g x + h y + 1), (d x + e y + f) / (g x + h y + 1)) in + the input image, rounded to nearest pixel. + + This function can be used to scale, translate, rotate, and shear the + original image. + + See :py:meth:`.Image.transform` + + :param matrix: An 8-tuple (a, b, c, d, e, f, g, h). + """ + + method = Image.Transform.PERSPECTIVE + + +class ExtentTransform(Transform): + """ + Define a transform to extract a subregion from an image. + + Maps a rectangle (defined by two corners) from the image to a rectangle of + the given size. The resulting image will contain data sampled from between + the corners, such that (x0, y0) in the input image will end up at (0,0) in + the output image, and (x1, y1) at size. + + This method can be used to crop, stretch, shrink, or mirror an arbitrary + rectangle in the current image. It is slightly slower than crop, but about + as fast as a corresponding resize operation. + + See :py:meth:`.Image.transform` + + :param bbox: A 4-tuple (x0, y0, x1, y1) which specifies two points in the + input image's coordinate system. See :ref:`coordinate-system`. + """ + + method = Image.Transform.EXTENT + + +class QuadTransform(Transform): + """ + Define a quad image transform. + + Maps a quadrilateral (a region defined by four corners) from the image to a + rectangle of the given size. + + See :py:meth:`.Image.transform` + + :param xy: An 8-tuple (x0, y0, x1, y1, x2, y2, x3, y3) which contain the + upper left, lower left, lower right, and upper right corner of the + source quadrilateral. + """ + + method = Image.Transform.QUAD + + +class MeshTransform(Transform): + """ + Define a mesh image transform. A mesh transform consists of one or more + individual quad transforms. + + See :py:meth:`.Image.transform` + + :param data: A list of (bbox, quad) tuples. + """ + + method = Image.Transform.MESH diff --git a/.venv/lib/python3.11/site-packages/PIL/ImageWin.py b/.venv/lib/python3.11/site-packages/PIL/ImageWin.py new file mode 100644 index 0000000000000000000000000000000000000000..29263617d0bab1989cc516c1a4b24e6546fdf6ff --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/ImageWin.py @@ -0,0 +1,247 @@ +# +# The Python Imaging Library. +# $Id$ +# +# a Windows DIB display interface +# +# History: +# 1996-05-20 fl Created +# 1996-09-20 fl Fixed subregion exposure +# 1997-09-21 fl Added draw primitive (for tzPrint) +# 2003-05-21 fl Added experimental Window/ImageWindow classes +# 2003-09-05 fl Added fromstring/tostring methods +# +# Copyright (c) Secret Labs AB 1997-2003. +# Copyright (c) Fredrik Lundh 1996-2003. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +from . import Image + + +class HDC: + """ + Wraps an HDC integer. The resulting object can be passed to the + :py:meth:`~PIL.ImageWin.Dib.draw` and :py:meth:`~PIL.ImageWin.Dib.expose` + methods. + """ + + def __init__(self, dc: int) -> None: + self.dc = dc + + def __int__(self) -> int: + return self.dc + + +class HWND: + """ + Wraps an HWND integer. The resulting object can be passed to the + :py:meth:`~PIL.ImageWin.Dib.draw` and :py:meth:`~PIL.ImageWin.Dib.expose` + methods, instead of a DC. + """ + + def __init__(self, wnd: int) -> None: + self.wnd = wnd + + def __int__(self) -> int: + return self.wnd + + +class Dib: + """ + A Windows bitmap with the given mode and size. The mode can be one of "1", + "L", "P", or "RGB". + + If the display requires a palette, this constructor creates a suitable + palette and associates it with the image. For an "L" image, 128 graylevels + are allocated. For an "RGB" image, a 6x6x6 colour cube is used, together + with 20 graylevels. + + To make sure that palettes work properly under Windows, you must call the + ``palette`` method upon certain events from Windows. + + :param image: Either a PIL image, or a mode string. If a mode string is + used, a size must also be given. The mode can be one of "1", + "L", "P", or "RGB". + :param size: If the first argument is a mode string, this + defines the size of the image. + """ + + def __init__( + self, image: Image.Image | str, size: tuple[int, int] | None = None + ) -> None: + if isinstance(image, str): + mode = image + image = "" + if size is None: + msg = "If first argument is mode, size is required" + raise ValueError(msg) + else: + mode = image.mode + size = image.size + if mode not in ["1", "L", "P", "RGB"]: + mode = Image.getmodebase(mode) + self.image = Image.core.display(mode, size) + self.mode = mode + self.size = size + if image: + assert not isinstance(image, str) + self.paste(image) + + def expose(self, handle: int | HDC | HWND) -> None: + """ + Copy the bitmap contents to a device context. + + :param handle: Device context (HDC), cast to a Python integer, or an + HDC or HWND instance. In PythonWin, you can use + ``CDC.GetHandleAttrib()`` to get a suitable handle. + """ + handle_int = int(handle) + if isinstance(handle, HWND): + dc = self.image.getdc(handle_int) + try: + self.image.expose(dc) + finally: + self.image.releasedc(handle_int, dc) + else: + self.image.expose(handle_int) + + def draw( + self, + handle: int | HDC | HWND, + dst: tuple[int, int, int, int], + src: tuple[int, int, int, int] | None = None, + ) -> None: + """ + Same as expose, but allows you to specify where to draw the image, and + what part of it to draw. + + The destination and source areas are given as 4-tuple rectangles. If + the source is omitted, the entire image is copied. If the source and + the destination have different sizes, the image is resized as + necessary. + """ + if src is None: + src = (0, 0) + self.size + handle_int = int(handle) + if isinstance(handle, HWND): + dc = self.image.getdc(handle_int) + try: + self.image.draw(dc, dst, src) + finally: + self.image.releasedc(handle_int, dc) + else: + self.image.draw(handle_int, dst, src) + + def query_palette(self, handle: int | HDC | HWND) -> int: + """ + Installs the palette associated with the image in the given device + context. + + This method should be called upon **QUERYNEWPALETTE** and + **PALETTECHANGED** events from Windows. If this method returns a + non-zero value, one or more display palette entries were changed, and + the image should be redrawn. + + :param handle: Device context (HDC), cast to a Python integer, or an + HDC or HWND instance. + :return: The number of entries that were changed (if one or more entries, + this indicates that the image should be redrawn). + """ + handle_int = int(handle) + if isinstance(handle, HWND): + handle = self.image.getdc(handle_int) + try: + result = self.image.query_palette(handle) + finally: + self.image.releasedc(handle, handle) + else: + result = self.image.query_palette(handle_int) + return result + + def paste( + self, im: Image.Image, box: tuple[int, int, int, int] | None = None + ) -> None: + """ + Paste a PIL image into the bitmap image. + + :param im: A PIL image. The size must match the target region. + If the mode does not match, the image is converted to the + mode of the bitmap image. + :param box: A 4-tuple defining the left, upper, right, and + lower pixel coordinate. See :ref:`coordinate-system`. If + None is given instead of a tuple, all of the image is + assumed. + """ + im.load() + if self.mode != im.mode: + im = im.convert(self.mode) + if box: + self.image.paste(im.im, box) + else: + self.image.paste(im.im) + + def frombytes(self, buffer: bytes | memoryview) -> None: + """ + Load display memory contents from byte data. + + :param buffer: A buffer containing display data (usually + data returned from :py:func:`~PIL.ImageWin.Dib.tobytes`) + """ + self.image.frombytes(buffer) + + def tobytes(self) -> bytes: + """ + Copy display memory contents to bytes object. + + :return: A bytes object containing display data. + """ + return self.image.tobytes() + + +class Window: + """Create a Window with the given title size.""" + + def __init__( + self, title: str = "PIL", width: int | None = None, height: int | None = None + ) -> None: + self.hwnd = Image.core.createwindow( + title, self.__dispatcher, width or 0, height or 0 + ) + + def __dispatcher(self, action: str, *args: int) -> None: + getattr(self, f"ui_handle_{action}")(*args) + + def ui_handle_clear(self, dc: int, x0: int, y0: int, x1: int, y1: int) -> None: + pass + + def ui_handle_damage(self, x0: int, y0: int, x1: int, y1: int) -> None: + pass + + def ui_handle_destroy(self) -> None: + pass + + def ui_handle_repair(self, dc: int, x0: int, y0: int, x1: int, y1: int) -> None: + pass + + def ui_handle_resize(self, width: int, height: int) -> None: + pass + + def mainloop(self) -> None: + Image.core.eventloop() + + +class ImageWindow(Window): + """Create an image window which displays the given image.""" + + def __init__(self, image: Image.Image | Dib, title: str = "PIL") -> None: + if not isinstance(image, Dib): + image = Dib(image) + self.image = image + width, height = image.size + super().__init__(title, width=width, height=height) + + def ui_handle_repair(self, dc: int, x0: int, y0: int, x1: int, y1: int) -> None: + self.image.draw(dc, (x0, y0, x1, y1)) diff --git a/.venv/lib/python3.11/site-packages/PIL/ImtImagePlugin.py b/.venv/lib/python3.11/site-packages/PIL/ImtImagePlugin.py new file mode 100644 index 0000000000000000000000000000000000000000..c4eccee3423dc6c273bdc1ea88eda5ef4e17cf7d --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/ImtImagePlugin.py @@ -0,0 +1,103 @@ +# +# The Python Imaging Library. +# $Id$ +# +# IM Tools support for PIL +# +# history: +# 1996-05-27 fl Created (read 8-bit images only) +# 2001-02-17 fl Use 're' instead of 'regex' (Python 2.1) (0.2) +# +# Copyright (c) Secret Labs AB 1997-2001. +# Copyright (c) Fredrik Lundh 1996-2001. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import re + +from . import Image, ImageFile + +# +# -------------------------------------------------------------------- + +field = re.compile(rb"([a-z]*) ([^ \r\n]*)") + + +## +# Image plugin for IM Tools images. + + +class ImtImageFile(ImageFile.ImageFile): + format = "IMT" + format_description = "IM Tools" + + def _open(self) -> None: + # Quick rejection: if there's not a LF among the first + # 100 bytes, this is (probably) not a text header. + + assert self.fp is not None + + buffer = self.fp.read(100) + if b"\n" not in buffer: + msg = "not an IM file" + raise SyntaxError(msg) + + xsize = ysize = 0 + + while True: + if buffer: + s = buffer[:1] + buffer = buffer[1:] + else: + s = self.fp.read(1) + if not s: + break + + if s == b"\x0c": + # image data begins + self.tile = [ + ImageFile._Tile( + "raw", + (0, 0) + self.size, + self.fp.tell() - len(buffer), + self.mode, + ) + ] + + break + + else: + # read key/value pair + if b"\n" not in buffer: + buffer += self.fp.read(100) + lines = buffer.split(b"\n") + s += lines.pop(0) + buffer = b"\n".join(lines) + if len(s) == 1 or len(s) > 100: + break + if s[0] == ord(b"*"): + continue # comment + + m = field.match(s) + if not m: + break + k, v = m.group(1, 2) + if k == b"width": + xsize = int(v) + self._size = xsize, ysize + elif k == b"height": + ysize = int(v) + self._size = xsize, ysize + elif k == b"pixel" and v == b"n8": + self._mode = "L" + + +# +# -------------------------------------------------------------------- + +Image.register_open(ImtImageFile.format, ImtImageFile) + +# +# no extension registered (".im" is simply too common) diff --git a/.venv/lib/python3.11/site-packages/PIL/IptcImagePlugin.py b/.venv/lib/python3.11/site-packages/PIL/IptcImagePlugin.py new file mode 100644 index 0000000000000000000000000000000000000000..9c8be8b4e36021e625a88a8f8157f69ec5c40dab --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/IptcImagePlugin.py @@ -0,0 +1,226 @@ +# +# The Python Imaging Library. +# $Id$ +# +# IPTC/NAA file handling +# +# history: +# 1995-10-01 fl Created +# 1998-03-09 fl Cleaned up and added to PIL +# 2002-06-18 fl Added getiptcinfo helper +# +# Copyright (c) Secret Labs AB 1997-2002. +# Copyright (c) Fredrik Lundh 1995. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +from io import BytesIO +from typing import cast + +from . import Image, ImageFile +from ._binary import i16be as i16 +from ._binary import i32be as i32 + +COMPRESSION = {1: "raw", 5: "jpeg"} + + +# +# Helpers + + +def _i(c: bytes) -> int: + return i32((b"\0\0\0\0" + c)[-4:]) + + +## +# Image plugin for IPTC/NAA datastreams. To read IPTC/NAA fields +# from TIFF and JPEG files, use the getiptcinfo function. + + +class IptcImageFile(ImageFile.ImageFile): + format = "IPTC" + format_description = "IPTC/NAA" + + def getint(self, key: tuple[int, int]) -> int: + return _i(self.info[key]) + + def field(self) -> tuple[tuple[int, int] | None, int]: + # + # get a IPTC field header + assert self.fp is not None + s = self.fp.read(5) + if not s.strip(b"\x00"): + return None, 0 + + tag = s[1], s[2] + + # syntax + if s[0] != 0x1C or tag[0] not in [1, 2, 3, 4, 5, 6, 7, 8, 9, 240]: + msg = "invalid IPTC/NAA file" + raise SyntaxError(msg) + + # field size + size = s[3] + if size > 132: + msg = "illegal field length in IPTC/NAA file" + raise OSError(msg) + elif size == 128: + size = 0 + elif size > 128: + size = _i(self.fp.read(size - 128)) + else: + size = i16(s, 3) + + return tag, size + + def _open(self) -> None: + # load descriptive fields + assert self.fp is not None + while True: + offset = self.fp.tell() + tag, size = self.field() + if not tag or tag == (8, 10): + break + if size: + tagdata = self.fp.read(size) + else: + tagdata = None + if tag in self.info: + if isinstance(self.info[tag], list): + self.info[tag].append(tagdata) + else: + self.info[tag] = [self.info[tag], tagdata] + else: + self.info[tag] = tagdata + + # mode + layers = self.info[(3, 60)][0] + component = self.info[(3, 60)][1] + if layers == 1 and not component: + self._mode = "L" + band = None + else: + if layers == 3 and component: + self._mode = "RGB" + elif layers == 4 and component: + self._mode = "CMYK" + if (3, 65) in self.info: + band = self.info[(3, 65)][0] - 1 + else: + band = 0 + + # size + self._size = self.getint((3, 20)), self.getint((3, 30)) + + # compression + try: + compression = COMPRESSION[self.getint((3, 120))] + except KeyError as e: + msg = "Unknown IPTC image compression" + raise OSError(msg) from e + + # tile + if tag == (8, 10): + self.tile = [ + ImageFile._Tile("iptc", (0, 0) + self.size, offset, (compression, band)) + ] + + def load(self) -> Image.core.PixelAccess | None: + if self.tile: + args = self.tile[0].args + assert isinstance(args, tuple) + compression, band = args + + assert self.fp is not None + self.fp.seek(self.tile[0].offset) + + # Copy image data to temporary file + o = BytesIO() + if compression == "raw": + # To simplify access to the extracted file, + # prepend a PPM header + o.write(b"P5\n%d %d\n255\n" % self.size) + while True: + type, size = self.field() + if type != (8, 10): + break + while size > 0: + s = self.fp.read(min(size, 8192)) + if not s: + break + o.write(s) + size -= len(s) + + with Image.open(o) as _im: + if band is not None: + bands = [Image.new("L", _im.size)] * Image.getmodebands(self.mode) + bands[band] = _im + im = Image.merge(self.mode, bands) + else: + im = _im + im.load() + self.im = im.im + self.tile = [] + return ImageFile.ImageFile.load(self) + + +Image.register_open(IptcImageFile.format, IptcImageFile) + +Image.register_extension(IptcImageFile.format, ".iim") + + +def getiptcinfo( + im: ImageFile.ImageFile, +) -> dict[tuple[int, int], bytes | list[bytes]] | None: + """ + Get IPTC information from TIFF, JPEG, or IPTC file. + + :param im: An image containing IPTC data. + :returns: A dictionary containing IPTC information, or None if + no IPTC information block was found. + """ + from . import JpegImagePlugin, TiffImagePlugin + + data = None + + if isinstance(im, IptcImageFile): + # return info dictionary right away + return {k: v for k, v in im.info.items() if isinstance(k, tuple)} + + elif isinstance(im, JpegImagePlugin.JpegImageFile): + # extract the IPTC/NAA resource + photoshop = im.info.get("photoshop") + if photoshop: + data = photoshop.get(0x0404) + + elif isinstance(im, TiffImagePlugin.TiffImageFile): + # get raw data from the IPTC/NAA tag (PhotoShop tags the data + # as 4-byte integers, so we cannot use the get method...) + try: + data = im.tag_v2._tagdata[TiffImagePlugin.IPTC_NAA_CHUNK] + except KeyError: + pass + + if data is None: + return None # no properties + + # create an IptcImagePlugin object without initializing it + class FakeImage: + pass + + fake_im = FakeImage() + fake_im.__class__ = IptcImageFile # type: ignore[assignment] + iptc_im = cast(IptcImageFile, fake_im) + + # parse the IPTC information chunk + iptc_im.info = {} + iptc_im.fp = BytesIO(data) + + try: + iptc_im._open() + except (IndexError, KeyError): + pass # expected failure + + return {k: v for k, v in iptc_im.info.items() if isinstance(k, tuple)} diff --git a/.venv/lib/python3.11/site-packages/PIL/Jpeg2KImagePlugin.py b/.venv/lib/python3.11/site-packages/PIL/Jpeg2KImagePlugin.py new file mode 100644 index 0000000000000000000000000000000000000000..ca982f06aa5707b51b7393c8e4ca234bc3f76099 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/Jpeg2KImagePlugin.py @@ -0,0 +1,466 @@ +# +# The Python Imaging Library +# $Id$ +# +# JPEG2000 file handling +# +# History: +# 2014-03-12 ajh Created +# 2021-06-30 rogermb Extract dpi information from the 'resc' header box +# +# Copyright (c) 2014 Coriolis Systems Limited +# Copyright (c) 2014 Alastair Houghton +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import io +import os +import struct +from typing import cast + +from . import Image, ImageFile, ImagePalette, _binary + +TYPE_CHECKING = False +if TYPE_CHECKING: + from collections.abc import Callable + from typing import IO + + +class BoxReader: + """ + A small helper class to read fields stored in JPEG2000 header boxes + and to easily step into and read sub-boxes. + """ + + def __init__(self, fp: IO[bytes], length: int = -1) -> None: + self.fp = fp + self.has_length = length >= 0 + self.length = length + self.remaining_in_box = -1 + + def _can_read(self, num_bytes: int) -> bool: + if self.has_length and self.fp.tell() + num_bytes > self.length: + # Outside box: ensure we don't read past the known file length + return False + if self.remaining_in_box >= 0: + # Inside box contents: ensure read does not go past box boundaries + return num_bytes <= self.remaining_in_box + else: + return True # No length known, just read + + def _read_bytes(self, num_bytes: int) -> bytes: + if not self._can_read(num_bytes): + msg = "Not enough data in header" + raise SyntaxError(msg) + + data = self.fp.read(num_bytes) + if len(data) < num_bytes: + msg = f"Expected to read {num_bytes} bytes but only got {len(data)}." + raise OSError(msg) + + if self.remaining_in_box > 0: + self.remaining_in_box -= num_bytes + return data + + def read_fields(self, field_format: str) -> tuple[int | bytes, ...]: + size = struct.calcsize(field_format) + data = self._read_bytes(size) + return struct.unpack(field_format, data) + + def read_boxes(self) -> BoxReader: + size = self.remaining_in_box + data = self._read_bytes(size) + return BoxReader(io.BytesIO(data), size) + + def has_next_box(self) -> bool: + if self.has_length: + return self.fp.tell() + self.remaining_in_box < self.length + else: + return True + + def next_box_type(self) -> bytes: + # Skip the rest of the box if it has not been read + if self.remaining_in_box > 0: + self.fp.seek(self.remaining_in_box, os.SEEK_CUR) + self.remaining_in_box = -1 + + # Read the length and type of the next box + lbox, tbox = cast(tuple[int, bytes], self.read_fields(">I4s")) + if lbox == 1: + lbox = cast(int, self.read_fields(">Q")[0]) + hlen = 16 + else: + hlen = 8 + + if lbox < hlen or not self._can_read(lbox - hlen): + msg = "Invalid header length" + raise SyntaxError(msg) + + self.remaining_in_box = lbox - hlen + return tbox + + +def _parse_codestream(fp: IO[bytes]) -> tuple[tuple[int, int], str]: + """Parse the JPEG 2000 codestream to extract the size and component + count from the SIZ marker segment, returning a PIL (size, mode) tuple.""" + + hdr = fp.read(2) + lsiz = _binary.i16be(hdr) + if lsiz < 38: + msg = "SIZ marker length must be at least 38" + raise ValueError(msg) + siz = hdr + fp.read(lsiz - 2) + lsiz, rsiz, xsiz, ysiz, xosiz, yosiz, _, _, _, _, csiz = struct.unpack_from( + ">HHIIIIIIIIH", siz + ) + + size = (xsiz - xosiz, ysiz - yosiz) + if csiz == 1: + ssiz = struct.unpack_from(">B", siz, 38) + if (ssiz[0] & 0x7F) + 1 > 8: + mode = "I;16" + else: + mode = "L" + elif csiz == 2: + mode = "LA" + elif csiz == 3: + mode = "RGB" + elif csiz == 4: + mode = "RGBA" + else: + msg = "unable to determine J2K image mode" + raise SyntaxError(msg) + + return size, mode + + +def _res_to_dpi(num: int, denom: int, exp: int) -> float | None: + """Convert JPEG2000's (numerator, denominator, exponent-base-10) resolution, + calculated as (num / denom) * 10^exp and stored in dots per meter, + to floating-point dots per inch.""" + if denom == 0: + return None + return (254 * num * (10**exp)) / (10000 * denom) + + +def _parse_jp2_header( + fp: IO[bytes], +) -> tuple[ + tuple[int, int], + str, + str | None, + tuple[float, float] | None, + ImagePalette.ImagePalette | None, +]: + """Parse the JP2 header box to extract size, component count, + color space information, and optionally DPI information, + returning a (size, mode, mimetype, dpi) tuple.""" + + # Find the JP2 header box + reader = BoxReader(fp) + header = None + mimetype = None + while reader.has_next_box(): + tbox = reader.next_box_type() + + if tbox == b"jp2h": + header = reader.read_boxes() + break + elif tbox == b"ftyp": + if reader.read_fields(">4s")[0] == b"jpx ": + mimetype = "image/jpx" + assert header is not None + + size = None + mode = None + bpc = None + nc = None + dpi = None # 2-tuple of DPI info, or None + palette = None + colr = None + + while header.has_next_box(): + tbox = header.next_box_type() + + if tbox == b"ihdr": + height, width, nc, bpc = header.read_fields(">IIHB") + assert isinstance(height, int) + assert isinstance(width, int) + assert isinstance(bpc, int) + size = (width, height) + if nc == 1 and (bpc & 0x7F) > 8: + mode = "I;16" + elif nc == 1: + mode = "L" + elif nc == 2: + mode = "LA" + elif nc == 3: + mode = "RGB" + elif nc == 4: + mode = "RGBA" + elif tbox == b"colr": + meth, _, _, enumcs = header.read_fields(">BBBI") + if meth == 1: + if enumcs in (0, 15): + colr = "1" + elif enumcs == 12: + colr = "CMYK" + if nc == 4: + mode = "CMYK" + elif enumcs == 17: + colr = "L" + elif tbox == b"pclr" and mode in ("L", "LA") and colr not in ("1", "L"): + ne, npc = header.read_fields(">HB") + assert isinstance(ne, int) + assert isinstance(npc, int) + max_bitdepth = 0 + for bitdepth in header.read_fields(">" + ("B" * npc)): + assert isinstance(bitdepth, int) + if bitdepth > max_bitdepth: + max_bitdepth = bitdepth + if max_bitdepth <= 8: + if npc == 4: + palette_mode = "CMYK" if colr == "CMYK" else "RGBA" + else: + palette_mode = "RGB" + palette = ImagePalette.ImagePalette(palette_mode) + for i in range(ne): + color: list[int] = [] + for value in header.read_fields(">" + ("B" * npc)): + assert isinstance(value, int) + color.append(value) + palette.getcolor(tuple(color)) + mode = "P" if mode == "L" else "PA" + elif tbox == b"res ": + res = header.read_boxes() + while res.has_next_box(): + tres = res.next_box_type() + if tres == b"resc": + vrcn, vrcd, hrcn, hrcd, vrce, hrce = res.read_fields(">HHHHBB") + assert isinstance(vrcn, int) + assert isinstance(vrcd, int) + assert isinstance(hrcn, int) + assert isinstance(hrcd, int) + assert isinstance(vrce, int) + assert isinstance(hrce, int) + hres = _res_to_dpi(hrcn, hrcd, hrce) + vres = _res_to_dpi(vrcn, vrcd, vrce) + if hres is not None and vres is not None: + dpi = (hres, vres) + break + + if size is None or mode is None: + msg = "Malformed JP2 header" + raise SyntaxError(msg) + + return size, mode, mimetype, dpi, palette + + +## +# Image plugin for JPEG2000 images. + + +class Jpeg2KImageFile(ImageFile.ImageFile): + format = "JPEG2000" + format_description = "JPEG 2000 (ISO 15444)" + + def _open(self) -> None: + assert self.fp is not None + sig = self.fp.read(4) + if sig == b"\xff\x4f\xff\x51": + self.codec = "j2k" + self._size, self._mode = _parse_codestream(self.fp) + self._parse_comment() + else: + sig = sig + self.fp.read(8) + + if sig == b"\x00\x00\x00\x0cjP \x0d\x0a\x87\x0a": + self.codec = "jp2" + header = _parse_jp2_header(self.fp) + self._size, self._mode, self.custom_mimetype, dpi, self.palette = header + if dpi is not None: + self.info["dpi"] = dpi + if self.fp.read(12).endswith(b"jp2c\xff\x4f\xff\x51"): + hdr = self.fp.read(2) + length = _binary.i16be(hdr) + self.fp.seek(length - 2, os.SEEK_CUR) + self._parse_comment() + else: + msg = "not a JPEG 2000 file" + raise SyntaxError(msg) + + self._reduce = 0 + self.layers = 0 + + fd = -1 + length = -1 + + try: + fd = self.fp.fileno() + length = os.fstat(fd).st_size + except Exception: + fd = -1 + try: + pos = self.fp.tell() + self.fp.seek(0, io.SEEK_END) + length = self.fp.tell() + self.fp.seek(pos) + except Exception: + length = -1 + + self.tile = [ + ImageFile._Tile( + "jpeg2k", + (0, 0) + self.size, + 0, + (self.codec, self._reduce, self.layers, fd, length), + ) + ] + + def _parse_comment(self) -> None: + assert self.fp is not None + while True: + marker = self.fp.read(2) + if not marker: + break + typ = marker[1] + if typ in (0x90, 0xD9): + # Start of tile or end of codestream + break + hdr = self.fp.read(2) + length = _binary.i16be(hdr) + if length < 2: + msg = "Marker length too small" + raise ValueError(msg) + if typ == 0x64: + # Comment + self.info["comment"] = self.fp.read(length - 2)[2:] + break + else: + self.fp.seek(length - 2, os.SEEK_CUR) + + @property # type: ignore[override] + def reduce( + self, + ) -> ( + Callable[[int | tuple[int, int], tuple[int, int, int, int] | None], Image.Image] + | int + ): + # https://github.com/python-pillow/Pillow/issues/4343 found that the + # new Image 'reduce' method was shadowed by this plugin's 'reduce' + # property. This attempts to allow for both scenarios + return self._reduce or super().reduce + + @reduce.setter + def reduce(self, value: int) -> None: + self._reduce = value + + def load(self) -> Image.core.PixelAccess | None: + if self.tile and self._reduce: + power = 1 << self._reduce + adjust = power >> 1 + self._size = ( + int((self.size[0] + adjust) / power), + int((self.size[1] + adjust) / power), + ) + + # Update the reduce and layers settings + t = self.tile[0] + assert isinstance(t[3], tuple) + t3 = (t[3][0], self._reduce, self.layers, t[3][3], t[3][4]) + self.tile = [ImageFile._Tile(t[0], (0, 0) + self.size, t[2], t3)] + + return ImageFile.ImageFile.load(self) + + +def _accept(prefix: bytes) -> bool: + return prefix.startswith( + (b"\xff\x4f\xff\x51", b"\x00\x00\x00\x0cjP \x0d\x0a\x87\x0a") + ) + + +# ------------------------------------------------------------ +# Save support + + +def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + # Get the keyword arguments + info = im.encoderinfo + + if isinstance(filename, str): + filename = filename.encode() + if filename.endswith(b".j2k") or info.get("no_jp2", False): + kind = "j2k" + else: + kind = "jp2" + + offset = info.get("offset", None) + tile_offset = info.get("tile_offset", None) + tile_size = info.get("tile_size", None) + quality_mode = info.get("quality_mode", "rates") + quality_layers = info.get("quality_layers", None) + if quality_layers is not None and not ( + isinstance(quality_layers, (list, tuple)) + and all( + isinstance(quality_layer, (int, float)) for quality_layer in quality_layers + ) + ): + msg = "quality_layers must be a sequence of numbers" + raise ValueError(msg) + + num_resolutions = info.get("num_resolutions", 0) + cblk_size = info.get("codeblock_size", None) + precinct_size = info.get("precinct_size", None) + irreversible = info.get("irreversible", False) + progression = info.get("progression", "LRCP") + cinema_mode = info.get("cinema_mode", "no") + mct = info.get("mct", 0) + signed = info.get("signed", False) + comment = info.get("comment") + if isinstance(comment, str): + comment = comment.encode() + plt = info.get("plt", False) + + fd = -1 + if hasattr(fp, "fileno"): + try: + fd = fp.fileno() + except Exception: + fd = -1 + + im.encoderconfig = ( + offset, + tile_offset, + tile_size, + quality_mode, + quality_layers, + num_resolutions, + cblk_size, + precinct_size, + irreversible, + progression, + cinema_mode, + mct, + signed, + fd, + comment, + plt, + ) + + ImageFile._save(im, fp, [ImageFile._Tile("jpeg2k", (0, 0) + im.size, 0, kind)]) + + +# ------------------------------------------------------------ +# Registry stuff + + +Image.register_open(Jpeg2KImageFile.format, Jpeg2KImageFile, _accept) +Image.register_save(Jpeg2KImageFile.format, _save) + +Image.register_extensions( + Jpeg2KImageFile.format, [".jp2", ".j2k", ".jpc", ".jpf", ".jpx", ".j2c"] +) + +Image.register_mime(Jpeg2KImageFile.format, "image/jp2") diff --git a/.venv/lib/python3.11/site-packages/PIL/JpegImagePlugin.py b/.venv/lib/python3.11/site-packages/PIL/JpegImagePlugin.py new file mode 100644 index 0000000000000000000000000000000000000000..46320eb3b5bfa918111c58c6dc3a3c22fe823bc2 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/JpegImagePlugin.py @@ -0,0 +1,889 @@ +# +# The Python Imaging Library. +# $Id$ +# +# JPEG (JFIF) file handling +# +# See "Digital Compression and Coding of Continuous-Tone Still Images, +# Part 1, Requirements and Guidelines" (CCITT T.81 / ISO 10918-1) +# +# History: +# 1995-09-09 fl Created +# 1995-09-13 fl Added full parser +# 1996-03-25 fl Added hack to use the IJG command line utilities +# 1996-05-05 fl Workaround Photoshop 2.5 CMYK polarity bug +# 1996-05-28 fl Added draft support, JFIF version (0.1) +# 1996-12-30 fl Added encoder options, added progression property (0.2) +# 1997-08-27 fl Save mode 1 images as BW (0.3) +# 1998-07-12 fl Added YCbCr to draft and save methods (0.4) +# 1998-10-19 fl Don't hang on files using 16-bit DQT's (0.4.1) +# 2001-04-16 fl Extract DPI settings from JFIF files (0.4.2) +# 2002-07-01 fl Skip pad bytes before markers; identify Exif files (0.4.3) +# 2003-04-25 fl Added experimental EXIF decoder (0.5) +# 2003-06-06 fl Added experimental EXIF GPSinfo decoder +# 2003-09-13 fl Extract COM markers +# 2009-09-06 fl Added icc_profile support (from Florian Hoech) +# 2009-03-06 fl Changed CMYK handling; always use Adobe polarity (0.6) +# 2009-03-08 fl Added subsampling support (from Justin Huff). +# +# Copyright (c) 1997-2003 by Secret Labs AB. +# Copyright (c) 1995-1996 by Fredrik Lundh. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import array +import io +import math +import os +import struct +import subprocess +import sys +import tempfile +import warnings + +from . import Image, ImageFile +from ._binary import i16be as i16 +from ._binary import i32be as i32 +from ._binary import o8 +from ._binary import o16be as o16 +from .JpegPresets import presets + +TYPE_CHECKING = False +if TYPE_CHECKING: + from typing import IO, Any + + from .MpoImagePlugin import MpoImageFile + +# +# Parser + + +def Skip(self: JpegImageFile, marker: int) -> None: + assert self.fp is not None + n = i16(self.fp.read(2)) - 2 + ImageFile._safe_read(self.fp, n) + + +def APP(self: JpegImageFile, marker: int) -> None: + # + # Application marker. Store these in the APP dictionary. + # Also look for well-known application markers. + + assert self.fp is not None + n = i16(self.fp.read(2)) - 2 + s = ImageFile._safe_read(self.fp, n) + + app = f"APP{marker & 15}" + + self.app[app] = s # compatibility + self.applist.append((app, s)) + + if marker == 0xFFE0 and s.startswith(b"JFIF"): + # extract JFIF information + self.info["jfif"] = version = i16(s, 5) # version + self.info["jfif_version"] = divmod(version, 256) + # extract JFIF properties + try: + jfif_unit = s[7] + jfif_density = i16(s, 8), i16(s, 10) + except Exception: + pass + else: + if jfif_unit == 1: + self.info["dpi"] = jfif_density + elif jfif_unit == 2: # cm + # 1 dpcm = 2.54 dpi + self.info["dpi"] = tuple(d * 2.54 for d in jfif_density) + self.info["jfif_unit"] = jfif_unit + self.info["jfif_density"] = jfif_density + elif marker == 0xFFE1 and s.startswith(b"Exif\0\0"): + # extract EXIF information + if "exif" in self.info: + self.info["exif"] += s[6:] + else: + self.info["exif"] = s + self._exif_offset = self.fp.tell() - n + 6 + elif marker == 0xFFE1 and s.startswith(b"http://ns.adobe.com/xap/1.0/\x00"): + self.info["xmp"] = s.split(b"\x00", 1)[1] + elif marker == 0xFFE2 and s.startswith(b"FPXR\0"): + # extract FlashPix information (incomplete) + self.info["flashpix"] = s # FIXME: value will change + elif marker == 0xFFE2 and s.startswith(b"ICC_PROFILE\0"): + # Since an ICC profile can be larger than the maximum size of + # a JPEG marker (64K), we need provisions to split it into + # multiple markers. The format defined by the ICC specifies + # one or more APP2 markers containing the following data: + # Identifying string ASCII "ICC_PROFILE\0" (12 bytes) + # Marker sequence number 1, 2, etc (1 byte) + # Number of markers Total of APP2's used (1 byte) + # Profile data (remainder of APP2 data) + # Decoders should use the marker sequence numbers to + # reassemble the profile, rather than assuming that the APP2 + # markers appear in the correct sequence. + self.icclist.append(s) + elif marker == 0xFFED and s.startswith(b"Photoshop 3.0\x00"): + # parse the image resource block + offset = 14 + photoshop = self.info.setdefault("photoshop", {}) + try: + while s[offset : offset + 4] == b"8BIM": + offset += 4 + # resource code + code = i16(s, offset) + offset += 2 + # resource name (usually empty) + name_len = s[offset] + # name = s[offset+1:offset+1+name_len] + offset += 1 + name_len + offset += offset & 1 # align + # resource data block + size = i32(s, offset) + offset += 4 + data = s[offset : offset + size] + if code == 0x03ED: # ResolutionInfo + photoshop[code] = { + "XResolution": i32(data, 0) / 65536, + "DisplayedUnitsX": i16(data, 4), + "YResolution": i32(data, 8) / 65536, + "DisplayedUnitsY": i16(data, 12), + } + else: + photoshop[code] = data + offset += size + offset += offset & 1 # align + except struct.error: + pass # insufficient data + + elif marker == 0xFFEE and s.startswith(b"Adobe"): + self.info["adobe"] = i16(s, 5) + # extract Adobe custom properties + try: + adobe_transform = s[11] + except IndexError: + pass + else: + self.info["adobe_transform"] = adobe_transform + elif marker == 0xFFE2 and s.startswith(b"MPF\0"): + # extract MPO information + self.info["mp"] = s[4:] + # offset is current location minus buffer size + # plus constant header size + self.info["mpoffset"] = self.fp.tell() - n + 4 + + +def COM(self: JpegImageFile, marker: int) -> None: + # + # Comment marker. Store these in the APP dictionary. + assert self.fp is not None + n = i16(self.fp.read(2)) - 2 + s = ImageFile._safe_read(self.fp, n) + + self.info["comment"] = s + self.app["COM"] = s # compatibility + self.applist.append(("COM", s)) + + +def SOF(self: JpegImageFile, marker: int) -> None: + # + # Start of frame marker. Defines the size and mode of the + # image. JPEG is colour blind, so we use some simple + # heuristics to map the number of layers to an appropriate + # mode. Note that this could be made a bit brighter, by + # looking for JFIF and Adobe APP markers. + + assert self.fp is not None + n = i16(self.fp.read(2)) - 2 + s = ImageFile._safe_read(self.fp, n) + self._size = i16(s, 3), i16(s, 1) + if self._im is not None and self.size != self.im.size: + self._im = None + + self.bits = s[0] + if self.bits != 8: + msg = f"cannot handle {self.bits}-bit layers" + raise SyntaxError(msg) + + self.layers = s[5] + if self.layers == 1: + self._mode = "L" + elif self.layers == 3: + self._mode = "RGB" + elif self.layers == 4: + self._mode = "CMYK" + else: + msg = f"cannot handle {self.layers}-layer images" + raise SyntaxError(msg) + + if marker in [0xFFC2, 0xFFC6, 0xFFCA, 0xFFCE]: + self.info["progressive"] = self.info["progression"] = 1 + + if self.icclist: + # fixup icc profile + self.icclist.sort() # sort by sequence number + if self.icclist[0][13] == len(self.icclist): + profile = [p[14:] for p in self.icclist] + icc_profile = b"".join(profile) + else: + icc_profile = None # wrong number of fragments + self.info["icc_profile"] = icc_profile + self.icclist = [] + + for i in range(6, len(s), 3): + t = s[i : i + 3] + # 4-tuples: id, vsamp, hsamp, qtable + self.layer.append((t[0], t[1] // 16, t[1] & 15, t[2])) + + +def DQT(self: JpegImageFile, marker: int) -> None: + # + # Define quantization table. Note that there might be more + # than one table in each marker. + + # FIXME: The quantization tables can be used to estimate the + # compression quality. + + assert self.fp is not None + n = i16(self.fp.read(2)) - 2 + s = ImageFile._safe_read(self.fp, n) + while len(s): + v = s[0] + precision = 1 if (v // 16 == 0) else 2 # in bytes + qt_length = 1 + precision * 64 + if len(s) < qt_length: + msg = "bad quantization table marker" + raise SyntaxError(msg) + data = array.array("B" if precision == 1 else "H", s[1:qt_length]) + if sys.byteorder == "little" and precision > 1: + data.byteswap() # the values are always big-endian + self.quantization[v & 15] = [data[i] for i in zigzag_index] + s = s[qt_length:] + + +# +# JPEG marker table + +MARKER = { + 0xFFC0: ("SOF0", "Baseline DCT", SOF), + 0xFFC1: ("SOF1", "Extended Sequential DCT", SOF), + 0xFFC2: ("SOF2", "Progressive DCT", SOF), + 0xFFC3: ("SOF3", "Spatial lossless", SOF), + 0xFFC4: ("DHT", "Define Huffman table", Skip), + 0xFFC5: ("SOF5", "Differential sequential DCT", SOF), + 0xFFC6: ("SOF6", "Differential progressive DCT", SOF), + 0xFFC7: ("SOF7", "Differential spatial", SOF), + 0xFFC8: ("JPG", "Extension", None), + 0xFFC9: ("SOF9", "Extended sequential DCT (AC)", SOF), + 0xFFCA: ("SOF10", "Progressive DCT (AC)", SOF), + 0xFFCB: ("SOF11", "Spatial lossless DCT (AC)", SOF), + 0xFFCC: ("DAC", "Define arithmetic coding conditioning", Skip), + 0xFFCD: ("SOF13", "Differential sequential DCT (AC)", SOF), + 0xFFCE: ("SOF14", "Differential progressive DCT (AC)", SOF), + 0xFFCF: ("SOF15", "Differential spatial (AC)", SOF), + 0xFFD0: ("RST0", "Restart 0", None), + 0xFFD1: ("RST1", "Restart 1", None), + 0xFFD2: ("RST2", "Restart 2", None), + 0xFFD3: ("RST3", "Restart 3", None), + 0xFFD4: ("RST4", "Restart 4", None), + 0xFFD5: ("RST5", "Restart 5", None), + 0xFFD6: ("RST6", "Restart 6", None), + 0xFFD7: ("RST7", "Restart 7", None), + 0xFFD8: ("SOI", "Start of image", None), + 0xFFD9: ("EOI", "End of image", None), + 0xFFDA: ("SOS", "Start of scan", Skip), + 0xFFDB: ("DQT", "Define quantization table", DQT), + 0xFFDC: ("DNL", "Define number of lines", Skip), + 0xFFDD: ("DRI", "Define restart interval", Skip), + 0xFFDE: ("DHP", "Define hierarchical progression", SOF), + 0xFFDF: ("EXP", "Expand reference component", Skip), + 0xFFE0: ("APP0", "Application segment 0", APP), + 0xFFE1: ("APP1", "Application segment 1", APP), + 0xFFE2: ("APP2", "Application segment 2", APP), + 0xFFE3: ("APP3", "Application segment 3", APP), + 0xFFE4: ("APP4", "Application segment 4", APP), + 0xFFE5: ("APP5", "Application segment 5", APP), + 0xFFE6: ("APP6", "Application segment 6", APP), + 0xFFE7: ("APP7", "Application segment 7", APP), + 0xFFE8: ("APP8", "Application segment 8", APP), + 0xFFE9: ("APP9", "Application segment 9", APP), + 0xFFEA: ("APP10", "Application segment 10", APP), + 0xFFEB: ("APP11", "Application segment 11", APP), + 0xFFEC: ("APP12", "Application segment 12", APP), + 0xFFED: ("APP13", "Application segment 13", APP), + 0xFFEE: ("APP14", "Application segment 14", APP), + 0xFFEF: ("APP15", "Application segment 15", APP), + 0xFFF0: ("JPG0", "Extension 0", None), + 0xFFF1: ("JPG1", "Extension 1", None), + 0xFFF2: ("JPG2", "Extension 2", None), + 0xFFF3: ("JPG3", "Extension 3", None), + 0xFFF4: ("JPG4", "Extension 4", None), + 0xFFF5: ("JPG5", "Extension 5", None), + 0xFFF6: ("JPG6", "Extension 6", None), + 0xFFF7: ("JPG7", "Extension 7", None), + 0xFFF8: ("JPG8", "Extension 8", None), + 0xFFF9: ("JPG9", "Extension 9", None), + 0xFFFA: ("JPG10", "Extension 10", None), + 0xFFFB: ("JPG11", "Extension 11", None), + 0xFFFC: ("JPG12", "Extension 12", None), + 0xFFFD: ("JPG13", "Extension 13", None), + 0xFFFE: ("COM", "Comment", COM), +} + + +def _accept(prefix: bytes) -> bool: + # Magic number was taken from https://en.wikipedia.org/wiki/JPEG + return prefix.startswith(b"\xff\xd8\xff") + + +## +# Image plugin for JPEG and JFIF images. + + +class JpegImageFile(ImageFile.ImageFile): + format = "JPEG" + format_description = "JPEG (ISO 10918)" + + def _open(self) -> None: + assert self.fp is not None + s = self.fp.read(3) + + if not _accept(s): + msg = "not a JPEG file" + raise SyntaxError(msg) + s = b"\xff" + + # Create attributes + self.bits = self.layers = 0 + self._exif_offset = 0 + + # JPEG specifics (internal) + self.layer: list[tuple[int, int, int, int]] = [] + self._huffman_dc: dict[Any, Any] = {} + self._huffman_ac: dict[Any, Any] = {} + self.quantization: dict[int, list[int]] = {} + self.app: dict[str, bytes] = {} # compatibility + self.applist: list[tuple[str, bytes]] = [] + self.icclist: list[bytes] = [] + + while True: + i = s[0] + if i == 0xFF: + s = s + self.fp.read(1) + i = i16(s) + else: + # Skip non-0xFF junk + s = self.fp.read(1) + continue + + if i in MARKER: + name, description, handler = MARKER[i] + if handler is not None: + handler(self, i) + if i == 0xFFDA: # start of scan + rawmode = self.mode + if self.mode == "CMYK": + rawmode = "CMYK;I" # assume adobe conventions + self.tile = [ + ImageFile._Tile("jpeg", (0, 0) + self.size, 0, (rawmode, "")) + ] + # self.__offset = self.fp.tell() + break + s = self.fp.read(1) + elif i in {0, 0xFFFF}: + # padded marker or junk; move on + s = b"\xff" + elif i == 0xFF00: # Skip extraneous data (escaped 0xFF) + s = self.fp.read(1) + else: + msg = "no marker found" + raise SyntaxError(msg) + + self._read_dpi_from_exif() + + def __getstate__(self) -> list[Any]: + return super().__getstate__() + [self.layers, self.layer] + + def __setstate__(self, state: list[Any]) -> None: + self.layers, self.layer = state[6:] + super().__setstate__(state) + + def load_read(self, read_bytes: int) -> bytes: + """ + internal: read more image data + For premature EOF and LOAD_TRUNCATED_IMAGES adds EOI marker + so libjpeg can finish decoding + """ + assert self.fp is not None + s = self.fp.read(read_bytes) + + if not s and ImageFile.LOAD_TRUNCATED_IMAGES and not hasattr(self, "_ended"): + # Premature EOF. + # Pretend file is finished adding EOI marker + self._ended = True + return b"\xff\xd9" + + return s + + def draft( + self, mode: str | None, size: tuple[int, int] | None + ) -> tuple[str, tuple[int, int, float, float]] | None: + if len(self.tile) != 1: + return None + + # Protect from second call + if self.decoderconfig: + return None + + d, e, o, a = self.tile[0] + scale = 1 + original_size = self.size + + assert isinstance(a, tuple) + if a[0] == "RGB" and mode in ["L", "YCbCr"]: + self._mode = mode + a = mode, "" + + if size: + scale = min(self.size[0] // size[0], self.size[1] // size[1]) + for s in [8, 4, 2, 1]: + if scale >= s: + break + assert e is not None + e = ( + e[0], + e[1], + (e[2] - e[0] + s - 1) // s + e[0], + (e[3] - e[1] + s - 1) // s + e[1], + ) + self._size = ((self.size[0] + s - 1) // s, (self.size[1] + s - 1) // s) + scale = s + + self.tile = [ImageFile._Tile(d, e, o, a)] + self.decoderconfig = (scale, 0) + + box = (0, 0, original_size[0] / scale, original_size[1] / scale) + return self.mode, box + + def load_djpeg(self) -> None: + # ALTERNATIVE: handle JPEGs via the IJG command line utilities + + f, path = tempfile.mkstemp() + os.close(f) + if os.path.exists(self.filename): + subprocess.check_call(["djpeg", "-outfile", path, self.filename]) + else: + try: + os.unlink(path) + except OSError: + pass + + msg = "Invalid Filename" + raise ValueError(msg) + + try: + with Image.open(path) as _im: + _im.load() + self.im = _im.im + finally: + try: + os.unlink(path) + except OSError: + pass + + self._mode = self.im.mode + self._size = self.im.size + + self.tile = [] + + def _getexif(self) -> dict[int, Any] | None: + return _getexif(self) + + def _read_dpi_from_exif(self) -> None: + # If DPI isn't in JPEG header, fetch from EXIF + if "dpi" in self.info or "exif" not in self.info: + return + try: + exif = self.getexif() + resolution_unit = exif[0x0128] + x_resolution = exif[0x011A] + try: + dpi = float(x_resolution[0]) / x_resolution[1] + except TypeError: + dpi = x_resolution + if math.isnan(dpi): + msg = "DPI is not a number" + raise ValueError(msg) + if resolution_unit == 3: # cm + # 1 dpcm = 2.54 dpi + dpi *= 2.54 + self.info["dpi"] = dpi, dpi + except ( + struct.error, # truncated EXIF + KeyError, # dpi not included + SyntaxError, # invalid/unreadable EXIF + TypeError, # dpi is an invalid float + ValueError, # dpi is an invalid float + ZeroDivisionError, # invalid dpi rational value + ): + self.info["dpi"] = 72, 72 + + def _getmp(self) -> dict[int, Any] | None: + return _getmp(self) + + +def _getexif(self: JpegImageFile) -> dict[int, Any] | None: + if "exif" not in self.info: + return None + return self.getexif()._get_merged_dict() + + +def _getmp(self: JpegImageFile) -> dict[int, Any] | None: + # Extract MP information. This method was inspired by the "highly + # experimental" _getexif version that's been in use for years now, + # itself based on the ImageFileDirectory class in the TIFF plugin. + + # The MP record essentially consists of a TIFF file embedded in a JPEG + # application marker. + try: + data = self.info["mp"] + except KeyError: + return None + file_contents = io.BytesIO(data) + head = file_contents.read(8) + endianness = ">" if head.startswith(b"\x4d\x4d\x00\x2a") else "<" + # process dictionary + from . import TiffImagePlugin + + try: + info = TiffImagePlugin.ImageFileDirectory_v2(head) + file_contents.seek(info.next) + info.load(file_contents) + mp = dict(info) + except Exception as e: + msg = "malformed MP Index (unreadable directory)" + raise SyntaxError(msg) from e + # it's an error not to have a number of images + try: + quant = mp[0xB001] + except KeyError as e: + msg = "malformed MP Index (no number of images)" + raise SyntaxError(msg) from e + # get MP entries + mpentries = [] + try: + rawmpentries = mp[0xB002] + for entrynum in range(quant): + unpackedentry = struct.unpack_from( + f"{endianness}LLLHH", rawmpentries, entrynum * 16 + ) + labels = ("Attribute", "Size", "DataOffset", "EntryNo1", "EntryNo2") + mpentry = dict(zip(labels, unpackedentry)) + mpentryattr = { + "DependentParentImageFlag": bool(mpentry["Attribute"] & (1 << 31)), + "DependentChildImageFlag": bool(mpentry["Attribute"] & (1 << 30)), + "RepresentativeImageFlag": bool(mpentry["Attribute"] & (1 << 29)), + "Reserved": (mpentry["Attribute"] & (3 << 27)) >> 27, + "ImageDataFormat": (mpentry["Attribute"] & (7 << 24)) >> 24, + "MPType": mpentry["Attribute"] & 0x00FFFFFF, + } + if mpentryattr["ImageDataFormat"] == 0: + mpentryattr["ImageDataFormat"] = "JPEG" + else: + msg = "unsupported picture format in MPO" + raise SyntaxError(msg) + mptypemap = { + 0x000000: "Undefined", + 0x010001: "Large Thumbnail (VGA Equivalent)", + 0x010002: "Large Thumbnail (Full HD Equivalent)", + 0x020001: "Multi-Frame Image (Panorama)", + 0x020002: "Multi-Frame Image: (Disparity)", + 0x020003: "Multi-Frame Image: (Multi-Angle)", + 0x030000: "Baseline MP Primary Image", + } + mpentryattr["MPType"] = mptypemap.get(mpentryattr["MPType"], "Unknown") + mpentry["Attribute"] = mpentryattr + mpentries.append(mpentry) + mp[0xB002] = mpentries + except KeyError as e: + msg = "malformed MP Index (bad MP Entry)" + raise SyntaxError(msg) from e + # Next we should try and parse the individual image unique ID list; + # we don't because I've never seen this actually used in a real MPO + # file and so can't test it. + return mp + + +# -------------------------------------------------------------------- +# stuff to save JPEG files + +RAWMODE = { + "1": "L", + "L": "L", + "RGB": "RGB", + "RGBX": "RGB", + "CMYK": "CMYK;I", # assume adobe conventions + "YCbCr": "YCbCr", +} + +# fmt: off +zigzag_index = ( + 0, 1, 5, 6, 14, 15, 27, 28, + 2, 4, 7, 13, 16, 26, 29, 42, + 3, 8, 12, 17, 25, 30, 41, 43, + 9, 11, 18, 24, 31, 40, 44, 53, + 10, 19, 23, 32, 39, 45, 52, 54, + 20, 22, 33, 38, 46, 51, 55, 60, + 21, 34, 37, 47, 50, 56, 59, 61, + 35, 36, 48, 49, 57, 58, 62, 63, +) + +samplings = { + (1, 1, 1, 1, 1, 1): 0, + (2, 1, 1, 1, 1, 1): 1, + (2, 2, 1, 1, 1, 1): 2, +} +# fmt: on + + +def get_sampling(im: Image.Image) -> int: + # There's no subsampling when images have only 1 layer + # (grayscale images) or when they are CMYK (4 layers), + # so set subsampling to the default value. + # + # NOTE: currently Pillow can't encode JPEG to YCCK format. + # If YCCK support is added in the future, subsampling code will have + # to be updated (here and in JpegEncode.c) to deal with 4 layers. + if not isinstance(im, JpegImageFile) or im.layers in (1, 4): + return -1 + sampling = im.layer[0][1:3] + im.layer[1][1:3] + im.layer[2][1:3] + return samplings.get(sampling, -1) + + +def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + try: + rawmode = RAWMODE[im.mode] + except KeyError as e: + msg = f"cannot write mode {im.mode} as JPEG" + raise OSError(msg) from e + + info = im.encoderinfo + + dpi = [round(x) for x in info.get("dpi", (0, 0))] + + quality = info.get("quality", -1) + subsampling = info.get("subsampling", -1) + qtables = info.get("qtables") + + if quality == "keep": + quality = -1 + subsampling = "keep" + qtables = "keep" + elif quality in presets: + preset = presets[quality] + quality = -1 + subsampling = preset.get("subsampling", -1) + qtables = preset.get("quantization") + elif not isinstance(quality, int): + msg = "Invalid quality setting" + raise ValueError(msg) + else: + if subsampling in presets: + subsampling = presets[subsampling].get("subsampling", -1) + if isinstance(qtables, str) and qtables in presets: + qtables = presets[qtables].get("quantization") + + if subsampling == "4:4:4": + subsampling = 0 + elif subsampling == "4:2:2": + subsampling = 1 + elif subsampling == "4:2:0": + subsampling = 2 + elif subsampling == "4:1:1": + # For compatibility. Before Pillow 4.3, 4:1:1 actually meant 4:2:0. + # Set 4:2:0 if someone is still using that value. + subsampling = 2 + elif subsampling == "keep": + if im.format != "JPEG": + msg = "Cannot use 'keep' when original image is not a JPEG" + raise ValueError(msg) + subsampling = get_sampling(im) + + def validate_qtables( + qtables: ( + str | tuple[list[int], ...] | list[list[int]] | dict[int, list[int]] | None + ), + ) -> list[list[int]] | None: + if qtables is None: + return qtables + if isinstance(qtables, str): + try: + lines = [ + int(num) + for line in qtables.splitlines() + for num in line.split("#", 1)[0].split() + ] + except ValueError as e: + msg = "Invalid quantization table" + raise ValueError(msg) from e + else: + qtables = [lines[s : s + 64] for s in range(0, len(lines), 64)] + if isinstance(qtables, (tuple, list, dict)): + if isinstance(qtables, dict): + qtables = [ + qtables[key] for key in range(len(qtables)) if key in qtables + ] + elif isinstance(qtables, tuple): + qtables = list(qtables) + if not (0 < len(qtables) < 5): + msg = "None or too many quantization tables" + raise ValueError(msg) + try: + for idx, table in enumerate(qtables): + if len(table) != 64: + msg = "Invalid quantization table" + raise TypeError(msg) + qtables[idx] = list(array.array("H", table)) + except TypeError as e: + msg = "Invalid quantization table" + raise ValueError(msg) from e + return qtables + + if qtables == "keep": + if im.format != "JPEG": + msg = "Cannot use 'keep' when original image is not a JPEG" + raise ValueError(msg) + qtables = getattr(im, "quantization", None) + qtables = validate_qtables(qtables) + + extra = info.get("extra", b"") + + MAX_BYTES_IN_MARKER = 65533 + if xmp := info.get("xmp"): + overhead_len = 29 # b"http://ns.adobe.com/xap/1.0/\x00" + max_data_bytes_in_marker = MAX_BYTES_IN_MARKER - overhead_len + if len(xmp) > max_data_bytes_in_marker: + msg = "XMP data is too long" + raise ValueError(msg) + size = o16(2 + overhead_len + len(xmp)) + extra += b"\xff\xe1" + size + b"http://ns.adobe.com/xap/1.0/\x00" + xmp + + if icc_profile := info.get("icc_profile"): + overhead_len = 14 # b"ICC_PROFILE\0" + o8(i) + o8(len(markers)) + max_data_bytes_in_marker = MAX_BYTES_IN_MARKER - overhead_len + markers = [] + while icc_profile: + markers.append(icc_profile[:max_data_bytes_in_marker]) + icc_profile = icc_profile[max_data_bytes_in_marker:] + i = 1 + for marker in markers: + size = o16(2 + overhead_len + len(marker)) + extra += ( + b"\xff\xe2" + + size + + b"ICC_PROFILE\0" + + o8(i) + + o8(len(markers)) + + marker + ) + i += 1 + + comment = info.get("comment", im.info.get("comment")) + + # "progressive" is the official name, but older documentation + # says "progression" + # FIXME: issue a warning if the wrong form is used (post-1.1.7) + progressive = info.get("progressive", False) or info.get("progression", False) + + optimize = info.get("optimize", False) + + exif = info.get("exif", b"") + if isinstance(exif, Image.Exif): + exif = exif.tobytes() + if len(exif) > MAX_BYTES_IN_MARKER: + msg = "EXIF data is too long" + raise ValueError(msg) + + # get keyword arguments + im.encoderconfig = ( + quality, + progressive, + info.get("smooth", 0), + optimize, + info.get("keep_rgb", False), + info.get("streamtype", 0), + dpi, + subsampling, + info.get("restart_marker_blocks", 0), + info.get("restart_marker_rows", 0), + qtables, + comment, + extra, + exif, + ) + + # if we optimize, libjpeg needs a buffer big enough to hold the whole image + # in a shot. Guessing on the size, at im.size bytes. (raw pixel size is + # channels*size, this is a value that's been used in a django patch. + # https://github.com/matthewwithanm/django-imagekit/issues/50 + if optimize or progressive: + # CMYK can be bigger + if im.mode == "CMYK": + bufsize = 4 * im.size[0] * im.size[1] + # keep sets quality to -1, but the actual value may be high. + elif quality >= 95 or quality == -1: + bufsize = 2 * im.size[0] * im.size[1] + else: + bufsize = im.size[0] * im.size[1] + if exif: + bufsize += len(exif) + 5 + if extra: + bufsize += len(extra) + 1 + else: + # The EXIF info needs to be written as one block, + APP1, + one spare byte. + # Ensure that our buffer is big enough. Same with the icc_profile block. + bufsize = max(len(exif) + 5, len(extra) + 1) + + ImageFile._save( + im, fp, [ImageFile._Tile("jpeg", (0, 0) + im.size, 0, rawmode)], bufsize + ) + + +## +# Factory for making JPEG and MPO instances +def jpeg_factory( + fp: IO[bytes], filename: str | bytes | None = None +) -> JpegImageFile | MpoImageFile: + im = JpegImageFile(fp, filename) + try: + mpheader = im._getmp() + if mpheader is not None and mpheader[45057] > 1: + for segment, content in im.applist: + if segment == "APP1" and b' hdrgm:Version="' in content: + # Ultra HDR images are not yet supported + return im + # It's actually an MPO + from .MpoImagePlugin import MpoImageFile + + # Don't reload everything, just convert it. + im = MpoImageFile.adopt(im, mpheader) + except (TypeError, IndexError): + # It is really a JPEG + pass + except SyntaxError: + warnings.warn( + "Image appears to be a malformed MPO file, it will be " + "interpreted as a base JPEG file" + ) + return im + + +# --------------------------------------------------------------------- +# Registry stuff + +Image.register_open(JpegImageFile.format, jpeg_factory, _accept) +Image.register_save(JpegImageFile.format, _save) + +Image.register_extensions(JpegImageFile.format, [".jfif", ".jpe", ".jpg", ".jpeg"]) + +Image.register_mime(JpegImageFile.format, "image/jpeg") diff --git a/.venv/lib/python3.11/site-packages/PIL/JpegPresets.py b/.venv/lib/python3.11/site-packages/PIL/JpegPresets.py new file mode 100644 index 0000000000000000000000000000000000000000..d0e64a35ee1b6fe3ac6da792682a3129253993bb --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/JpegPresets.py @@ -0,0 +1,242 @@ +""" +JPEG quality settings equivalent to the Photoshop settings. +Can be used when saving JPEG files. + +The following presets are available by default: +``web_low``, ``web_medium``, ``web_high``, ``web_very_high``, ``web_maximum``, +``low``, ``medium``, ``high``, ``maximum``. +More presets can be added to the :py:data:`presets` dict if needed. + +To apply the preset, specify:: + + quality="preset_name" + +To apply only the quantization table:: + + qtables="preset_name" + +To apply only the subsampling setting:: + + subsampling="preset_name" + +Example:: + + im.save("image_name.jpg", quality="web_high") + +Subsampling +----------- + +Subsampling is the practice of encoding images by implementing less resolution +for chroma information than for luma information. +(ref.: https://en.wikipedia.org/wiki/Chroma_subsampling) + +Possible subsampling values are 0, 1 and 2 that correspond to 4:4:4, 4:2:2 and +4:2:0. + +You can get the subsampling of a JPEG with the +:func:`.JpegImagePlugin.get_sampling` function. + +In JPEG compressed data a JPEG marker is used instead of an EXIF tag. +(ref.: https://exiv2.org/tags.html) + + +Quantization tables +------------------- + +They are values use by the DCT (Discrete cosine transform) to remove +*unnecessary* information from the image (the lossy part of the compression). +(ref.: https://en.wikipedia.org/wiki/Quantization_matrix#Quantization_matrices, +https://en.wikipedia.org/wiki/JPEG#Quantization) + +You can get the quantization tables of a JPEG with:: + + im.quantization + +This will return a dict with a number of lists. You can pass this dict +directly as the qtables argument when saving a JPEG. + +The quantization table format in presets is a list with sublists. These formats +are interchangeable. + +Libjpeg ref.: +https://web.archive.org/web/20120328125543/http://www.jpegcameras.com/libjpeg/libjpeg-3.html + +""" + +from __future__ import annotations + +# fmt: off +presets = { + 'web_low': {'subsampling': 2, # "4:2:0" + 'quantization': [ + [20, 16, 25, 39, 50, 46, 62, 68, + 16, 18, 23, 38, 38, 53, 65, 68, + 25, 23, 31, 38, 53, 65, 68, 68, + 39, 38, 38, 53, 65, 68, 68, 68, + 50, 38, 53, 65, 68, 68, 68, 68, + 46, 53, 65, 68, 68, 68, 68, 68, + 62, 65, 68, 68, 68, 68, 68, 68, + 68, 68, 68, 68, 68, 68, 68, 68], + [21, 25, 32, 38, 54, 68, 68, 68, + 25, 28, 24, 38, 54, 68, 68, 68, + 32, 24, 32, 43, 66, 68, 68, 68, + 38, 38, 43, 53, 68, 68, 68, 68, + 54, 54, 66, 68, 68, 68, 68, 68, + 68, 68, 68, 68, 68, 68, 68, 68, + 68, 68, 68, 68, 68, 68, 68, 68, + 68, 68, 68, 68, 68, 68, 68, 68] + ]}, + 'web_medium': {'subsampling': 2, # "4:2:0" + 'quantization': [ + [16, 11, 11, 16, 23, 27, 31, 30, + 11, 12, 12, 15, 20, 23, 23, 30, + 11, 12, 13, 16, 23, 26, 35, 47, + 16, 15, 16, 23, 26, 37, 47, 64, + 23, 20, 23, 26, 39, 51, 64, 64, + 27, 23, 26, 37, 51, 64, 64, 64, + 31, 23, 35, 47, 64, 64, 64, 64, + 30, 30, 47, 64, 64, 64, 64, 64], + [17, 15, 17, 21, 20, 26, 38, 48, + 15, 19, 18, 17, 20, 26, 35, 43, + 17, 18, 20, 22, 26, 30, 46, 53, + 21, 17, 22, 28, 30, 39, 53, 64, + 20, 20, 26, 30, 39, 48, 64, 64, + 26, 26, 30, 39, 48, 63, 64, 64, + 38, 35, 46, 53, 64, 64, 64, 64, + 48, 43, 53, 64, 64, 64, 64, 64] + ]}, + 'web_high': {'subsampling': 0, # "4:4:4" + 'quantization': [ + [6, 4, 4, 6, 9, 11, 12, 16, + 4, 5, 5, 6, 8, 10, 12, 12, + 4, 5, 5, 6, 10, 12, 14, 19, + 6, 6, 6, 11, 12, 15, 19, 28, + 9, 8, 10, 12, 16, 20, 27, 31, + 11, 10, 12, 15, 20, 27, 31, 31, + 12, 12, 14, 19, 27, 31, 31, 31, + 16, 12, 19, 28, 31, 31, 31, 31], + [7, 7, 13, 24, 26, 31, 31, 31, + 7, 12, 16, 21, 31, 31, 31, 31, + 13, 16, 17, 31, 31, 31, 31, 31, + 24, 21, 31, 31, 31, 31, 31, 31, + 26, 31, 31, 31, 31, 31, 31, 31, + 31, 31, 31, 31, 31, 31, 31, 31, + 31, 31, 31, 31, 31, 31, 31, 31, + 31, 31, 31, 31, 31, 31, 31, 31] + ]}, + 'web_very_high': {'subsampling': 0, # "4:4:4" + 'quantization': [ + [2, 2, 2, 2, 3, 4, 5, 6, + 2, 2, 2, 2, 3, 4, 5, 6, + 2, 2, 2, 2, 4, 5, 7, 9, + 2, 2, 2, 4, 5, 7, 9, 12, + 3, 3, 4, 5, 8, 10, 12, 12, + 4, 4, 5, 7, 10, 12, 12, 12, + 5, 5, 7, 9, 12, 12, 12, 12, + 6, 6, 9, 12, 12, 12, 12, 12], + [3, 3, 5, 9, 13, 15, 15, 15, + 3, 4, 6, 11, 14, 12, 12, 12, + 5, 6, 9, 14, 12, 12, 12, 12, + 9, 11, 14, 12, 12, 12, 12, 12, + 13, 14, 12, 12, 12, 12, 12, 12, + 15, 12, 12, 12, 12, 12, 12, 12, + 15, 12, 12, 12, 12, 12, 12, 12, + 15, 12, 12, 12, 12, 12, 12, 12] + ]}, + 'web_maximum': {'subsampling': 0, # "4:4:4" + 'quantization': [ + [1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 2, + 1, 1, 1, 1, 1, 1, 2, 2, + 1, 1, 1, 1, 1, 2, 2, 3, + 1, 1, 1, 1, 2, 2, 3, 3, + 1, 1, 1, 2, 2, 3, 3, 3, + 1, 1, 2, 2, 3, 3, 3, 3], + [1, 1, 1, 2, 2, 3, 3, 3, + 1, 1, 1, 2, 3, 3, 3, 3, + 1, 1, 1, 3, 3, 3, 3, 3, + 2, 2, 3, 3, 3, 3, 3, 3, + 2, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3] + ]}, + 'low': {'subsampling': 2, # "4:2:0" + 'quantization': [ + [18, 14, 14, 21, 30, 35, 34, 17, + 14, 16, 16, 19, 26, 23, 12, 12, + 14, 16, 17, 21, 23, 12, 12, 12, + 21, 19, 21, 23, 12, 12, 12, 12, + 30, 26, 23, 12, 12, 12, 12, 12, + 35, 23, 12, 12, 12, 12, 12, 12, + 34, 12, 12, 12, 12, 12, 12, 12, + 17, 12, 12, 12, 12, 12, 12, 12], + [20, 19, 22, 27, 20, 20, 17, 17, + 19, 25, 23, 14, 14, 12, 12, 12, + 22, 23, 14, 14, 12, 12, 12, 12, + 27, 14, 14, 12, 12, 12, 12, 12, + 20, 14, 12, 12, 12, 12, 12, 12, + 20, 12, 12, 12, 12, 12, 12, 12, + 17, 12, 12, 12, 12, 12, 12, 12, + 17, 12, 12, 12, 12, 12, 12, 12] + ]}, + 'medium': {'subsampling': 2, # "4:2:0" + 'quantization': [ + [12, 8, 8, 12, 17, 21, 24, 17, + 8, 9, 9, 11, 15, 19, 12, 12, + 8, 9, 10, 12, 19, 12, 12, 12, + 12, 11, 12, 21, 12, 12, 12, 12, + 17, 15, 19, 12, 12, 12, 12, 12, + 21, 19, 12, 12, 12, 12, 12, 12, + 24, 12, 12, 12, 12, 12, 12, 12, + 17, 12, 12, 12, 12, 12, 12, 12], + [13, 11, 13, 16, 20, 20, 17, 17, + 11, 14, 14, 14, 14, 12, 12, 12, + 13, 14, 14, 14, 12, 12, 12, 12, + 16, 14, 14, 12, 12, 12, 12, 12, + 20, 14, 12, 12, 12, 12, 12, 12, + 20, 12, 12, 12, 12, 12, 12, 12, + 17, 12, 12, 12, 12, 12, 12, 12, + 17, 12, 12, 12, 12, 12, 12, 12] + ]}, + 'high': {'subsampling': 0, # "4:4:4" + 'quantization': [ + [6, 4, 4, 6, 9, 11, 12, 16, + 4, 5, 5, 6, 8, 10, 12, 12, + 4, 5, 5, 6, 10, 12, 12, 12, + 6, 6, 6, 11, 12, 12, 12, 12, + 9, 8, 10, 12, 12, 12, 12, 12, + 11, 10, 12, 12, 12, 12, 12, 12, + 12, 12, 12, 12, 12, 12, 12, 12, + 16, 12, 12, 12, 12, 12, 12, 12], + [7, 7, 13, 24, 20, 20, 17, 17, + 7, 12, 16, 14, 14, 12, 12, 12, + 13, 16, 14, 14, 12, 12, 12, 12, + 24, 14, 14, 12, 12, 12, 12, 12, + 20, 14, 12, 12, 12, 12, 12, 12, + 20, 12, 12, 12, 12, 12, 12, 12, + 17, 12, 12, 12, 12, 12, 12, 12, + 17, 12, 12, 12, 12, 12, 12, 12] + ]}, + 'maximum': {'subsampling': 0, # "4:4:4" + 'quantization': [ + [2, 2, 2, 2, 3, 4, 5, 6, + 2, 2, 2, 2, 3, 4, 5, 6, + 2, 2, 2, 2, 4, 5, 7, 9, + 2, 2, 2, 4, 5, 7, 9, 12, + 3, 3, 4, 5, 8, 10, 12, 12, + 4, 4, 5, 7, 10, 12, 12, 12, + 5, 5, 7, 9, 12, 12, 12, 12, + 6, 6, 9, 12, 12, 12, 12, 12], + [3, 3, 5, 9, 13, 15, 15, 15, + 3, 4, 6, 10, 14, 12, 12, 12, + 5, 6, 9, 14, 12, 12, 12, 12, + 9, 10, 14, 12, 12, 12, 12, 12, + 13, 14, 12, 12, 12, 12, 12, 12, + 15, 12, 12, 12, 12, 12, 12, 12, + 15, 12, 12, 12, 12, 12, 12, 12, + 15, 12, 12, 12, 12, 12, 12, 12] + ]}, +} +# fmt: on diff --git a/.venv/lib/python3.11/site-packages/PIL/McIdasImagePlugin.py b/.venv/lib/python3.11/site-packages/PIL/McIdasImagePlugin.py new file mode 100644 index 0000000000000000000000000000000000000000..9a47933b69cbdc628faafb67b2fca8de703abfc1 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/McIdasImagePlugin.py @@ -0,0 +1,78 @@ +# +# The Python Imaging Library. +# $Id$ +# +# Basic McIdas support for PIL +# +# History: +# 1997-05-05 fl Created (8-bit images only) +# 2009-03-08 fl Added 16/32-bit support. +# +# Thanks to Richard Jones and Craig Swank for specs and samples. +# +# Copyright (c) Secret Labs AB 1997. +# Copyright (c) Fredrik Lundh 1997. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import struct + +from . import Image, ImageFile + + +def _accept(prefix: bytes) -> bool: + return prefix.startswith(b"\x00\x00\x00\x00\x00\x00\x00\x04") + + +## +# Image plugin for McIdas area images. + + +class McIdasImageFile(ImageFile.ImageFile): + format = "MCIDAS" + format_description = "McIdas area file" + + def _open(self) -> None: + # parse area file directory + assert self.fp is not None + + s = self.fp.read(256) + if not _accept(s) or len(s) != 256: + msg = "not an McIdas area file" + raise SyntaxError(msg) + + self.area_descriptor_raw = s + self.area_descriptor = w = [0, *struct.unpack("!64i", s)] + + # get mode + if w[11] == 1: + mode = rawmode = "L" + elif w[11] == 2: + mode = rawmode = "I;16B" + elif w[11] == 4: + # FIXME: add memory map support + mode = "I" + rawmode = "I;32B" + else: + msg = "unsupported McIdas format" + raise SyntaxError(msg) + + self._mode = mode + self._size = w[10], w[9] + + offset = w[34] + w[15] + stride = w[15] + w[10] * w[11] * w[14] + + self.tile = [ + ImageFile._Tile("raw", (0, 0) + self.size, offset, (rawmode, stride, 1)) + ] + + +# -------------------------------------------------------------------- +# registry + +Image.register_open(McIdasImageFile.format, McIdasImageFile, _accept) + +# no default extension diff --git a/.venv/lib/python3.11/site-packages/PIL/MicImagePlugin.py b/.venv/lib/python3.11/site-packages/PIL/MicImagePlugin.py new file mode 100644 index 0000000000000000000000000000000000000000..99a07bae02cc10dfd3dc868ae0a46b9a36838665 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/MicImagePlugin.py @@ -0,0 +1,103 @@ +# +# The Python Imaging Library. +# $Id$ +# +# Microsoft Image Composer support for PIL +# +# Notes: +# uses TiffImagePlugin.py to read the actual image streams +# +# History: +# 97-01-20 fl Created +# +# Copyright (c) Secret Labs AB 1997. +# Copyright (c) Fredrik Lundh 1997. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import olefile + +from . import Image, TiffImagePlugin + +# +# -------------------------------------------------------------------- + + +def _accept(prefix: bytes) -> bool: + return prefix.startswith(olefile.MAGIC) + + +## +# Image plugin for Microsoft's Image Composer file format. + + +class MicImageFile(TiffImagePlugin.TiffImageFile): + format = "MIC" + format_description = "Microsoft Image Composer" + _close_exclusive_fp_after_loading = False + + def _open(self) -> None: + # read the OLE directory and see if this is a likely + # to be a Microsoft Image Composer file + + try: + self.ole = olefile.OleFileIO(self.fp) + except OSError as e: + msg = "not an MIC file; invalid OLE file" + raise SyntaxError(msg) from e + + # find ACI subfiles with Image members (maybe not the + # best way to identify MIC files, but what the... ;-) + + self.images = [ + path + for path in self.ole.listdir() + if path[1:] and path[0].endswith(".ACI") and path[1] == "Image" + ] + + # if we didn't find any images, this is probably not + # an MIC file. + if not self.images: + msg = "not an MIC file; no image entries" + raise SyntaxError(msg) + + self.frame = -1 + self._n_frames = len(self.images) + self.is_animated = self._n_frames > 1 + + assert self.fp is not None + self.__fp = self.fp + self.seek(0) + + def seek(self, frame: int) -> None: + if not self._seek_check(frame): + return + filename = self.images[frame] + self.fp = self.ole.openstream(filename) + + TiffImagePlugin.TiffImageFile._open(self) + + self.frame = frame + + def tell(self) -> int: + return self.frame + + def close(self) -> None: + self.__fp.close() + self.ole.close() + super().close() + + def __exit__(self, *args: object) -> None: + self.__fp.close() + self.ole.close() + super().__exit__() + + +# +# -------------------------------------------------------------------- + +Image.register_open(MicImageFile.format, MicImageFile, _accept) + +Image.register_extension(MicImageFile.format, ".mic") diff --git a/.venv/lib/python3.11/site-packages/PIL/MpegImagePlugin.py b/.venv/lib/python3.11/site-packages/PIL/MpegImagePlugin.py new file mode 100644 index 0000000000000000000000000000000000000000..47ebe9d62c4edd3b5e97f760ff7e9b0417e5b5ab --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/MpegImagePlugin.py @@ -0,0 +1,84 @@ +# +# The Python Imaging Library. +# $Id$ +# +# MPEG file handling +# +# History: +# 95-09-09 fl Created +# +# Copyright (c) Secret Labs AB 1997. +# Copyright (c) Fredrik Lundh 1995. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +from . import Image, ImageFile +from ._binary import i8 +from ._typing import SupportsRead + +# +# Bitstream parser + + +class BitStream: + def __init__(self, fp: SupportsRead[bytes]) -> None: + self.fp = fp + self.bits = 0 + self.bitbuffer = 0 + + def next(self) -> int: + return i8(self.fp.read(1)) + + def peek(self, bits: int) -> int: + while self.bits < bits: + self.bitbuffer = (self.bitbuffer << 8) + self.next() + self.bits += 8 + return self.bitbuffer >> (self.bits - bits) & (1 << bits) - 1 + + def skip(self, bits: int) -> None: + while self.bits < bits: + self.bitbuffer = (self.bitbuffer << 8) + i8(self.fp.read(1)) + self.bits += 8 + self.bits = self.bits - bits + + def read(self, bits: int) -> int: + v = self.peek(bits) + self.bits = self.bits - bits + return v + + +def _accept(prefix: bytes) -> bool: + return prefix.startswith(b"\x00\x00\x01\xb3") + + +## +# Image plugin for MPEG streams. This plugin can identify a stream, +# but it cannot read it. + + +class MpegImageFile(ImageFile.ImageFile): + format = "MPEG" + format_description = "MPEG" + + def _open(self) -> None: + assert self.fp is not None + + s = BitStream(self.fp) + if s.read(32) != 0x1B3: + msg = "not an MPEG file" + raise SyntaxError(msg) + + self._mode = "RGB" + self._size = s.read(12), s.read(12) + + +# -------------------------------------------------------------------- +# Registry stuff + +Image.register_open(MpegImageFile.format, MpegImageFile, _accept) + +Image.register_extensions(MpegImageFile.format, [".mpg", ".mpeg"]) + +Image.register_mime(MpegImageFile.format, "video/mpeg") diff --git a/.venv/lib/python3.11/site-packages/PIL/MpoImagePlugin.py b/.venv/lib/python3.11/site-packages/PIL/MpoImagePlugin.py new file mode 100644 index 0000000000000000000000000000000000000000..bee0a56f9ac86d8e066a1a91721bc7cca150399b --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/MpoImagePlugin.py @@ -0,0 +1,203 @@ +# +# The Python Imaging Library. +# $Id$ +# +# MPO file handling +# +# See "Multi-Picture Format" (CIPA DC-007-Translation 2009, Standard of the +# Camera & Imaging Products Association) +# +# The multi-picture object combines multiple JPEG images (with a modified EXIF +# data format) into a single file. While it can theoretically be used much like +# a GIF animation, it is commonly used to represent 3D photographs and is (as +# of this writing) the most commonly used format by 3D cameras. +# +# History: +# 2014-03-13 Feneric Created +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import os +import struct +from typing import IO, Any, cast + +from . import ( + Image, + ImageFile, + ImageSequence, + JpegImagePlugin, + TiffImagePlugin, +) +from ._binary import o32le +from ._util import DeferredError + + +def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + JpegImagePlugin._save(im, fp, filename) + + +def _save_all(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + append_images = im.encoderinfo.get("append_images", []) + if not append_images and not getattr(im, "is_animated", False): + _save(im, fp, filename) + return + + mpf_offset = 28 + offsets: list[int] = [] + im_sequences = [im, *append_images] + total = sum(getattr(seq, "n_frames", 1) for seq in im_sequences) + for im_sequence in im_sequences: + for im_frame in ImageSequence.Iterator(im_sequence): + if not offsets: + # APP2 marker + ifd_length = 66 + 16 * total + im_frame.encoderinfo["extra"] = ( + b"\xff\xe2" + + struct.pack(">H", 6 + ifd_length) + + b"MPF\0" + + b" " * ifd_length + ) + if exif := im_frame.encoderinfo.get("exif"): + if isinstance(exif, Image.Exif): + exif = exif.tobytes() + im_frame.encoderinfo["exif"] = exif + mpf_offset += 4 + len(exif) + + JpegImagePlugin._save(im_frame, fp, filename) + offsets.append(fp.tell()) + else: + encoderinfo = im_frame._attach_default_encoderinfo(im) + im_frame.save(fp, "JPEG") + im_frame.encoderinfo = encoderinfo + offsets.append(fp.tell() - offsets[-1]) + + ifd = TiffImagePlugin.ImageFileDirectory_v2() + ifd[0xB000] = b"0100" + ifd[0xB001] = len(offsets) + + mpentries = b"" + data_offset = 0 + for i, size in enumerate(offsets): + if i == 0: + mptype = 0x030000 # Baseline MP Primary Image + else: + mptype = 0x000000 # Undefined + mpentries += struct.pack(" None: + assert self.fp is not None + self.fp.seek(0) # prep the fp in order to pass the JPEG test + JpegImagePlugin.JpegImageFile._open(self) + self._after_jpeg_open() + + def _after_jpeg_open(self, mpheader: dict[int, Any] | None = None) -> None: + self.mpinfo = mpheader if mpheader is not None else self._getmp() + if self.mpinfo is None: + msg = "Image appears to be a malformed MPO file" + raise ValueError(msg) + self.n_frames = self.mpinfo[0xB001] + self.__mpoffsets = [ + mpent["DataOffset"] + self.info["mpoffset"] for mpent in self.mpinfo[0xB002] + ] + self.__mpoffsets[0] = 0 + # Note that the following assertion will only be invalid if something + # gets broken within JpegImagePlugin. + assert self.n_frames == len(self.__mpoffsets) + del self.info["mpoffset"] # no longer needed + self.is_animated = self.n_frames > 1 + assert self.fp is not None + self._fp = self.fp # FIXME: hack + self._fp.seek(self.__mpoffsets[0]) # get ready to read first frame + self.__frame = 0 + self.offset = 0 + # for now we can only handle reading and individual frame extraction + self.readonly = 1 + + def load_seek(self, pos: int) -> None: + if isinstance(self._fp, DeferredError): + raise self._fp.ex + self._fp.seek(pos) + + def seek(self, frame: int) -> None: + if not self._seek_check(frame): + return + if isinstance(self._fp, DeferredError): + raise self._fp.ex + self.fp = self._fp + self.offset = self.__mpoffsets[frame] + + original_exif = self.info.get("exif") + if "exif" in self.info: + del self.info["exif"] + + self.fp.seek(self.offset + 2) # skip SOI marker + if not self.fp.read(2): + msg = "No data found for frame" + raise ValueError(msg) + self.fp.seek(self.offset) + JpegImagePlugin.JpegImageFile._open(self) + if self.info.get("exif") != original_exif: + self._reload_exif() + + self.tile = [ + ImageFile._Tile("jpeg", (0, 0) + self.size, self.offset, self.tile[0][-1]) + ] + self.__frame = frame + + def tell(self) -> int: + return self.__frame + + @staticmethod + def adopt( + jpeg_instance: JpegImagePlugin.JpegImageFile, + mpheader: dict[int, Any] | None = None, + ) -> MpoImageFile: + """ + Transform the instance of JpegImageFile into + an instance of MpoImageFile. + After the call, the JpegImageFile is extended + to be an MpoImageFile. + + This is essentially useful when opening a JPEG + file that reveals itself as an MPO, to avoid + double call to _open. + """ + jpeg_instance.__class__ = MpoImageFile + mpo_instance = cast(MpoImageFile, jpeg_instance) + mpo_instance._after_jpeg_open(mpheader) + return mpo_instance + + +# --------------------------------------------------------------------- +# Registry stuff + +# Note that since MPO shares a factory with JPEG, we do not need to do a +# separate registration for it here. +# Image.register_open(MpoImageFile.format, +# JpegImagePlugin.jpeg_factory, _accept) +Image.register_save(MpoImageFile.format, _save) +Image.register_save_all(MpoImageFile.format, _save_all) + +Image.register_extension(MpoImageFile.format, ".mpo") + +Image.register_mime(MpoImageFile.format, "image/mpo") diff --git a/.venv/lib/python3.11/site-packages/PIL/MspImagePlugin.py b/.venv/lib/python3.11/site-packages/PIL/MspImagePlugin.py new file mode 100644 index 0000000000000000000000000000000000000000..9df5cfd9345a7c8cf5fa7501c9b1446e7bcec7e4 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/MspImagePlugin.py @@ -0,0 +1,200 @@ +# +# The Python Imaging Library. +# +# MSP file handling +# +# This is the format used by the Paint program in Windows 1 and 2. +# +# History: +# 95-09-05 fl Created +# 97-01-03 fl Read/write MSP images +# 17-02-21 es Fixed RLE interpretation +# +# Copyright (c) Secret Labs AB 1997. +# Copyright (c) Fredrik Lundh 1995-97. +# Copyright (c) Eric Soroos 2017. +# +# See the README file for information on usage and redistribution. +# +# More info on this format: https://archive.org/details/gg243631 +# Page 313: +# Figure 205. Windows Paint Version 1: "DanM" Format +# Figure 206. Windows Paint Version 2: "LinS" Format. Used in Windows V2.03 +# +# See also: https://www.fileformat.info/format/mspaint/egff.htm +from __future__ import annotations + +import io +import struct +from typing import IO + +from . import Image, ImageFile +from ._binary import i16le as i16 +from ._binary import o16le as o16 + +# +# read MSP files + + +def _accept(prefix: bytes) -> bool: + return prefix.startswith((b"DanM", b"LinS")) + + +## +# Image plugin for Windows MSP images. This plugin supports both +# uncompressed (Windows 1.0). + + +class MspImageFile(ImageFile.ImageFile): + format = "MSP" + format_description = "Windows Paint" + + def _open(self) -> None: + # Header + assert self.fp is not None + + s = self.fp.read(32) + if not _accept(s): + msg = "not an MSP file" + raise SyntaxError(msg) + + # Header checksum + checksum = 0 + for i in range(0, 32, 2): + checksum = checksum ^ i16(s, i) + if checksum != 0: + msg = "bad MSP checksum" + raise SyntaxError(msg) + + self._mode = "1" + self._size = i16(s, 4), i16(s, 6) + + if s.startswith(b"DanM"): + self.tile = [ImageFile._Tile("raw", (0, 0) + self.size, 32, "1")] + else: + self.tile = [ImageFile._Tile("MSP", (0, 0) + self.size, 32)] + + +class MspDecoder(ImageFile.PyDecoder): + # The algo for the MSP decoder is from + # https://www.fileformat.info/format/mspaint/egff.htm + # cc-by-attribution -- That page references is taken from the + # Encyclopedia of Graphics File Formats and is licensed by + # O'Reilly under the Creative Common/Attribution license + # + # For RLE encoded files, the 32byte header is followed by a scan + # line map, encoded as one 16bit word of encoded byte length per + # line. + # + # NOTE: the encoded length of the line can be 0. This was not + # handled in the previous version of this encoder, and there's no + # mention of how to handle it in the documentation. From the few + # examples I've seen, I've assumed that it is a fill of the + # background color, in this case, white. + # + # + # Pseudocode of the decoder: + # Read a BYTE value as the RunType + # If the RunType value is zero + # Read next byte as the RunCount + # Read the next byte as the RunValue + # Write the RunValue byte RunCount times + # If the RunType value is non-zero + # Use this value as the RunCount + # Read and write the next RunCount bytes literally + # + # e.g.: + # 0x00 03 ff 05 00 01 02 03 04 + # would yield the bytes: + # 0xff ff ff 00 01 02 03 04 + # + # which are then interpreted as a bit packed mode '1' image + + _pulls_fd = True + + def decode(self, buffer: Image.DecoderInput) -> tuple[int, int]: + assert self.fd is not None + + img = io.BytesIO() + blank_line = bytearray((0xFF,) * ((self.state.xsize + 7) // 8)) + try: + self.fd.seek(32) + rowmap = struct.unpack_from( + f"<{self.state.ysize}H", self.fd.read(self.state.ysize * 2) + ) + except struct.error as e: + msg = "Truncated MSP file in row map" + raise OSError(msg) from e + + for x, rowlen in enumerate(rowmap): + try: + if rowlen == 0: + img.write(blank_line) + continue + row = self.fd.read(rowlen) + if len(row) != rowlen: + msg = f"Truncated MSP file, expected {rowlen} bytes on row {x}" + raise OSError(msg) + idx = 0 + while idx < rowlen: + runtype = row[idx] + idx += 1 + if runtype == 0: + runcount, runval = struct.unpack_from("Bc", row, idx) + img.write(runval * runcount) + idx += 2 + else: + runcount = runtype + img.write(row[idx : idx + runcount]) + idx += runcount + + except struct.error as e: + msg = f"Corrupted MSP file in row {x}" + raise OSError(msg) from e + + self.set_as_raw(img.getvalue(), "1") + + return -1, 0 + + +Image.register_decoder("MSP", MspDecoder) + + +# +# write MSP files (uncompressed only) + + +def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + if im.mode != "1": + msg = f"cannot write mode {im.mode} as MSP" + raise OSError(msg) + + # create MSP header + header = [0] * 16 + + header[0], header[1] = i16(b"Da"), i16(b"nM") # version 1 + header[2], header[3] = im.size + header[4], header[5] = 1, 1 + header[6], header[7] = 1, 1 + header[8], header[9] = im.size + + checksum = 0 + for h in header: + checksum = checksum ^ h + header[12] = checksum # FIXME: is this the right field? + + # header + for h in header: + fp.write(o16(h)) + + # image body + ImageFile._save(im, fp, [ImageFile._Tile("raw", (0, 0) + im.size, 32, "1")]) + + +# +# registry + +Image.register_open(MspImageFile.format, MspImageFile, _accept) +Image.register_save(MspImageFile.format, _save) + +Image.register_extension(MspImageFile.format, ".msp") diff --git a/.venv/lib/python3.11/site-packages/PIL/PSDraw.py b/.venv/lib/python3.11/site-packages/PIL/PSDraw.py new file mode 100644 index 0000000000000000000000000000000000000000..e6b74a9188863f00ff27e4d97088f251109041c9 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/PSDraw.py @@ -0,0 +1,238 @@ +# +# The Python Imaging Library +# $Id$ +# +# Simple PostScript graphics interface +# +# History: +# 1996-04-20 fl Created +# 1999-01-10 fl Added gsave/grestore to image method +# 2005-05-04 fl Fixed floating point issue in image (from Eric Etheridge) +# +# Copyright (c) 1997-2005 by Secret Labs AB. All rights reserved. +# Copyright (c) 1996 by Fredrik Lundh. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import sys +from typing import IO + +from . import EpsImagePlugin + +TYPE_CHECKING = False + + +## +# Simple PostScript graphics interface. + + +class PSDraw: + """ + Sets up printing to the given file. If ``fp`` is omitted, + ``sys.stdout.buffer`` is assumed. + """ + + def __init__(self, fp: IO[bytes] | None = None) -> None: + if not fp: + fp = sys.stdout.buffer + self.fp = fp + + def begin_document(self, id: str | None = None) -> None: + """Set up printing of a document. (Write PostScript DSC header.)""" + # FIXME: incomplete + self.fp.write( + b"%!PS-Adobe-3.0\n" + b"save\n" + b"/showpage { } def\n" + b"%%EndComments\n" + b"%%BeginDocument\n" + ) + # self.fp.write(ERROR_PS) # debugging! + self.fp.write(EDROFF_PS) + self.fp.write(VDI_PS) + self.fp.write(b"%%EndProlog\n") + self.isofont: dict[bytes, int] = {} + + def end_document(self) -> None: + """Ends printing. (Write PostScript DSC footer.)""" + self.fp.write(b"%%EndDocument\nrestore showpage\n%%End\n") + if hasattr(self.fp, "flush"): + self.fp.flush() + + def setfont(self, font: str, size: int) -> None: + """ + Selects which font to use. + + :param font: A PostScript font name + :param size: Size in points. + """ + font_bytes = bytes(font, "UTF-8") + if font_bytes not in self.isofont: + # reencode font + self.fp.write( + b"/PSDraw-%s ISOLatin1Encoding /%s E\n" % (font_bytes, font_bytes) + ) + self.isofont[font_bytes] = 1 + # rough + self.fp.write(b"/F0 %d /PSDraw-%s F\n" % (size, font_bytes)) + + def line(self, xy0: tuple[int, int], xy1: tuple[int, int]) -> None: + """ + Draws a line between the two points. Coordinates are given in + PostScript point coordinates (72 points per inch, (0, 0) is the lower + left corner of the page). + """ + self.fp.write(b"%d %d %d %d Vl\n" % (*xy0, *xy1)) + + def rectangle(self, box: tuple[int, int, int, int]) -> None: + """ + Draws a rectangle. + + :param box: A tuple of four integers, specifying left, bottom, width and + height. + """ + self.fp.write(b"%d %d M 0 %d %d Vr\n" % box) + + def text(self, xy: tuple[int, int], text: str) -> None: + """ + Draws text at the given position. You must use + :py:meth:`~PIL.PSDraw.PSDraw.setfont` before calling this method. + """ + # The font is loaded as ISOLatin1Encoding, so use latin-1 here. + text_bytes = bytes(text, "latin-1") + text_bytes = b"\\(".join(text_bytes.split(b"(")) + text_bytes = b"\\)".join(text_bytes.split(b")")) + self.fp.write(b"%d %d M (%s) S\n" % (xy + (text_bytes,))) + + if TYPE_CHECKING: + from . import Image + + def image( + self, box: tuple[int, int, int, int], im: Image.Image, dpi: int | None = None + ) -> None: + """Draw a PIL image, centered in the given box.""" + # default resolution depends on mode + if not dpi: + if im.mode == "1": + dpi = 200 # fax + else: + dpi = 100 # grayscale + # image size (on paper) + x = im.size[0] * 72 / dpi + y = im.size[1] * 72 / dpi + # max allowed size + xmax = float(box[2] - box[0]) + ymax = float(box[3] - box[1]) + if x > xmax: + y = y * xmax / x + x = xmax + if y > ymax: + x = x * ymax / y + y = ymax + dx = (xmax - x) / 2 + box[0] + dy = (ymax - y) / 2 + box[1] + self.fp.write(b"gsave\n%f %f translate\n" % (dx, dy)) + if (x, y) != im.size: + # EpsImagePlugin._save prints the image at (0,0,xsize,ysize) + sx = x / im.size[0] + sy = y / im.size[1] + self.fp.write(b"%f %f scale\n" % (sx, sy)) + EpsImagePlugin._save(im, self.fp, "", 0) + self.fp.write(b"\ngrestore\n") + + +# -------------------------------------------------------------------- +# PostScript driver + +# +# EDROFF.PS -- PostScript driver for Edroff 2 +# +# History: +# 94-01-25 fl: created (edroff 2.04) +# +# Copyright (c) Fredrik Lundh 1994. +# + + +EDROFF_PS = b"""\ +/S { show } bind def +/P { moveto show } bind def +/M { moveto } bind def +/X { 0 rmoveto } bind def +/Y { 0 exch rmoveto } bind def +/E { findfont + dup maxlength dict begin + { + 1 index /FID ne { def } { pop pop } ifelse + } forall + /Encoding exch def + dup /FontName exch def + currentdict end definefont pop +} bind def +/F { findfont exch scalefont dup setfont + [ exch /setfont cvx ] cvx bind def +} bind def +""" + +# +# VDI.PS -- PostScript driver for VDI meta commands +# +# History: +# 94-01-25 fl: created (edroff 2.04) +# +# Copyright (c) Fredrik Lundh 1994. +# + +VDI_PS = b"""\ +/Vm { moveto } bind def +/Va { newpath arcn stroke } bind def +/Vl { moveto lineto stroke } bind def +/Vc { newpath 0 360 arc closepath } bind def +/Vr { exch dup 0 rlineto + exch dup 0 exch rlineto + exch neg 0 rlineto + 0 exch neg rlineto + setgray fill } bind def +/Tm matrix def +/Ve { Tm currentmatrix pop + translate scale newpath 0 0 .5 0 360 arc closepath + Tm setmatrix +} bind def +/Vf { currentgray exch setgray fill setgray } bind def +""" + +# +# ERROR.PS -- Error handler +# +# History: +# 89-11-21 fl: created (pslist 1.10) +# + +ERROR_PS = b"""\ +/landscape false def +/errorBUF 200 string def +/errorNL { currentpoint 10 sub exch pop 72 exch moveto } def +errordict begin /handleerror { + initmatrix /Courier findfont 10 scalefont setfont + newpath 72 720 moveto $error begin /newerror false def + (PostScript Error) show errorNL errorNL + (Error: ) show + /errorname load errorBUF cvs show errorNL errorNL + (Command: ) show + /command load dup type /stringtype ne { errorBUF cvs } if show + errorNL errorNL + (VMstatus: ) show + vmstatus errorBUF cvs show ( bytes available, ) show + errorBUF cvs show ( bytes used at level ) show + errorBUF cvs show errorNL errorNL + (Operand stargck: ) show errorNL /ostargck load { + dup type /stringtype ne { errorBUF cvs } if 72 0 rmoveto show errorNL + } forall errorNL + (Execution stargck: ) show errorNL /estargck load { + dup type /stringtype ne { errorBUF cvs } if 72 0 rmoveto show errorNL + } forall + end showpage +} def end +""" diff --git a/.venv/lib/python3.11/site-packages/PIL/PaletteFile.py b/.venv/lib/python3.11/site-packages/PIL/PaletteFile.py new file mode 100644 index 0000000000000000000000000000000000000000..2a26e5d4e223ba0bc80ad1bfb37b4c3927e222ac --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/PaletteFile.py @@ -0,0 +1,54 @@ +# +# Python Imaging Library +# $Id$ +# +# stuff to read simple, teragon-style palette files +# +# History: +# 97-08-23 fl Created +# +# Copyright (c) Secret Labs AB 1997. +# Copyright (c) Fredrik Lundh 1997. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +from typing import IO + +from ._binary import o8 + + +class PaletteFile: + """File handler for Teragon-style palette files.""" + + rawmode = "RGB" + + def __init__(self, fp: IO[bytes]) -> None: + palette = [o8(i) * 3 for i in range(256)] + + while True: + s = fp.readline() + + if not s: + break + if s.startswith(b"#"): + continue + if len(s) > 100: + msg = "bad palette file" + raise SyntaxError(msg) + + v = [int(x) for x in s.split()] + try: + [i, r, g, b] = v + except ValueError: + [i, r] = v + g = b = r + + if 0 <= i <= 255: + palette[i] = o8(r) + o8(g) + o8(b) + + self.palette = b"".join(palette) + + def getpalette(self) -> tuple[bytes, str]: + return self.palette, self.rawmode diff --git a/.venv/lib/python3.11/site-packages/PIL/PalmImagePlugin.py b/.venv/lib/python3.11/site-packages/PIL/PalmImagePlugin.py new file mode 100644 index 0000000000000000000000000000000000000000..232adf3d3bb33a18b9522f28ca7d61c7adb1655c --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/PalmImagePlugin.py @@ -0,0 +1,217 @@ +# +# The Python Imaging Library. +# $Id$ +# + +## +# Image plugin for Palm pixmap images (output only). +## +from __future__ import annotations + +from typing import IO + +from . import Image, ImageFile +from ._binary import o8 +from ._binary import o16be as o16b + +# fmt: off +_Palm8BitColormapValues = ( + (255, 255, 255), (255, 204, 255), (255, 153, 255), (255, 102, 255), + (255, 51, 255), (255, 0, 255), (255, 255, 204), (255, 204, 204), + (255, 153, 204), (255, 102, 204), (255, 51, 204), (255, 0, 204), + (255, 255, 153), (255, 204, 153), (255, 153, 153), (255, 102, 153), + (255, 51, 153), (255, 0, 153), (204, 255, 255), (204, 204, 255), + (204, 153, 255), (204, 102, 255), (204, 51, 255), (204, 0, 255), + (204, 255, 204), (204, 204, 204), (204, 153, 204), (204, 102, 204), + (204, 51, 204), (204, 0, 204), (204, 255, 153), (204, 204, 153), + (204, 153, 153), (204, 102, 153), (204, 51, 153), (204, 0, 153), + (153, 255, 255), (153, 204, 255), (153, 153, 255), (153, 102, 255), + (153, 51, 255), (153, 0, 255), (153, 255, 204), (153, 204, 204), + (153, 153, 204), (153, 102, 204), (153, 51, 204), (153, 0, 204), + (153, 255, 153), (153, 204, 153), (153, 153, 153), (153, 102, 153), + (153, 51, 153), (153, 0, 153), (102, 255, 255), (102, 204, 255), + (102, 153, 255), (102, 102, 255), (102, 51, 255), (102, 0, 255), + (102, 255, 204), (102, 204, 204), (102, 153, 204), (102, 102, 204), + (102, 51, 204), (102, 0, 204), (102, 255, 153), (102, 204, 153), + (102, 153, 153), (102, 102, 153), (102, 51, 153), (102, 0, 153), + (51, 255, 255), (51, 204, 255), (51, 153, 255), (51, 102, 255), + (51, 51, 255), (51, 0, 255), (51, 255, 204), (51, 204, 204), + (51, 153, 204), (51, 102, 204), (51, 51, 204), (51, 0, 204), + (51, 255, 153), (51, 204, 153), (51, 153, 153), (51, 102, 153), + (51, 51, 153), (51, 0, 153), (0, 255, 255), (0, 204, 255), + (0, 153, 255), (0, 102, 255), (0, 51, 255), (0, 0, 255), + (0, 255, 204), (0, 204, 204), (0, 153, 204), (0, 102, 204), + (0, 51, 204), (0, 0, 204), (0, 255, 153), (0, 204, 153), + (0, 153, 153), (0, 102, 153), (0, 51, 153), (0, 0, 153), + (255, 255, 102), (255, 204, 102), (255, 153, 102), (255, 102, 102), + (255, 51, 102), (255, 0, 102), (255, 255, 51), (255, 204, 51), + (255, 153, 51), (255, 102, 51), (255, 51, 51), (255, 0, 51), + (255, 255, 0), (255, 204, 0), (255, 153, 0), (255, 102, 0), + (255, 51, 0), (255, 0, 0), (204, 255, 102), (204, 204, 102), + (204, 153, 102), (204, 102, 102), (204, 51, 102), (204, 0, 102), + (204, 255, 51), (204, 204, 51), (204, 153, 51), (204, 102, 51), + (204, 51, 51), (204, 0, 51), (204, 255, 0), (204, 204, 0), + (204, 153, 0), (204, 102, 0), (204, 51, 0), (204, 0, 0), + (153, 255, 102), (153, 204, 102), (153, 153, 102), (153, 102, 102), + (153, 51, 102), (153, 0, 102), (153, 255, 51), (153, 204, 51), + (153, 153, 51), (153, 102, 51), (153, 51, 51), (153, 0, 51), + (153, 255, 0), (153, 204, 0), (153, 153, 0), (153, 102, 0), + (153, 51, 0), (153, 0, 0), (102, 255, 102), (102, 204, 102), + (102, 153, 102), (102, 102, 102), (102, 51, 102), (102, 0, 102), + (102, 255, 51), (102, 204, 51), (102, 153, 51), (102, 102, 51), + (102, 51, 51), (102, 0, 51), (102, 255, 0), (102, 204, 0), + (102, 153, 0), (102, 102, 0), (102, 51, 0), (102, 0, 0), + (51, 255, 102), (51, 204, 102), (51, 153, 102), (51, 102, 102), + (51, 51, 102), (51, 0, 102), (51, 255, 51), (51, 204, 51), + (51, 153, 51), (51, 102, 51), (51, 51, 51), (51, 0, 51), + (51, 255, 0), (51, 204, 0), (51, 153, 0), (51, 102, 0), + (51, 51, 0), (51, 0, 0), (0, 255, 102), (0, 204, 102), + (0, 153, 102), (0, 102, 102), (0, 51, 102), (0, 0, 102), + (0, 255, 51), (0, 204, 51), (0, 153, 51), (0, 102, 51), + (0, 51, 51), (0, 0, 51), (0, 255, 0), (0, 204, 0), + (0, 153, 0), (0, 102, 0), (0, 51, 0), (17, 17, 17), + (34, 34, 34), (68, 68, 68), (85, 85, 85), (119, 119, 119), + (136, 136, 136), (170, 170, 170), (187, 187, 187), (221, 221, 221), + (238, 238, 238), (192, 192, 192), (128, 0, 0), (128, 0, 128), + (0, 128, 0), (0, 128, 128), (0, 0, 0), (0, 0, 0), + (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), + (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), + (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), + (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), + (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), + (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0)) +# fmt: on + + +# so build a prototype image to be used for palette resampling +def build_prototype_image() -> Image.Image: + image = Image.new("L", (1, len(_Palm8BitColormapValues))) + image.putdata(list(range(len(_Palm8BitColormapValues)))) + palettedata: tuple[int, ...] = () + for colormapValue in _Palm8BitColormapValues: + palettedata += colormapValue + palettedata += (0, 0, 0) * (256 - len(_Palm8BitColormapValues)) + image.putpalette(palettedata) + return image + + +Palm8BitColormapImage = build_prototype_image() + +# OK, we now have in Palm8BitColormapImage, +# a "P"-mode image with the right palette +# +# -------------------------------------------------------------------- + +_FLAGS = {"custom-colormap": 0x4000, "is-compressed": 0x8000, "has-transparent": 0x2000} + +_COMPRESSION_TYPES = {"none": 0xFF, "rle": 0x01, "scanline": 0x00} + + +# +# -------------------------------------------------------------------- + +## +# (Internal) Image save plugin for the Palm format. + + +def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + if im.mode == "P": + rawmode = "P" + bpp = 8 + version = 1 + + elif im.mode == "L": + if im.encoderinfo.get("bpp") in (1, 2, 4): + # this is 8-bit grayscale, so we shift it to get the high-order bits, + # and invert it because + # Palm does grayscale from white (0) to black (1) + bpp = im.encoderinfo["bpp"] + maxval = (1 << bpp) - 1 + shift = 8 - bpp + im = im.point(lambda x: maxval - (x >> shift)) + elif im.info.get("bpp") in (1, 2, 4): + # here we assume that even though the inherent mode is 8-bit grayscale, + # only the lower bpp bits are significant. + # We invert them to match the Palm. + bpp = im.info["bpp"] + maxval = (1 << bpp) - 1 + im = im.point(lambda x: maxval - (x & maxval)) + else: + msg = f"cannot write mode {im.mode} as Palm" + raise OSError(msg) + + # we ignore the palette here + im._mode = "P" + rawmode = f"P;{bpp}" + version = 1 + + elif im.mode == "1": + # monochrome -- write it inverted, as is the Palm standard + rawmode = "1;I" + bpp = 1 + version = 0 + + else: + msg = f"cannot write mode {im.mode} as Palm" + raise OSError(msg) + + # + # make sure image data is available + im.load() + + # write header + + cols = im.size[0] + rows = im.size[1] + + rowbytes = int((cols + (16 // bpp - 1)) / (16 // bpp)) * 2 + transparent_index = 0 + compression_type = _COMPRESSION_TYPES["none"] + + flags = 0 + if im.mode == "P": + flags |= _FLAGS["custom-colormap"] + colormap = im.im.getpalette() + colors = len(colormap) // 3 + colormapsize = 4 * colors + 2 + else: + colormapsize = 0 + + if "offset" in im.info: + offset = (rowbytes * rows + 16 + 3 + colormapsize) // 4 + else: + offset = 0 + + fp.write(o16b(cols) + o16b(rows) + o16b(rowbytes) + o16b(flags)) + fp.write(o8(bpp)) + fp.write(o8(version)) + fp.write(o16b(offset)) + fp.write(o8(transparent_index)) + fp.write(o8(compression_type)) + fp.write(o16b(0)) # reserved by Palm + + # now write colormap if necessary + + if colormapsize: + fp.write(o16b(colors)) + for i in range(colors): + fp.write(o8(i)) + fp.write(colormap[3 * i : 3 * i + 3]) + + # now convert data to raw form + ImageFile._save( + im, fp, [ImageFile._Tile("raw", (0, 0) + im.size, 0, (rawmode, rowbytes, 1))] + ) + + if hasattr(fp, "flush"): + fp.flush() + + +# +# -------------------------------------------------------------------- + +Image.register_save("PALM", _save) + +Image.register_extension("PALM", ".palm") + +Image.register_mime("PALM", "image/palm") diff --git a/.venv/lib/python3.11/site-packages/PIL/PcdImagePlugin.py b/.venv/lib/python3.11/site-packages/PIL/PcdImagePlugin.py new file mode 100644 index 0000000000000000000000000000000000000000..296f3775b0d064627888df8958786731643989cd --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/PcdImagePlugin.py @@ -0,0 +1,68 @@ +# +# The Python Imaging Library. +# $Id$ +# +# PCD file handling +# +# History: +# 96-05-10 fl Created +# 96-05-27 fl Added draft mode (128x192, 256x384) +# +# Copyright (c) Secret Labs AB 1997. +# Copyright (c) Fredrik Lundh 1996. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +from . import Image, ImageFile + +## +# Image plugin for PhotoCD images. This plugin only reads the 768x512 +# image from the file; higher resolutions are encoded in a proprietary +# encoding. + + +class PcdImageFile(ImageFile.ImageFile): + format = "PCD" + format_description = "Kodak PhotoCD" + + def _open(self) -> None: + # rough + assert self.fp is not None + + self.fp.seek(2048) + s = self.fp.read(1539) + + if not s.startswith(b"PCD_"): + msg = "not a PCD file" + raise SyntaxError(msg) + + orientation = s[1538] & 3 + self.tile_post_rotate = None + if orientation == 1: + self.tile_post_rotate = 90 + elif orientation == 3: + self.tile_post_rotate = 270 + + self._mode = "RGB" + self._size = (512, 768) if orientation in (1, 3) else (768, 512) + self.tile = [ImageFile._Tile("pcd", (0, 0, 768, 512), 96 * 2048)] + + def load_prepare(self) -> None: + if self._im is None and self.tile_post_rotate: + self.im = Image.core.new(self.mode, (768, 512)) + ImageFile.ImageFile.load_prepare(self) + + def load_end(self) -> None: + if self.tile_post_rotate: + # Handle rotated PCDs + self.im = self.rotate(self.tile_post_rotate, expand=True).im + + +# +# registry + +Image.register_open(PcdImageFile.format, PcdImageFile) + +Image.register_extension(PcdImageFile.format, ".pcd") diff --git a/.venv/lib/python3.11/site-packages/PIL/PcfFontFile.py b/.venv/lib/python3.11/site-packages/PIL/PcfFontFile.py new file mode 100644 index 0000000000000000000000000000000000000000..985444106a1743b274511dfd957b0e1d0a0bc9b2 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/PcfFontFile.py @@ -0,0 +1,256 @@ +# +# THIS IS WORK IN PROGRESS +# +# The Python Imaging Library +# $Id$ +# +# portable compiled font file parser +# +# history: +# 1997-08-19 fl created +# 2003-09-13 fl fixed loading of unicode fonts +# +# Copyright (c) 1997-2003 by Secret Labs AB. +# Copyright (c) 1997-2003 by Fredrik Lundh. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import io + +from . import FontFile, Image +from ._binary import i8 +from ._binary import i16be as b16 +from ._binary import i16le as l16 +from ._binary import i32be as b32 +from ._binary import i32le as l32 + +TYPE_CHECKING = False +if TYPE_CHECKING: + from collections.abc import Callable + from typing import BinaryIO + +# -------------------------------------------------------------------- +# declarations + +PCF_MAGIC = 0x70636601 # "\x01fcp" + +PCF_PROPERTIES = 1 << 0 +PCF_ACCELERATORS = 1 << 1 +PCF_METRICS = 1 << 2 +PCF_BITMAPS = 1 << 3 +PCF_INK_METRICS = 1 << 4 +PCF_BDF_ENCODINGS = 1 << 5 +PCF_SWIDTHS = 1 << 6 +PCF_GLYPH_NAMES = 1 << 7 +PCF_BDF_ACCELERATORS = 1 << 8 + +BYTES_PER_ROW: list[Callable[[int], int]] = [ + lambda bits: ((bits + 7) >> 3), + lambda bits: ((bits + 15) >> 3) & ~1, + lambda bits: ((bits + 31) >> 3) & ~3, + lambda bits: ((bits + 63) >> 3) & ~7, +] + + +def sz(s: bytes, o: int) -> bytes: + return s[o : s.index(b"\0", o)] + + +class PcfFontFile(FontFile.FontFile): + """Font file plugin for the X11 PCF format.""" + + name = "name" + + def __init__(self, fp: BinaryIO, charset_encoding: str = "iso8859-1"): + self.charset_encoding = charset_encoding + + magic = l32(fp.read(4)) + if magic != PCF_MAGIC: + msg = "not a PCF file" + raise SyntaxError(msg) + + super().__init__() + + count = l32(fp.read(4)) + self.toc = {} + for i in range(count): + type = l32(fp.read(4)) + self.toc[type] = l32(fp.read(4)), l32(fp.read(4)), l32(fp.read(4)) + + self.fp = fp + + self.info = self._load_properties() + + metrics = self._load_metrics() + bitmaps = self._load_bitmaps(metrics) + encoding = self._load_encoding() + + # + # create glyph structure + + for ch, ix in enumerate(encoding): + if ix is not None: + ( + xsize, + ysize, + left, + right, + width, + ascent, + descent, + attributes, + ) = metrics[ix] + self.glyph[ch] = ( + (width, 0), + (left, descent - ysize, xsize + left, descent), + (0, 0, xsize, ysize), + bitmaps[ix], + ) + + def _getformat( + self, tag: int + ) -> tuple[BinaryIO, int, Callable[[bytes], int], Callable[[bytes], int]]: + format, size, offset = self.toc[tag] + + fp = self.fp + fp.seek(offset) + + format = l32(fp.read(4)) + + if format & 4: + i16, i32 = b16, b32 + else: + i16, i32 = l16, l32 + + return fp, format, i16, i32 + + def _load_properties(self) -> dict[bytes, bytes | int]: + # + # font properties + + properties = {} + + fp, format, i16, i32 = self._getformat(PCF_PROPERTIES) + + nprops = i32(fp.read(4)) + + # read property description + p = [(i32(fp.read(4)), i8(fp.read(1)), i32(fp.read(4))) for _ in range(nprops)] + + if nprops & 3: + fp.seek(4 - (nprops & 3), io.SEEK_CUR) # pad + + data = fp.read(i32(fp.read(4))) + + for k, s, v in p: + property_value: bytes | int = sz(data, v) if s else v + properties[sz(data, k)] = property_value + + return properties + + def _load_metrics(self) -> list[tuple[int, int, int, int, int, int, int, int]]: + # + # font metrics + + metrics: list[tuple[int, int, int, int, int, int, int, int]] = [] + + fp, format, i16, i32 = self._getformat(PCF_METRICS) + + def append( + left: int, + right: int, + width: int, + ascent: int, + descent: int, + attributes: int = 0, + ) -> None: + xsize = right - left + ysize = ascent + descent + Image._decompression_bomb_check((xsize, ysize)) + metrics.append( + (xsize, ysize, left, right, width, ascent, descent, attributes) + ) + + if (format & 0xFF00) == 0x100: + # "compressed" metrics + for i in range(i16(fp.read(2))): + append(*(i8(fp.read(1)) - 128 for _ in range(5))) + + else: + # "jumbo" metrics + for i in range(i32(fp.read(4))): + append(*(i16(fp.read(2)) for _ in range(6))) + + return metrics + + def _load_bitmaps( + self, metrics: list[tuple[int, int, int, int, int, int, int, int]] + ) -> list[Image.Image]: + # + # bitmap data + + fp, format, i16, i32 = self._getformat(PCF_BITMAPS) + + nbitmaps = i32(fp.read(4)) + + if nbitmaps != len(metrics): + msg = "Wrong number of bitmaps" + raise OSError(msg) + + offsets = [i32(fp.read(4)) for _ in range(nbitmaps)] + + bitmap_sizes = [i32(fp.read(4)) for _ in range(4)] + + # byteorder = format & 4 # non-zero => MSB + bitorder = format & 8 # non-zero => MSB + padindex = format & 3 + + bitmapsize = bitmap_sizes[padindex] + offsets.append(bitmapsize) + + data = fp.read(bitmapsize) + + pad = BYTES_PER_ROW[padindex] + mode = "1;R" + if bitorder: + mode = "1" + + bitmaps = [] + for i in range(nbitmaps): + xsize, ysize = metrics[i][:2] + b, e = offsets[i : i + 2] + bitmaps.append( + Image.frombytes("1", (xsize, ysize), data[b:e], "raw", mode, pad(xsize)) + ) + + return bitmaps + + def _load_encoding(self) -> list[int | None]: + fp, format, i16, i32 = self._getformat(PCF_BDF_ENCODINGS) + + first_col, last_col = i16(fp.read(2)), i16(fp.read(2)) + first_row, last_row = i16(fp.read(2)), i16(fp.read(2)) + + i16(fp.read(2)) # default + + nencoding = (last_col - first_col + 1) * (last_row - first_row + 1) + + # map character code to bitmap index + encoding: list[int | None] = [None] * min(256, nencoding) + + encoding_offsets = [i16(fp.read(2)) for _ in range(nencoding)] + + for i in range(first_col, len(encoding)): + try: + encoding_offset = encoding_offsets[ + ord(bytearray([i]).decode(self.charset_encoding)) + ] + if encoding_offset != 0xFFFF: + encoding[i] = encoding_offset + except UnicodeDecodeError: # noqa: PERF203 + # character is not supported in selected encoding + pass + + return encoding diff --git a/.venv/lib/python3.11/site-packages/PIL/PcxImagePlugin.py b/.venv/lib/python3.11/site-packages/PIL/PcxImagePlugin.py new file mode 100644 index 0000000000000000000000000000000000000000..3e34e3c63bafcff8dceae14e4bbd17ec176b33b1 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/PcxImagePlugin.py @@ -0,0 +1,232 @@ +# +# The Python Imaging Library. +# $Id$ +# +# PCX file handling +# +# This format was originally used by ZSoft's popular PaintBrush +# program for the IBM PC. It is also supported by many MS-DOS and +# Windows applications, including the Windows PaintBrush program in +# Windows 3. +# +# history: +# 1995-09-01 fl Created +# 1996-05-20 fl Fixed RGB support +# 1997-01-03 fl Fixed 2-bit and 4-bit support +# 1999-02-03 fl Fixed 8-bit support (broken in 1.0b1) +# 1999-02-07 fl Added write support +# 2002-06-09 fl Made 2-bit and 4-bit support a bit more robust +# 2002-07-30 fl Seek from to current position, not beginning of file +# 2003-06-03 fl Extract DPI settings (info["dpi"]) +# +# Copyright (c) 1997-2003 by Secret Labs AB. +# Copyright (c) 1995-2003 by Fredrik Lundh. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import io +import logging +from typing import IO + +from . import Image, ImageFile, ImagePalette +from ._binary import i16le as i16 +from ._binary import o8 +from ._binary import o16le as o16 + +logger = logging.getLogger(__name__) + + +def _accept(prefix: bytes) -> bool: + return len(prefix) >= 2 and prefix[0] == 10 and prefix[1] in [0, 2, 3, 5] + + +## +# Image plugin for Paintbrush images. + + +class PcxImageFile(ImageFile.ImageFile): + format = "PCX" + format_description = "Paintbrush" + + def _open(self) -> None: + # header + assert self.fp is not None + + s = self.fp.read(68) + if not _accept(s): + msg = "not a PCX file" + raise SyntaxError(msg) + + # image + bbox = i16(s, 4), i16(s, 6), i16(s, 8) + 1, i16(s, 10) + 1 + if bbox[2] <= bbox[0] or bbox[3] <= bbox[1]: + msg = "bad PCX image size" + raise SyntaxError(msg) + logger.debug("BBox: %s %s %s %s", *bbox) + + offset = self.fp.tell() + 60 + + # format + version = s[1] + bits = s[3] + planes = s[65] + provided_stride = i16(s, 66) + logger.debug( + "PCX version %s, bits %s, planes %s, stride %s", + version, + bits, + planes, + provided_stride, + ) + + self.info["dpi"] = i16(s, 12), i16(s, 14) + + if bits == 1 and planes == 1: + mode = rawmode = "1" + + elif bits == 1 and planes in (2, 4): + mode = "P" + rawmode = f"P;{planes}L" + self.palette = ImagePalette.raw("RGB", s[16:64]) + + elif version == 5 and bits == 8 and planes == 1: + mode = rawmode = "L" + # FIXME: hey, this doesn't work with the incremental loader !!! + self.fp.seek(-769, io.SEEK_END) + s = self.fp.read(769) + if len(s) == 769 and s[0] == 12: + # check if the palette is linear grayscale + for i in range(256): + if s[i * 3 + 1 : i * 3 + 4] != o8(i) * 3: + mode = rawmode = "P" + break + if mode == "P": + self.palette = ImagePalette.raw("RGB", s[1:]) + + elif version == 5 and bits == 8 and planes == 3: + mode = "RGB" + rawmode = "RGB;L" + + else: + msg = "unknown PCX mode" + raise OSError(msg) + + self._mode = mode + self._size = bbox[2] - bbox[0], bbox[3] - bbox[1] + + # Don't trust the passed in stride. + # Calculate the approximate position for ourselves. + # CVE-2020-35653 + stride = (self._size[0] * bits + 7) // 8 + + # While the specification states that this must be even, + # not all images follow this + if provided_stride != stride: + stride += stride % 2 + + bbox = (0, 0) + self.size + logger.debug("size: %sx%s", *self.size) + + self.tile = [ImageFile._Tile("pcx", bbox, offset, (rawmode, planes * stride))] + + +# -------------------------------------------------------------------- +# save PCX files + + +SAVE = { + # mode: (version, bits, planes, raw mode) + "1": (2, 1, 1, "1"), + "L": (5, 8, 1, "L"), + "P": (5, 8, 1, "P"), + "RGB": (5, 8, 3, "RGB;L"), +} + + +def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + if im.width == 0 or im.height == 0: + msg = "Cannot write empty image as PCX" + raise ValueError(msg) + + try: + version, bits, planes, rawmode = SAVE[im.mode] + except KeyError as e: + msg = f"Cannot save {im.mode} images as PCX" + raise ValueError(msg) from e + + # bytes per plane + stride = (im.size[0] * bits + 7) // 8 + # stride should be even + stride += stride % 2 + # Stride needs to be kept in sync with the PcxEncode.c version. + # Ideally it should be passed in in the state, but the bytes value + # gets overwritten. + + logger.debug( + "PcxImagePlugin._save: xwidth: %d, bits: %d, stride: %d", + im.size[0], + bits, + stride, + ) + + # under windows, we could determine the current screen size with + # "Image.core.display_mode()[1]", but I think that's overkill... + + screen = im.size + + dpi = 100, 100 + + # PCX header + fp.write( + o8(10) + + o8(version) + + o8(1) + + o8(bits) + + o16(0) + + o16(0) + + o16(im.size[0] - 1) + + o16(im.size[1] - 1) + + o16(dpi[0]) + + o16(dpi[1]) + + b"\0" * 24 + + b"\xff" * 24 + + b"\0" + + o8(planes) + + o16(stride) + + o16(1) + + o16(screen[0]) + + o16(screen[1]) + + b"\0" * 54 + ) + + assert fp.tell() == 128 + + ImageFile._save( + im, fp, [ImageFile._Tile("pcx", (0, 0) + im.size, 0, (rawmode, bits * planes))] + ) + + if im.mode == "P": + # colour palette + fp.write(o8(12)) + palette = im.im.getpalette("RGB", "RGB") + palette += b"\x00" * (768 - len(palette)) + fp.write(palette) # 768 bytes + elif im.mode == "L": + # grayscale palette + fp.write(o8(12)) + for i in range(256): + fp.write(o8(i) * 3) + + +# -------------------------------------------------------------------- +# registry + + +Image.register_open(PcxImageFile.format, PcxImageFile, _accept) +Image.register_save(PcxImageFile.format, _save) + +Image.register_extension(PcxImageFile.format, ".pcx") + +Image.register_mime(PcxImageFile.format, "image/x-pcx") diff --git a/.venv/lib/python3.11/site-packages/PIL/PdfImagePlugin.py b/.venv/lib/python3.11/site-packages/PIL/PdfImagePlugin.py new file mode 100644 index 0000000000000000000000000000000000000000..cb26786b0d9c9c81c0c54aeba7d7e1fb1fda9000 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/PdfImagePlugin.py @@ -0,0 +1,315 @@ +# +# The Python Imaging Library. +# $Id$ +# +# PDF (Acrobat) file handling +# +# History: +# 1996-07-16 fl Created +# 1997-01-18 fl Fixed header +# 2004-02-21 fl Fixes for 1/L/CMYK images, etc. +# 2004-02-24 fl Fixes for 1 and P images. +# +# Copyright (c) 1997-2004 by Secret Labs AB. All rights reserved. +# Copyright (c) 1996-1997 by Fredrik Lundh. +# +# See the README file for information on usage and redistribution. +# + +## +# Image plugin for PDF images (output only). +## +from __future__ import annotations + +import io +import math +import os +import time +from typing import IO, Any + +from . import Image, ImageFile, ImageSequence, PdfParser, features + +# +# -------------------------------------------------------------------- + +# object ids: +# 1. catalogue +# 2. pages +# 3. image +# 4. page +# 5. page contents + + +def _save_all(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + _save(im, fp, filename, save_all=True) + + +## +# (Internal) Image save plugin for the PDF format. + + +def _write_image( + im: Image.Image, + filename: str | bytes, + existing_pdf: PdfParser.PdfParser, + image_refs: list[PdfParser.IndirectReference], +) -> tuple[PdfParser.IndirectReference, str]: + # FIXME: Should replace ASCIIHexDecode with RunLengthDecode + # (packbits) or LZWDecode (tiff/lzw compression). Note that + # PDF 1.2 also supports Flatedecode (zip compression). + + params = None + decode = None + + # + # Get image characteristics + + width, height = im.size + + dict_obj: dict[str, Any] = {"BitsPerComponent": 8} + if im.mode == "1": + if features.check("libtiff"): + decode_filter = "CCITTFaxDecode" + dict_obj["BitsPerComponent"] = 1 + params = PdfParser.PdfArray( + [ + PdfParser.PdfDict( + { + "K": -1, + "BlackIs1": True, + "Columns": width, + "Rows": height, + } + ) + ] + ) + else: + decode_filter = "DCTDecode" + dict_obj["ColorSpace"] = PdfParser.PdfName("DeviceGray") + procset = "ImageB" # grayscale + elif im.mode == "L": + decode_filter = "DCTDecode" + # params = f"<< /Predictor 15 /Columns {width-2} >>" + dict_obj["ColorSpace"] = PdfParser.PdfName("DeviceGray") + procset = "ImageB" # grayscale + elif im.mode == "LA": + decode_filter = "JPXDecode" + # params = f"<< /Predictor 15 /Columns {width-2} >>" + procset = "ImageB" # grayscale + dict_obj["SMaskInData"] = 1 + elif im.mode == "P": + decode_filter = "ASCIIHexDecode" + palette = im.getpalette() + assert palette is not None + dict_obj["ColorSpace"] = [ + PdfParser.PdfName("Indexed"), + PdfParser.PdfName("DeviceRGB"), + len(palette) // 3 - 1, + PdfParser.PdfBinary(palette), + ] + procset = "ImageI" # indexed color + + if "transparency" in im.info: + smask = im.convert("LA").getchannel("A") + smask.encoderinfo = {} + + image_ref = _write_image(smask, filename, existing_pdf, image_refs)[0] + dict_obj["SMask"] = image_ref + elif im.mode == "RGB": + decode_filter = "DCTDecode" + dict_obj["ColorSpace"] = PdfParser.PdfName("DeviceRGB") + procset = "ImageC" # color images + elif im.mode == "RGBA": + decode_filter = "JPXDecode" + procset = "ImageC" # color images + dict_obj["SMaskInData"] = 1 + elif im.mode == "CMYK": + decode_filter = "DCTDecode" + dict_obj["ColorSpace"] = PdfParser.PdfName("DeviceCMYK") + procset = "ImageC" # color images + decode = [1, 0, 1, 0, 1, 0, 1, 0] + else: + msg = f"cannot save mode {im.mode}" + raise ValueError(msg) + + # + # image + + op = io.BytesIO() + + if decode_filter == "ASCIIHexDecode": + ImageFile._save(im, op, [ImageFile._Tile("hex", (0, 0) + im.size, 0, im.mode)]) + elif decode_filter == "CCITTFaxDecode": + im.save( + op, + "TIFF", + compression="group4", + # use a single strip + strip_size=math.ceil(width / 8) * height, + ) + elif decode_filter == "DCTDecode": + from . import JpegImagePlugin + + JpegImagePlugin._save(im, op, filename) + elif decode_filter == "JPXDecode": + from . import Jpeg2KImagePlugin + + del dict_obj["BitsPerComponent"] + Jpeg2KImagePlugin._save(im, op, filename) + else: + msg = f"unsupported PDF filter ({decode_filter})" + raise ValueError(msg) + + stream = op.getvalue() + filter: PdfParser.PdfArray | PdfParser.PdfName + if decode_filter == "CCITTFaxDecode": + stream = stream[8:] + filter = PdfParser.PdfArray([PdfParser.PdfName(decode_filter)]) + else: + filter = PdfParser.PdfName(decode_filter) + + image_ref = image_refs.pop(0) + existing_pdf.write_obj( + image_ref, + stream=stream, + Type=PdfParser.PdfName("XObject"), + Subtype=PdfParser.PdfName("Image"), + Width=width, # * 72.0 / x_resolution, + Height=height, # * 72.0 / y_resolution, + Filter=filter, + Decode=decode, + DecodeParms=params, + **dict_obj, + ) + + return image_ref, procset + + +def _save( + im: Image.Image, fp: IO[bytes], filename: str | bytes, save_all: bool = False +) -> None: + is_appending = im.encoderinfo.get("append", False) + filename_str = filename.decode() if isinstance(filename, bytes) else filename + if is_appending: + existing_pdf = PdfParser.PdfParser(f=fp, filename=filename_str, mode="r+b") + else: + existing_pdf = PdfParser.PdfParser(f=fp, filename=filename_str, mode="w+b") + + dpi = im.encoderinfo.get("dpi") + if dpi: + x_resolution = dpi[0] + y_resolution = dpi[1] + else: + x_resolution = y_resolution = im.encoderinfo.get("resolution", 72.0) + + info = { + "title": ( + None if is_appending else os.path.splitext(os.path.basename(filename))[0] + ), + "author": None, + "subject": None, + "keywords": None, + "creator": None, + "producer": None, + "creationDate": None if is_appending else time.gmtime(), + "modDate": None if is_appending else time.gmtime(), + } + for k, default in info.items(): + v = im.encoderinfo.get(k) if k in im.encoderinfo else default + if v: + existing_pdf.info[k[0].upper() + k[1:]] = v + + # + # make sure image data is available + im.load() + + existing_pdf.start_writing() + existing_pdf.write_header() + existing_pdf.write_comment("created by Pillow PDF driver") + + # + # pages + ims = [im] + if save_all: + append_images = im.encoderinfo.get("append_images", []) + for append_im in append_images: + append_im.encoderinfo = im.encoderinfo.copy() + ims.append(append_im) + number_of_pages = 0 + image_refs = [] + page_refs = [] + contents_refs = [] + for im in ims: + im_number_of_pages = 1 + if save_all: + im_number_of_pages = getattr(im, "n_frames", 1) + number_of_pages += im_number_of_pages + for i in range(im_number_of_pages): + image_refs.append(existing_pdf.next_object_id(0)) + if im.mode == "P" and "transparency" in im.info: + image_refs.append(existing_pdf.next_object_id(0)) + + page_refs.append(existing_pdf.next_object_id(0)) + contents_refs.append(existing_pdf.next_object_id(0)) + existing_pdf.pages.append(page_refs[-1]) + + # + # catalog and list of pages + existing_pdf.write_catalog() + + page_number = 0 + for im_sequence in ims: + im_pages: ImageSequence.Iterator | list[Image.Image] = ( + ImageSequence.Iterator(im_sequence) if save_all else [im_sequence] + ) + for im in im_pages: + image_ref, procset = _write_image(im, filename, existing_pdf, image_refs) + + # + # page + + existing_pdf.write_page( + page_refs[page_number], + Resources=PdfParser.PdfDict( + ProcSet=[PdfParser.PdfName("PDF"), PdfParser.PdfName(procset)], + XObject=PdfParser.PdfDict(image=image_ref), + ), + MediaBox=[ + 0, + 0, + im.width * 72.0 / x_resolution, + im.height * 72.0 / y_resolution, + ], + Contents=contents_refs[page_number], + ) + + # + # page contents + + page_contents = b"q %f 0 0 %f 0 0 cm /image Do Q\n" % ( + im.width * 72.0 / x_resolution, + im.height * 72.0 / y_resolution, + ) + + existing_pdf.write_obj(contents_refs[page_number], stream=page_contents) + + page_number += 1 + + # + # trailer + existing_pdf.write_xref_and_trailer() + if hasattr(fp, "flush"): + fp.flush() + existing_pdf.close() + + +# +# -------------------------------------------------------------------- + + +Image.register_save("PDF", _save) +Image.register_save_all("PDF", _save_all) + +Image.register_extension("PDF", ".pdf") + +Image.register_mime("PDF", "application/pdf") diff --git a/.venv/lib/python3.11/site-packages/PIL/PdfParser.py b/.venv/lib/python3.11/site-packages/PIL/PdfParser.py new file mode 100644 index 0000000000000000000000000000000000000000..c2e1568f969c3f33cb75df1860a609c6431b85a3 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/PdfParser.py @@ -0,0 +1,1092 @@ +from __future__ import annotations + +import calendar +import codecs +import collections +import mmap +import os +import re +import time +import zlib +from typing import Any, NamedTuple + +from . import ImageFile + +TYPE_CHECKING = False +if TYPE_CHECKING: + from typing import IO + + _DictBase = collections.UserDict[str | bytes, Any] +else: + _DictBase = collections.UserDict + + +# see 7.9.2.2 Text String Type on page 86 and D.3 PDFDocEncoding Character Set +# on page 656 +def encode_text(s: str) -> bytes: + return codecs.BOM_UTF16_BE + s.encode("utf_16_be") + + +PDFDocEncoding = { + 0x16: "\u0017", + 0x18: "\u02d8", + 0x19: "\u02c7", + 0x1A: "\u02c6", + 0x1B: "\u02d9", + 0x1C: "\u02dd", + 0x1D: "\u02db", + 0x1E: "\u02da", + 0x1F: "\u02dc", + 0x80: "\u2022", + 0x81: "\u2020", + 0x82: "\u2021", + 0x83: "\u2026", + 0x84: "\u2014", + 0x85: "\u2013", + 0x86: "\u0192", + 0x87: "\u2044", + 0x88: "\u2039", + 0x89: "\u203a", + 0x8A: "\u2212", + 0x8B: "\u2030", + 0x8C: "\u201e", + 0x8D: "\u201c", + 0x8E: "\u201d", + 0x8F: "\u2018", + 0x90: "\u2019", + 0x91: "\u201a", + 0x92: "\u2122", + 0x93: "\ufb01", + 0x94: "\ufb02", + 0x95: "\u0141", + 0x96: "\u0152", + 0x97: "\u0160", + 0x98: "\u0178", + 0x99: "\u017d", + 0x9A: "\u0131", + 0x9B: "\u0142", + 0x9C: "\u0153", + 0x9D: "\u0161", + 0x9E: "\u017e", + 0xA0: "\u20ac", +} + + +def decode_text(b: bytes) -> str: + if b[: len(codecs.BOM_UTF16_BE)] == codecs.BOM_UTF16_BE: + return b[len(codecs.BOM_UTF16_BE) :].decode("utf_16_be") + else: + return "".join(PDFDocEncoding.get(byte, chr(byte)) for byte in b) + + +class PdfFormatError(RuntimeError): + """An error that probably indicates a syntactic or semantic error in the + PDF file structure""" + + pass + + +def check_format_condition(condition: bool, error_message: str) -> None: + if not condition: + raise PdfFormatError(error_message) + + +class IndirectReferenceTuple(NamedTuple): + object_id: int + generation: int + + +class IndirectReference(IndirectReferenceTuple): + def __str__(self) -> str: + return f"{self.object_id} {self.generation} R" + + def __bytes__(self) -> bytes: + return self.__str__().encode("us-ascii") + + def __eq__(self, other: object) -> bool: + if self.__class__ is not other.__class__: + return False + assert isinstance(other, IndirectReference) + return other.object_id == self.object_id and other.generation == self.generation + + def __ne__(self, other: object) -> bool: + return not (self == other) + + def __hash__(self) -> int: + return hash((self.object_id, self.generation)) + + +class IndirectObjectDef(IndirectReference): + def __str__(self) -> str: + return f"{self.object_id} {self.generation} obj" + + +class XrefTable: + def __init__(self) -> None: + self.existing_entries: dict[int, tuple[int, int]] = ( + {} + ) # object ID => (offset, generation) + self.new_entries: dict[int, tuple[int, int]] = ( + {} + ) # object ID => (offset, generation) + self.deleted_entries = {0: 65536} # object ID => generation + self.reading_finished = False + + def __setitem__(self, key: int, value: tuple[int, int]) -> None: + if self.reading_finished: + self.new_entries[key] = value + else: + self.existing_entries[key] = value + if key in self.deleted_entries: + del self.deleted_entries[key] + + def __getitem__(self, key: int) -> tuple[int, int]: + try: + return self.new_entries[key] + except KeyError: + return self.existing_entries[key] + + def __delitem__(self, key: int) -> None: + if key in self.new_entries: + generation = self.new_entries[key][1] + 1 + del self.new_entries[key] + self.deleted_entries[key] = generation + elif key in self.existing_entries: + generation = self.existing_entries[key][1] + 1 + self.deleted_entries[key] = generation + elif key in self.deleted_entries: + generation = self.deleted_entries[key] + else: + msg = f"object ID {key} cannot be deleted because it doesn't exist" + raise IndexError(msg) + + def __contains__(self, key: int) -> bool: + return key in self.existing_entries or key in self.new_entries + + def __len__(self) -> int: + return len( + set(self.existing_entries.keys()) + | set(self.new_entries.keys()) + | set(self.deleted_entries.keys()) + ) + + def keys(self) -> set[int]: + return ( + set(self.existing_entries.keys()) - set(self.deleted_entries.keys()) + ) | set(self.new_entries.keys()) + + def write(self, f: IO[bytes]) -> int: + keys = sorted(set(self.new_entries.keys()) | set(self.deleted_entries.keys())) + deleted_keys = sorted(set(self.deleted_entries.keys())) + startxref = f.tell() + f.write(b"xref\n") + while keys: + # find a contiguous sequence of object IDs + prev: int | None = None + for index, key in enumerate(keys): + if prev is None or prev + 1 == key: + prev = key + else: + contiguous_keys = keys[:index] + keys = keys[index:] + break + else: + contiguous_keys = keys + keys = [] + f.write(b"%d %d\n" % (contiguous_keys[0], len(contiguous_keys))) + for object_id in contiguous_keys: + if object_id in self.new_entries: + f.write(b"%010d %05d n \n" % self.new_entries[object_id]) + else: + this_deleted_object_id = deleted_keys.pop(0) + check_format_condition( + object_id == this_deleted_object_id, + f"expected the next deleted object ID to be {object_id}, " + f"instead found {this_deleted_object_id}", + ) + try: + next_in_linked_list = deleted_keys[0] + except IndexError: + next_in_linked_list = 0 + f.write( + b"%010d %05d f \n" + % (next_in_linked_list, self.deleted_entries[object_id]) + ) + return startxref + + +class PdfName: + name: bytes + + def __init__(self, name: PdfName | bytes | str) -> None: + if isinstance(name, PdfName): + self.name = name.name + elif isinstance(name, bytes): + self.name = name + else: + self.name = name.encode("us-ascii") + + def name_as_str(self) -> str: + return self.name.decode("us-ascii") + + def __eq__(self, other: object) -> bool: + return ( + isinstance(other, PdfName) and other.name == self.name + ) or other == self.name + + def __hash__(self) -> int: + return hash(self.name) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({repr(self.name)})" + + @classmethod + def from_pdf_stream(cls, data: bytes) -> PdfName: + return cls(PdfParser.interpret_name(data)) + + allowed_chars = set(range(33, 127)) - {ord(c) for c in "#%/()<>[]{}"} + + def __bytes__(self) -> bytes: + result = bytearray(b"/") + for b in self.name: + if b in self.allowed_chars: + result.append(b) + else: + result.extend(b"#%02X" % b) + return bytes(result) + + +class PdfArray(list[Any]): + def __bytes__(self) -> bytes: + return b"[ " + b" ".join(pdf_repr(x) for x in self) + b" ]" + + +class PdfDict(_DictBase): + def __setattr__(self, key: str, value: Any) -> None: + if key == "data": + collections.UserDict.__setattr__(self, key, value) + else: + self[key.encode("us-ascii")] = value + + def __getattr__(self, key: str) -> str | time.struct_time: + try: + value = self[key.encode("us-ascii")] + except KeyError as e: + raise AttributeError(key) from e + if isinstance(value, bytes): + value = decode_text(value) + if key.endswith("Date"): + if value.startswith("D:"): + value = value[2:] + + relationship = "Z" + if len(value) > 17: + relationship = value[14] + offset = int(value[15:17]) * 60 + if len(value) > 20: + offset += int(value[18:20]) + + format = "%Y%m%d%H%M%S"[: len(value) - 2] + value = time.strptime(value[: len(format) + 2], format) + if relationship in ["+", "-"]: + offset *= 60 + if relationship == "+": + offset *= -1 + value = time.gmtime(calendar.timegm(value) + offset) + return value + + def __bytes__(self) -> bytes: + out = bytearray(b"<<") + for key, value in self.items(): + if value is None: + continue + value = pdf_repr(value) + out.extend(b"\n") + out.extend(bytes(PdfName(key))) + out.extend(b" ") + out.extend(value) + out.extend(b"\n>>") + return bytes(out) + + +class PdfBinary: + def __init__(self, data: list[int] | bytes) -> None: + self.data = data + + def __bytes__(self) -> bytes: + return b"<%s>" % b"".join(b"%02X" % b for b in self.data) + + +class PdfStream: + def __init__(self, dictionary: PdfDict, buf: bytes) -> None: + self.dictionary = dictionary + self.buf = buf + + def decode(self, max_length: int = ImageFile.SAFEBLOCK) -> bytes: + try: + filter = self.dictionary[b"Filter"] + except KeyError: + return self.buf + if filter == b"FlateDecode": + dobj = zlib.decompressobj() + plaintext = dobj.decompress(self.buf, max_length) + if dobj.unconsumed_tail: + msg = "Decompressed data too large" + raise ValueError(msg) + return plaintext + else: + msg = f"stream filter {repr(filter)} unknown/unsupported" + raise NotImplementedError(msg) + + +def pdf_repr(x: Any) -> bytes: + if x is True: + return b"true" + elif x is False: + return b"false" + elif x is None: + return b"null" + elif isinstance(x, (PdfName, PdfDict, PdfArray, PdfBinary)): + return bytes(x) + elif isinstance(x, (int, float)): + return str(x).encode("us-ascii") + elif isinstance(x, time.struct_time): + return b"(D:" + time.strftime("%Y%m%d%H%M%SZ", x).encode("us-ascii") + b")" + elif isinstance(x, dict): + return bytes(PdfDict(x)) + elif isinstance(x, list): + return bytes(PdfArray(x)) + elif isinstance(x, str): + return pdf_repr(encode_text(x)) + elif isinstance(x, bytes): + # XXX escape more chars? handle binary garbage + x = x.replace(b"\\", b"\\\\") + x = x.replace(b"(", b"\\(") + x = x.replace(b")", b"\\)") + return b"(" + x + b")" + else: + return bytes(x) + + +class PdfParser: + """Based on + https://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/PDF32000_2008.pdf + Supports PDF up to 1.4 + """ + + def __init__( + self, + filename: str | None = None, + f: IO[bytes] | None = None, + buf: bytes | bytearray | None = None, + start_offset: int = 0, + mode: str = "rb", + ) -> None: + if buf and f: + msg = "specify buf or f or filename, but not both buf and f" + raise RuntimeError(msg) + self.filename = filename + self.buf: bytes | bytearray | memoryview | mmap.mmap | None = buf + self.f = f + self.start_offset = start_offset + self.should_close_buf = False + self.should_close_file = False + if filename is not None and f is None: + self.f = f = open(filename, mode) + self.should_close_file = True + if f is not None: + self.buf = self.get_buf_from_file(f) + self.should_close_buf = True + if not filename and hasattr(f, "name"): + self.filename = f.name + self.cached_objects: dict[IndirectReference, Any] = {} + self.root_ref: IndirectReference | None + self.info_ref: IndirectReference | None + self.pages_ref: IndirectReference | None + self.last_xref_section_offset: int | None + if self.buf: + try: + self.read_pdf_info() + except PdfFormatError: + self.close() + raise + else: + self.file_size_total = self.file_size_this = 0 + self.root = PdfDict() + self.root_ref = None + self.info = PdfDict() + self.info_ref = None + self.page_tree_root = PdfDict() + self.pages: list[IndirectReference] = [] + self.orig_pages: list[IndirectReference] = [] + self.pages_ref = None + self.last_xref_section_offset = None + self.trailer_dict: dict[bytes, Any] = {} + self.xref_table = XrefTable() + self.xref_table.reading_finished = True + if f: + self.seek_end() + + def __enter__(self) -> PdfParser: + return self + + def __exit__(self, *args: object) -> None: + self.close() + + def start_writing(self) -> None: + self.close_buf() + self.seek_end() + + def close_buf(self) -> None: + if isinstance(self.buf, memoryview): + self.buf.release() + elif isinstance(self.buf, mmap.mmap): + self.buf.close() + self.buf = None + + def close(self) -> None: + if self.should_close_buf: + self.close_buf() + if self.f is not None and self.should_close_file: + self.f.close() + self.f = None + + def seek_end(self) -> None: + assert self.f is not None + self.f.seek(0, os.SEEK_END) + + def write_header(self) -> None: + assert self.f is not None + self.f.write(b"%PDF-1.4\n") + + def write_comment(self, s: str) -> None: + assert self.f is not None + self.f.write(f"% {s}\n".encode()) + + def write_catalog(self) -> IndirectReference: + assert self.f is not None + self.del_root() + self.root_ref = self.next_object_id(self.f.tell()) + self.pages_ref = self.next_object_id(0) + self.rewrite_pages() + self.write_obj(self.root_ref, Type=PdfName(b"Catalog"), Pages=self.pages_ref) + self.write_obj( + self.pages_ref, + Type=PdfName(b"Pages"), + Count=len(self.pages), + Kids=self.pages, + ) + return self.root_ref + + def rewrite_pages(self) -> None: + pages_tree_nodes_to_delete = [] + for i, page_ref in enumerate(self.orig_pages): + page_info = self.cached_objects[page_ref] + del self.xref_table[page_ref.object_id] + pages_tree_nodes_to_delete.append(page_info[PdfName(b"Parent")]) + if page_ref not in self.pages: + # the page has been deleted + continue + # make dict keys into strings for passing to write_page + stringified_page_info = {} + for key, value in page_info.items(): + # key should be a PdfName + stringified_page_info[key.name_as_str()] = value + stringified_page_info["Parent"] = self.pages_ref + new_page_ref = self.write_page(None, **stringified_page_info) + for j, cur_page_ref in enumerate(self.pages): + if cur_page_ref == page_ref: + # replace the page reference with the new one + self.pages[j] = new_page_ref + # delete redundant Pages tree nodes from xref table + for pages_tree_node_ref in pages_tree_nodes_to_delete: + while pages_tree_node_ref: + pages_tree_node = self.cached_objects[pages_tree_node_ref] + if pages_tree_node_ref.object_id in self.xref_table: + del self.xref_table[pages_tree_node_ref.object_id] + pages_tree_node_ref = pages_tree_node.get(b"Parent", None) + self.orig_pages = [] + + def write_xref_and_trailer( + self, new_root_ref: IndirectReference | None = None + ) -> None: + assert self.f is not None + if new_root_ref: + self.del_root() + self.root_ref = new_root_ref + if self.info: + self.info_ref = self.write_obj(None, self.info) + start_xref = self.xref_table.write(self.f) + num_entries = len(self.xref_table) + trailer_dict: dict[str | bytes, Any] = { + b"Root": self.root_ref, + b"Size": num_entries, + } + if self.last_xref_section_offset is not None: + trailer_dict[b"Prev"] = self.last_xref_section_offset + if self.info: + trailer_dict[b"Info"] = self.info_ref + self.last_xref_section_offset = start_xref + self.f.write( + b"trailer\n" + + bytes(PdfDict(trailer_dict)) + + b"\nstartxref\n%d\n%%%%EOF" % start_xref + ) + + def write_page( + self, ref: int | IndirectReference | None, *objs: Any, **dict_obj: Any + ) -> IndirectReference: + obj_ref = self.pages[ref] if isinstance(ref, int) else ref + if "Type" not in dict_obj: + dict_obj["Type"] = PdfName(b"Page") + if "Parent" not in dict_obj: + dict_obj["Parent"] = self.pages_ref + return self.write_obj(obj_ref, *objs, **dict_obj) + + def write_obj( + self, ref: IndirectReference | None, *objs: Any, **dict_obj: Any + ) -> IndirectReference: + assert self.f is not None + f = self.f + if ref is None: + ref = self.next_object_id(f.tell()) + else: + self.xref_table[ref.object_id] = (f.tell(), ref.generation) + f.write(bytes(IndirectObjectDef(*ref))) + stream = dict_obj.pop("stream", None) + if stream is not None: + dict_obj["Length"] = len(stream) + if dict_obj: + f.write(pdf_repr(dict_obj)) + for obj in objs: + f.write(pdf_repr(obj)) + if stream is not None: + f.write(b"stream\n") + f.write(stream) + f.write(b"\nendstream\n") + f.write(b"endobj\n") + return ref + + def del_root(self) -> None: + if self.root_ref is None: + return + del self.xref_table[self.root_ref.object_id] + del self.xref_table[self.root[b"Pages"].object_id] + + @staticmethod + def get_buf_from_file(f: IO[bytes]) -> bytes | mmap.mmap: + if hasattr(f, "getbuffer"): + return f.getbuffer() + elif hasattr(f, "getvalue"): + return f.getvalue() + else: + try: + return mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) + except ValueError: # cannot mmap an empty file + return b"" + + def read_pdf_info(self) -> None: + assert self.buf is not None + self.file_size_total = len(self.buf) + self.file_size_this = self.file_size_total - self.start_offset + self.read_trailer() + check_format_condition( + self.trailer_dict.get(b"Root") is not None, "Root is missing" + ) + self.root_ref = self.trailer_dict[b"Root"] + assert self.root_ref is not None + self.info_ref = self.trailer_dict.get(b"Info", None) + self.root = PdfDict(self.read_indirect(self.root_ref)) + if self.info_ref is None: + self.info = PdfDict() + else: + self.info = PdfDict(self.read_indirect(self.info_ref)) + check_format_condition(b"Type" in self.root, "/Type missing in Root") + check_format_condition( + self.root[b"Type"] == b"Catalog", "/Type in Root is not /Catalog" + ) + check_format_condition( + self.root.get(b"Pages") is not None, "/Pages missing in Root" + ) + check_format_condition( + isinstance(self.root[b"Pages"], IndirectReference), + "/Pages in Root is not an indirect reference", + ) + self.pages_ref = self.root[b"Pages"] + assert self.pages_ref is not None + self.page_tree_root = self.read_indirect(self.pages_ref) + self.pages = self.linearize_page_tree(self.page_tree_root) + # save the original list of page references + # in case the user modifies, adds or deletes some pages + # and we need to rewrite the pages and their list + self.orig_pages = self.pages[:] + + def next_object_id(self, offset: int | None = None) -> IndirectReference: + try: + # TODO: support reuse of deleted objects + reference = IndirectReference(max(self.xref_table.keys()) + 1, 0) + except ValueError: + reference = IndirectReference(1, 0) + if offset is not None: + self.xref_table[reference.object_id] = (offset, 0) + return reference + + delimiter = rb"[][()<>{}/%]" + delimiter_or_ws = rb"[][()<>{}/%\000\011\012\014\015\040]" + whitespace = rb"[\000\011\012\014\015\040]" + whitespace_or_hex = rb"[\000\011\012\014\015\0400-9a-fA-F]" + whitespace_optional = whitespace + b"*" + whitespace_mandatory = whitespace + b"+" + # No "\012" aka "\n" or "\015" aka "\r": + whitespace_optional_no_nl = rb"[\000\011\014\040]*" + newline_only = rb"[\r\n]+" + newline = whitespace_optional_no_nl + newline_only + whitespace_optional_no_nl + re_trailer_end = re.compile( + whitespace_mandatory + + rb"trailer" + + whitespace_optional + + rb"<<(.*>>)" + + newline + + rb"startxref" + + newline + + rb"([0-9]+)" + + newline + + rb"%%EOF" + + whitespace_optional + + rb"$", + re.DOTALL, + ) + re_trailer_prev = re.compile( + whitespace_optional + + rb"trailer" + + whitespace_optional + + rb"<<(.*?>>)" + + newline + + rb"startxref" + + newline + + rb"([0-9]+)" + + newline + + rb"%%EOF" + + whitespace_optional, + re.DOTALL, + ) + + def read_trailer(self) -> None: + assert self.buf is not None + search_start_offset = len(self.buf) - 16384 + if search_start_offset < self.start_offset: + search_start_offset = self.start_offset + m = self.re_trailer_end.search(self.buf, search_start_offset) + check_format_condition(m is not None, "trailer end not found") + # make sure we found the LAST trailer + last_match = m + while m: + last_match = m + m = self.re_trailer_end.search(self.buf, m.start() + 16) + if not m: + m = last_match + assert m is not None + trailer_data = m.group(1) + self.last_xref_section_offset = int(m.group(2)) + self.trailer_dict = self.interpret_trailer(trailer_data) + self.xref_table = XrefTable() + self.read_xref_table(xref_section_offset=self.last_xref_section_offset) + if b"Prev" in self.trailer_dict: + self.read_prev_trailer(self.trailer_dict[b"Prev"]) + + def read_prev_trailer( + self, xref_section_offset: int, processed_offsets: list[int] | None = None + ) -> None: + assert self.buf is not None + trailer_offset = self.read_xref_table(xref_section_offset=xref_section_offset) + m = self.re_trailer_prev.search( + self.buf[trailer_offset : trailer_offset + 16384] + ) + check_format_condition(m is not None, "previous trailer not found") + assert m is not None + trailer_data = m.group(1) + check_format_condition( + int(m.group(2)) == xref_section_offset, + "xref section offset in previous trailer doesn't match what was expected", + ) + trailer_dict = self.interpret_trailer(trailer_data) + if b"Prev" in trailer_dict: + if processed_offsets is None: + processed_offsets = [] + processed_offsets.append(xref_section_offset) + check_format_condition( + trailer_dict[b"Prev"] not in processed_offsets, "trailer loop found" + ) + self.read_prev_trailer(trailer_dict[b"Prev"], processed_offsets) + + re_whitespace_optional = re.compile(whitespace_optional) + re_name = re.compile( + whitespace_optional + + rb"/([!-$&'*-.0-;=?-Z\\^-z|~]+)(?=" + + delimiter_or_ws + + rb")" + ) + re_dict_start = re.compile(whitespace_optional + rb"<<") + re_dict_end = re.compile(whitespace_optional + rb">>" + whitespace_optional) + + @classmethod + def interpret_trailer(cls, trailer_data: bytes) -> dict[bytes, Any]: + trailer = {} + offset = 0 + while True: + m = cls.re_name.match(trailer_data, offset) + if not m: + m = cls.re_dict_end.match(trailer_data, offset) + check_format_condition( + m is not None and m.end() == len(trailer_data), + "name not found in trailer, remaining data: " + + repr(trailer_data[offset:]), + ) + break + key = cls.interpret_name(m.group(1)) + assert isinstance(key, bytes) + value, value_offset = cls.get_value(trailer_data, m.end()) + trailer[key] = value + if value_offset is None: + break + offset = value_offset + check_format_condition( + b"Size" in trailer and isinstance(trailer[b"Size"], int), + "/Size not in trailer or not an integer", + ) + check_format_condition( + b"Root" in trailer and isinstance(trailer[b"Root"], IndirectReference), + "/Root not in trailer or not an indirect reference", + ) + return trailer + + re_hashes_in_name = re.compile(rb"([^#]*)(#([0-9a-fA-F]{2}))?") + + @classmethod + def interpret_name(cls, raw: bytes, as_text: bool = False) -> str | bytes: + name = b"" + for m in cls.re_hashes_in_name.finditer(raw): + if m.group(3): + name += m.group(1) + bytearray.fromhex(m.group(3).decode("us-ascii")) + else: + name += m.group(1) + if as_text: + return name.decode("utf-8") + else: + return bytes(name) + + re_null = re.compile(whitespace_optional + rb"null(?=" + delimiter_or_ws + rb")") + re_true = re.compile(whitespace_optional + rb"true(?=" + delimiter_or_ws + rb")") + re_false = re.compile(whitespace_optional + rb"false(?=" + delimiter_or_ws + rb")") + re_int = re.compile( + whitespace_optional + rb"([-+]?[0-9]+)(?=" + delimiter_or_ws + rb")" + ) + re_real = re.compile( + whitespace_optional + + rb"([-+]?([0-9]+\.[0-9]*|[0-9]*\.[0-9]+))(?=" + + delimiter_or_ws + + rb")" + ) + re_array_start = re.compile(whitespace_optional + rb"\[") + re_array_end = re.compile(whitespace_optional + rb"]") + re_string_hex = re.compile( + whitespace_optional + rb"<(" + whitespace_or_hex + rb"*)>" + ) + re_string_lit = re.compile(whitespace_optional + rb"\(") + re_indirect_reference = re.compile( + whitespace_optional + + rb"([-+]?[0-9]+)" + + whitespace_mandatory + + rb"([-+]?[0-9]+)" + + whitespace_mandatory + + rb"R(?=" + + delimiter_or_ws + + rb")" + ) + re_indirect_def_start = re.compile( + whitespace_optional + + rb"([-+]?[0-9]+)" + + whitespace_mandatory + + rb"([-+]?[0-9]+)" + + whitespace_mandatory + + rb"obj(?=" + + delimiter_or_ws + + rb")" + ) + re_indirect_def_end = re.compile( + whitespace_optional + rb"endobj(?=" + delimiter_or_ws + rb")" + ) + re_comment = re.compile( + rb"(" + whitespace_optional + rb"%[^\r\n]*" + newline + rb")*" + ) + re_stream_start = re.compile(whitespace_optional + rb"stream\r?\n") + re_stream_end = re.compile( + whitespace_optional + rb"endstream(?=" + delimiter_or_ws + rb")" + ) + + @classmethod + def get_value( + cls, + data: bytes | bytearray | memoryview | mmap.mmap, + offset: int, + expect_indirect: IndirectReference | None = None, + max_nesting: int = -1, + ) -> tuple[Any, int | None]: + if max_nesting == 0: + return None, None + m = cls.re_comment.match(data, offset) + if m: + offset = m.end() + m = cls.re_indirect_def_start.match(data, offset) + if m: + check_format_condition( + int(m.group(1)) > 0, + "indirect object definition: object ID must be greater than 0", + ) + check_format_condition( + int(m.group(2)) >= 0, + "indirect object definition: generation must be non-negative", + ) + check_format_condition( + expect_indirect is None + or expect_indirect + == IndirectReference(int(m.group(1)), int(m.group(2))), + "indirect object definition different than expected", + ) + object, object_offset = cls.get_value( + data, m.end(), max_nesting=max_nesting - 1 + ) + if object_offset is None: + return object, None + m = cls.re_indirect_def_end.match(data, object_offset) + check_format_condition( + m is not None, "indirect object definition end not found" + ) + assert m is not None + return object, m.end() + check_format_condition( + not expect_indirect, "indirect object definition not found" + ) + m = cls.re_indirect_reference.match(data, offset) + if m: + check_format_condition( + int(m.group(1)) > 0, + "indirect object reference: object ID must be greater than 0", + ) + check_format_condition( + int(m.group(2)) >= 0, + "indirect object reference: generation must be non-negative", + ) + return IndirectReference(int(m.group(1)), int(m.group(2))), m.end() + m = cls.re_dict_start.match(data, offset) + if m: + offset = m.end() + result: dict[Any, Any] = {} + m = cls.re_dict_end.match(data, offset) + current_offset: int | None = offset + while not m: + assert current_offset is not None + key, current_offset = cls.get_value( + data, current_offset, max_nesting=max_nesting - 1 + ) + if current_offset is None: + return result, None + value, current_offset = cls.get_value( + data, current_offset, max_nesting=max_nesting - 1 + ) + result[key] = value + if current_offset is None: + return result, None + m = cls.re_dict_end.match(data, current_offset) + current_offset = m.end() + m = cls.re_stream_start.match(data, current_offset) + if m: + stream_len = result.get(b"Length") + if stream_len is None or not isinstance(stream_len, int): + msg = f"bad or missing Length in stream dict ({stream_len})" + raise PdfFormatError(msg) + stream_data = bytes(data[m.end() : m.end() + stream_len]) + m = cls.re_stream_end.match(data, m.end() + stream_len) + check_format_condition(m is not None, "stream end not found") + assert m is not None + current_offset = m.end() + return PdfStream(PdfDict(result), stream_data), current_offset + return PdfDict(result), current_offset + m = cls.re_array_start.match(data, offset) + if m: + offset = m.end() + results = [] + m = cls.re_array_end.match(data, offset) + current_offset = offset + while not m: + assert current_offset is not None + value, current_offset = cls.get_value( + data, current_offset, max_nesting=max_nesting - 1 + ) + results.append(value) + if current_offset is None: + return results, None + m = cls.re_array_end.match(data, current_offset) + return results, m.end() + m = cls.re_null.match(data, offset) + if m: + return None, m.end() + m = cls.re_true.match(data, offset) + if m: + return True, m.end() + m = cls.re_false.match(data, offset) + if m: + return False, m.end() + m = cls.re_name.match(data, offset) + if m: + return PdfName(cls.interpret_name(m.group(1))), m.end() + m = cls.re_int.match(data, offset) + if m: + return int(m.group(1)), m.end() + m = cls.re_real.match(data, offset) + if m: + # XXX Decimal instead of float??? + return float(m.group(1)), m.end() + m = cls.re_string_hex.match(data, offset) + if m: + # filter out whitespace + hex_string = bytearray( + b for b in m.group(1) if b in b"0123456789abcdefABCDEF" + ) + if len(hex_string) % 2 == 1: + # append a 0 if the length is not even - yes, at the end + hex_string.append(ord(b"0")) + return bytearray.fromhex(hex_string.decode("us-ascii")), m.end() + m = cls.re_string_lit.match(data, offset) + if m: + return cls.get_literal_string(data, m.end()) + # return None, offset # fallback (only for debugging) + msg = f"unrecognized object: {repr(data[offset : offset + 32])}" + raise PdfFormatError(msg) + + re_lit_str_token = re.compile( + rb"(\\[nrtbf()\\])|(\\[0-9]{1,3})|(\\(\r\n|\r|\n))|(\r\n|\r|\n)|(\()|(\))" + ) + escaped_chars = { + b"n": b"\n", + b"r": b"\r", + b"t": b"\t", + b"b": b"\b", + b"f": b"\f", + b"(": b"(", + b")": b")", + b"\\": b"\\", + ord(b"n"): b"\n", + ord(b"r"): b"\r", + ord(b"t"): b"\t", + ord(b"b"): b"\b", + ord(b"f"): b"\f", + ord(b"("): b"(", + ord(b")"): b")", + ord(b"\\"): b"\\", + } + + @classmethod + def get_literal_string( + cls, data: bytes | bytearray | memoryview | mmap.mmap, offset: int + ) -> tuple[bytes, int]: + nesting_depth = 0 + result = bytearray() + for m in cls.re_lit_str_token.finditer(data, offset): + result.extend(data[offset : m.start()]) + if m.group(1): + result.extend(cls.escaped_chars[m.group(1)[1]]) + elif m.group(2): + result.append(int(m.group(2)[1:], 8)) + elif m.group(3): + pass + elif m.group(5): + result.extend(b"\n") + elif m.group(6): + result.extend(b"(") + nesting_depth += 1 + elif m.group(7): + if nesting_depth == 0: + return bytes(result), m.end() + result.extend(b")") + nesting_depth -= 1 + offset = m.end() + msg = "unfinished literal string" + raise PdfFormatError(msg) + + re_xref_section_start = re.compile(whitespace_optional + rb"xref" + newline) + re_xref_subsection_start = re.compile( + whitespace_optional + + rb"([0-9]+)" + + whitespace_mandatory + + rb"([0-9]+)" + + whitespace_optional + + newline_only + ) + re_xref_entry = re.compile(rb"([0-9]{10}) ([0-9]{5}) ([fn])( \r| \n|\r\n)") + + def read_xref_table(self, xref_section_offset: int) -> int: + assert self.buf is not None + subsection_found = False + m = self.re_xref_section_start.match( + self.buf, xref_section_offset + self.start_offset + ) + check_format_condition(m is not None, "xref section start not found") + assert m is not None + offset = m.end() + while True: + m = self.re_xref_subsection_start.match(self.buf, offset) + if not m: + check_format_condition( + subsection_found, "xref subsection start not found" + ) + break + subsection_found = True + offset = m.end() + first_object = int(m.group(1)) + num_objects = int(m.group(2)) + for i in range(first_object, first_object + num_objects): + m = self.re_xref_entry.match(self.buf, offset) + check_format_condition(m is not None, "xref entry not found") + assert m is not None + offset = m.end() + is_free = m.group(3) == b"f" + if not is_free: + generation = int(m.group(2)) + new_entry = (int(m.group(1)), generation) + if i not in self.xref_table: + self.xref_table[i] = new_entry + return offset + + def read_indirect(self, ref: IndirectReference, max_nesting: int = -1) -> Any: + offset, generation = self.xref_table[ref[0]] + check_format_condition( + generation == ref[1], + f"expected to find generation {ref[1]} for object ID {ref[0]} in xref " + f"table, instead found generation {generation} at offset {offset}", + ) + assert self.buf is not None + value = self.get_value( + self.buf, + offset + self.start_offset, + expect_indirect=IndirectReference(*ref), + max_nesting=max_nesting, + )[0] + self.cached_objects[ref] = value + return value + + def linearize_page_tree( + self, node: PdfDict | None = None + ) -> list[IndirectReference]: + page_node = node if node is not None else self.page_tree_root + check_format_condition( + page_node[b"Type"] == b"Pages", "/Type of page tree node is not /Pages" + ) + pages = [] + for kid in page_node[b"Kids"]: + kid_object = self.read_indirect(kid) + if kid_object[b"Type"] == b"Page": + pages.append(kid) + else: + pages.extend(self.linearize_page_tree(node=kid_object)) + return pages diff --git a/.venv/lib/python3.11/site-packages/PIL/PixarImagePlugin.py b/.venv/lib/python3.11/site-packages/PIL/PixarImagePlugin.py new file mode 100644 index 0000000000000000000000000000000000000000..d2b6d0a97e4bd230134d4741fc997baca5b4507f --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/PixarImagePlugin.py @@ -0,0 +1,72 @@ +# +# The Python Imaging Library. +# $Id$ +# +# PIXAR raster support for PIL +# +# history: +# 97-01-29 fl Created +# +# notes: +# This is incomplete; it is based on a few samples created with +# Photoshop 2.5 and 3.0, and a summary description provided by +# Greg Coats . Hopefully, "L" and +# "RGBA" support will be added in future versions. +# +# Copyright (c) Secret Labs AB 1997. +# Copyright (c) Fredrik Lundh 1997. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +from . import Image, ImageFile +from ._binary import i16le as i16 + +# +# helpers + + +def _accept(prefix: bytes) -> bool: + return prefix.startswith(b"\200\350\000\000") + + +## +# Image plugin for PIXAR raster images. + + +class PixarImageFile(ImageFile.ImageFile): + format = "PIXAR" + format_description = "PIXAR raster image" + + def _open(self) -> None: + # assuming a 4-byte magic label + assert self.fp is not None + + s = self.fp.read(4) + if not _accept(s): + msg = "not a PIXAR file" + raise SyntaxError(msg) + + # read rest of header + s = s + self.fp.read(508) + + self._size = i16(s, 418), i16(s, 416) + + # get channel/depth descriptions + mode = i16(s, 424), i16(s, 426) + + if mode == (14, 2): + self._mode = "RGB" + # FIXME: to be continued... + + # create tile descriptor (assuming "dumped") + self.tile = [ImageFile._Tile("raw", (0, 0) + self.size, 1024, self.mode)] + + +# +# -------------------------------------------------------------------- + +Image.register_open(PixarImageFile.format, PixarImageFile, _accept) + +Image.register_extension(PixarImageFile.format, ".pxr") diff --git a/.venv/lib/python3.11/site-packages/PIL/PngImagePlugin.py b/.venv/lib/python3.11/site-packages/PIL/PngImagePlugin.py new file mode 100644 index 0000000000000000000000000000000000000000..058fb831c9e3699792eadd57242419817edcda13 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/PngImagePlugin.py @@ -0,0 +1,1578 @@ +# +# The Python Imaging Library. +# $Id$ +# +# PNG support code +# +# See "PNG (Portable Network Graphics) Specification, version 1.0; +# W3C Recommendation", 1996-10-01, Thomas Boutell (ed.). +# +# history: +# 1996-05-06 fl Created (couldn't resist it) +# 1996-12-14 fl Upgraded, added read and verify support (0.2) +# 1996-12-15 fl Separate PNG stream parser +# 1996-12-29 fl Added write support, added getchunks +# 1996-12-30 fl Eliminated circular references in decoder (0.3) +# 1998-07-12 fl Read/write 16-bit images as mode I (0.4) +# 2001-02-08 fl Added transparency support (from Zircon) (0.5) +# 2001-04-16 fl Don't close data source in "open" method (0.6) +# 2004-02-24 fl Don't even pretend to support interlaced files (0.7) +# 2004-08-31 fl Do basic sanity check on chunk identifiers (0.8) +# 2004-09-20 fl Added PngInfo chunk container +# 2004-12-18 fl Added DPI read support (based on code by Niki Spahiev) +# 2008-08-13 fl Added tRNS support for RGB images +# 2009-03-06 fl Support for preserving ICC profiles (by Florian Hoech) +# 2009-03-08 fl Added zTXT support (from Lowell Alleman) +# 2009-03-29 fl Read interlaced PNG files (from Conrado Porto Lopes Gouvua) +# +# Copyright (c) 1997-2009 by Secret Labs AB +# Copyright (c) 1996 by Fredrik Lundh +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import itertools +import logging +import re +import struct +import warnings +import zlib +from enum import IntEnum +from fractions import Fraction +from typing import IO, NamedTuple, cast + +from . import Image, ImageChops, ImageFile, ImagePalette, ImageSequence +from ._binary import i16be as i16 +from ._binary import i32be as i32 +from ._binary import o8 +from ._binary import o16be as o16 +from ._binary import o32be as o32 +from ._deprecate import deprecate +from ._util import DeferredError + +TYPE_CHECKING = False +if TYPE_CHECKING: + from collections.abc import Callable + from typing import Any, NoReturn + + from . import _imaging + +logger = logging.getLogger(__name__) + +is_cid = re.compile(rb"\w\w\w\w").match + + +_MAGIC = b"\211PNG\r\n\032\n" + + +_MODES = { + # supported bits/color combinations, and corresponding modes/rawmodes + # Grayscale + (1, 0): ("1", "1"), + (2, 0): ("L", "L;2"), + (4, 0): ("L", "L;4"), + (8, 0): ("L", "L"), + (16, 0): ("I;16", "I;16B"), + # Truecolour + (8, 2): ("RGB", "RGB"), + (16, 2): ("RGB", "RGB;16B"), + # Indexed-colour + (1, 3): ("P", "P;1"), + (2, 3): ("P", "P;2"), + (4, 3): ("P", "P;4"), + (8, 3): ("P", "P"), + # Grayscale with alpha + (8, 4): ("LA", "LA"), + (16, 4): ("RGBA", "LA;16B"), # LA;16B->LA not yet available + # Truecolour with alpha + (8, 6): ("RGBA", "RGBA"), + (16, 6): ("RGBA", "RGBA;16B"), +} + + +_simple_palette = re.compile(b"^\xff*\x00\xff*$") + +MAX_TEXT_CHUNK = ImageFile.SAFEBLOCK +""" +Maximum decompressed size for a iTXt or zTXt chunk. +Eliminates decompression bombs where compressed chunks can expand 1000x. +See :ref:`Text in PNG File Format`. +""" +MAX_TEXT_MEMORY = 64 * MAX_TEXT_CHUNK +""" +Set the maximum total text chunk size. +See :ref:`Text in PNG File Format`. +""" + + +# APNG frame disposal modes +class Disposal(IntEnum): + OP_NONE = 0 + """ + No disposal is done on this frame before rendering the next frame. + See :ref:`Saving APNG sequences`. + """ + OP_BACKGROUND = 1 + """ + This frame’s modified region is cleared to fully transparent black before rendering + the next frame. + See :ref:`Saving APNG sequences`. + """ + OP_PREVIOUS = 2 + """ + This frame’s modified region is reverted to the previous frame’s contents before + rendering the next frame. + See :ref:`Saving APNG sequences`. + """ + + +# APNG frame blend modes +class Blend(IntEnum): + OP_SOURCE = 0 + """ + All color components of this frame, including alpha, overwrite the previous output + image contents. + See :ref:`Saving APNG sequences`. + """ + OP_OVER = 1 + """ + This frame should be alpha composited with the previous output image contents. + See :ref:`Saving APNG sequences`. + """ + + +def _safe_zlib_decompress(s: bytes) -> bytes: + dobj = zlib.decompressobj() + plaintext = dobj.decompress(s, MAX_TEXT_CHUNK) + if dobj.unconsumed_tail: + msg = "Decompressed data too large for PngImagePlugin.MAX_TEXT_CHUNK" + raise ValueError(msg) + return plaintext + + +def _crc32(data: bytes, seed: int = 0) -> int: + return zlib.crc32(data, seed) & 0xFFFFFFFF + + +# -------------------------------------------------------------------- +# Support classes. Suitable for PNG and related formats like MNG etc. + + +class ChunkStream: + def __init__(self, fp: IO[bytes]) -> None: + self.fp: IO[bytes] | None = fp + self.queue: list[tuple[bytes, int, int]] | None = [] + + def read(self) -> tuple[bytes, int, int]: + """Fetch a new chunk. Returns header information.""" + cid = None + + assert self.fp is not None + if self.queue: + cid, pos, length = self.queue.pop() + self.fp.seek(pos) + else: + s = self.fp.read(8) + cid = s[4:] + pos = self.fp.tell() + length = i32(s) + + if not is_cid(cid): + if not ImageFile.LOAD_TRUNCATED_IMAGES: + msg = f"broken PNG file (chunk {repr(cid)})" + raise SyntaxError(msg) + + return cid, pos, length + + def __enter__(self) -> ChunkStream: + return self + + def __exit__(self, *args: object) -> None: + self.close() + + def close(self) -> None: + self.queue = self.fp = None + + def push(self, cid: bytes, pos: int, length: int) -> None: + assert self.queue is not None + self.queue.append((cid, pos, length)) + + def call(self, cid: bytes, pos: int, length: int) -> bytes: + """Call the appropriate chunk handler""" + + logger.debug("STREAM %r %s %s", cid, pos, length) + return getattr(self, f"chunk_{cid.decode('ascii')}")(pos, length) + + def crc(self, cid: bytes, data: bytes) -> None: + """Read and verify checksum""" + + # Skip CRC checks for ancillary chunks if allowed to load truncated + # images + # 5th byte of first char is 1 [specs, section 5.4] + if ImageFile.LOAD_TRUNCATED_IMAGES and (cid[0] >> 5 & 1): + self.crc_skip(cid, data) + return + + assert self.fp is not None + try: + crc1 = _crc32(data, _crc32(cid)) + crc2 = i32(self.fp.read(4)) + if crc1 != crc2: + msg = f"broken PNG file (bad header checksum in {repr(cid)})" + raise SyntaxError(msg) + except struct.error as e: + msg = f"broken PNG file (incomplete checksum in {repr(cid)})" + raise SyntaxError(msg) from e + + def crc_skip(self, cid: bytes, data: bytes) -> None: + """Read checksum""" + + assert self.fp is not None + self.fp.read(4) + + def verify(self, endchunk: bytes = b"IEND") -> list[bytes]: + # Simple approach; just calculate checksum for all remaining + # blocks. Must be called directly after open. + + cids = [] + + assert self.fp is not None + while True: + try: + cid, pos, length = self.read() + except struct.error as e: + msg = "truncated PNG file" + raise OSError(msg) from e + + if cid == endchunk: + break + self.crc(cid, ImageFile._safe_read(self.fp, length)) + cids.append(cid) + + return cids + + +class iTXt(str): + """ + Subclass of string to allow iTXt chunks to look like strings while + keeping their extra information + + """ + + lang: str | bytes | None + tkey: str | bytes | None + + @staticmethod + def __new__( + cls, text: str, lang: str | None = None, tkey: str | None = None + ) -> iTXt: + """ + :param cls: the class to use when creating the instance + :param text: value for this key + :param lang: language code + :param tkey: UTF-8 version of the key name + """ + + self = str.__new__(cls, text) + self.lang = lang + self.tkey = tkey + return self + + +class PngInfo: + """ + PNG chunk container (for use with save(pnginfo=)) + + """ + + def __init__(self) -> None: + self.chunks: list[tuple[bytes, bytes, bool]] = [] + + def add(self, cid: bytes, data: bytes, after_idat: bool = False) -> None: + """Appends an arbitrary chunk. Use with caution. + + :param cid: a byte string, 4 bytes long. + :param data: a byte string of the encoded data + :param after_idat: for use with private chunks. Whether the chunk + should be written after IDAT + + """ + + self.chunks.append((cid, data, after_idat)) + + def add_itxt( + self, + key: str | bytes, + value: str | bytes, + lang: str | bytes = "", + tkey: str | bytes = "", + zip: bool = False, + ) -> None: + """Appends an iTXt chunk. + + :param key: latin-1 encodable text key name + :param value: value for this key + :param lang: language code + :param tkey: UTF-8 version of the key name + :param zip: compression flag + + """ + + if not isinstance(key, bytes): + key = key.encode("latin-1", "strict") + if not isinstance(value, bytes): + value = value.encode("utf-8", "strict") + if not isinstance(lang, bytes): + lang = lang.encode("utf-8", "strict") + if not isinstance(tkey, bytes): + tkey = tkey.encode("utf-8", "strict") + + if zip: + self.add( + b"iTXt", + key + b"\0\x01\0" + lang + b"\0" + tkey + b"\0" + zlib.compress(value), + ) + else: + self.add(b"iTXt", key + b"\0\0\0" + lang + b"\0" + tkey + b"\0" + value) + + def add_text( + self, key: str | bytes, value: str | bytes | iTXt, zip: bool = False + ) -> None: + """Appends a text chunk. + + :param key: latin-1 encodable text key name + :param value: value for this key, text or an + :py:class:`PIL.PngImagePlugin.iTXt` instance + :param zip: compression flag + + """ + if isinstance(value, iTXt): + return self.add_itxt( + key, + value, + value.lang if value.lang is not None else b"", + value.tkey if value.tkey is not None else b"", + zip=zip, + ) + + # The tEXt chunk stores latin-1 text + if not isinstance(value, bytes): + try: + value = value.encode("latin-1", "strict") + except UnicodeError: + return self.add_itxt(key, value, zip=zip) + + if not isinstance(key, bytes): + key = key.encode("latin-1", "strict") + + if zip: + self.add(b"zTXt", key + b"\0\0" + zlib.compress(value)) + else: + self.add(b"tEXt", key + b"\0" + value) + + +# -------------------------------------------------------------------- +# PNG image stream (IHDR/IEND) + + +class _RewindState(NamedTuple): + info: dict[str | tuple[int, int], Any] + tile: list[ImageFile._Tile] + seq_num: int | None + + +class PngStream(ChunkStream): + def __init__(self, fp: IO[bytes]) -> None: + super().__init__(fp) + + # local copies of Image attributes + self.im_info: dict[str | tuple[int, int], Any] = {} + self.im_text: dict[str, str | iTXt] = {} + self.im_size = (0, 0) + self.im_mode = "" + self.im_tile: list[ImageFile._Tile] = [] + self.im_palette: tuple[str, bytes] | None = None + self.im_custom_mimetype: str | None = None + self.im_n_frames: int | None = None + self._seq_num: int | None = None + self.rewind_state = _RewindState({}, [], None) + + self.text_memory = 0 + + def __enter__(self) -> PngStream: + return self + + def check_text_memory(self, chunklen: int) -> None: + self.text_memory += chunklen + if self.text_memory > MAX_TEXT_MEMORY: + msg = ( + "Too much memory used in text chunks: " + f"{self.text_memory}>MAX_TEXT_MEMORY" + ) + raise ValueError(msg) + + def save_rewind(self) -> None: + self.rewind_state = _RewindState( + self.im_info.copy(), + self.im_tile, + self._seq_num, + ) + + def rewind(self) -> None: + self.im_info = self.rewind_state.info.copy() + self.im_tile = self.rewind_state.tile + self._seq_num = self.rewind_state.seq_num + + def chunk_iCCP(self, pos: int, length: int) -> bytes: + # ICC profile + assert self.fp is not None + s = ImageFile._safe_read(self.fp, length) + # according to PNG spec, the iCCP chunk contains: + # Profile name 1-79 bytes (character string) + # Null separator 1 byte (null character) + # Compression method 1 byte (0) + # Compressed profile n bytes (zlib with deflate compression) + i = s.find(b"\0") + logger.debug("iCCP profile name %r", s[:i]) + comp_method = s[i + 1] + logger.debug("Compression method %s", comp_method) + if comp_method != 0: + msg = f"Unknown compression method {comp_method} in iCCP chunk" + raise SyntaxError(msg) + try: + icc_profile = _safe_zlib_decompress(s[i + 2 :]) + except ValueError: + if ImageFile.LOAD_TRUNCATED_IMAGES: + icc_profile = None + else: + raise + except zlib.error: + icc_profile = None # FIXME + self.im_info["icc_profile"] = icc_profile + return s + + def chunk_IHDR(self, pos: int, length: int) -> bytes: + # image header + assert self.fp is not None + s = ImageFile._safe_read(self.fp, length) + if length < 13: + if ImageFile.LOAD_TRUNCATED_IMAGES: + return s + msg = "Truncated IHDR chunk" + raise ValueError(msg) + self.im_size = i32(s, 0), i32(s, 4) + try: + self.im_mode, self.im_rawmode = _MODES[(s[8], s[9])] + except KeyError: + pass + if s[12]: + self.im_info["interlace"] = 1 + if s[11]: + msg = "unknown filter category" + raise SyntaxError(msg) + return s + + def chunk_IDAT(self, pos: int, length: int) -> NoReturn: + # image data + if "bbox" in self.im_info: + tile = [ImageFile._Tile("zip", self.im_info["bbox"], pos, self.im_rawmode)] + else: + if self.im_n_frames is not None: + self.im_info["default_image"] = True + tile = [ImageFile._Tile("zip", (0, 0) + self.im_size, pos, self.im_rawmode)] + self.im_tile = tile + self.im_idat = length + msg = "image data found" + raise EOFError(msg) + + def chunk_IEND(self, pos: int, length: int) -> NoReturn: + msg = "end of PNG image" + raise EOFError(msg) + + def chunk_PLTE(self, pos: int, length: int) -> bytes: + # palette + assert self.fp is not None + s = ImageFile._safe_read(self.fp, length) + if self.im_mode == "P": + self.im_palette = "RGB", s + return s + + def chunk_tRNS(self, pos: int, length: int) -> bytes: + # transparency + assert self.fp is not None + s = ImageFile._safe_read(self.fp, length) + if self.im_mode == "P": + if _simple_palette.match(s): + # tRNS contains only one full-transparent entry, + # other entries are full opaque + i = s.find(b"\0") + if i >= 0: + self.im_info["transparency"] = i + else: + # otherwise, we have a byte string with one alpha value + # for each palette entry + self.im_info["transparency"] = s + elif self.im_mode == "1": + self.im_info["transparency"] = 255 if i16(s) else 0 + elif self.im_mode in ("L", "I;16"): + self.im_info["transparency"] = i16(s) + elif self.im_mode == "RGB": + self.im_info["transparency"] = i16(s), i16(s, 2), i16(s, 4) + return s + + def chunk_gAMA(self, pos: int, length: int) -> bytes: + # gamma setting + assert self.fp is not None + s = ImageFile._safe_read(self.fp, length) + self.im_info["gamma"] = i32(s) / 100000.0 + return s + + def chunk_cHRM(self, pos: int, length: int) -> bytes: + # chromaticity, 8 unsigned ints, actual value is scaled by 100,000 + # WP x,y, Red x,y, Green x,y Blue x,y + + assert self.fp is not None + s = ImageFile._safe_read(self.fp, length) + raw_vals = struct.unpack(f">{len(s) // 4}I", s) + self.im_info["chromaticity"] = tuple(elt / 100000.0 for elt in raw_vals) + return s + + def chunk_sRGB(self, pos: int, length: int) -> bytes: + # srgb rendering intent, 1 byte + # 0 perceptual + # 1 relative colorimetric + # 2 saturation + # 3 absolute colorimetric + + assert self.fp is not None + s = ImageFile._safe_read(self.fp, length) + if length < 1: + if ImageFile.LOAD_TRUNCATED_IMAGES: + return s + msg = "Truncated sRGB chunk" + raise ValueError(msg) + self.im_info["srgb"] = s[0] + return s + + def chunk_pHYs(self, pos: int, length: int) -> bytes: + # pixels per unit + assert self.fp is not None + s = ImageFile._safe_read(self.fp, length) + if length < 9: + if ImageFile.LOAD_TRUNCATED_IMAGES: + return s + msg = "Truncated pHYs chunk" + raise ValueError(msg) + px, py = i32(s, 0), i32(s, 4) + unit = s[8] + if unit == 1: # meter + dpi = px * 0.0254, py * 0.0254 + self.im_info["dpi"] = dpi + elif unit == 0: + self.im_info["aspect"] = px, py + return s + + def chunk_tEXt(self, pos: int, length: int) -> bytes: + # text + assert self.fp is not None + s = ImageFile._safe_read(self.fp, length) + try: + k, v = s.split(b"\0", 1) + except ValueError: + # fallback for broken tEXt tags + k = s + v = b"" + if k: + k_str = k.decode("latin-1", "strict") + v_str = v.decode("latin-1", "replace") + + self.im_info[k_str] = v if k == b"exif" else v_str + self.im_text[k_str] = v_str + self.check_text_memory(len(v_str)) + + return s + + def chunk_zTXt(self, pos: int, length: int) -> bytes: + # compressed text + assert self.fp is not None + s = ImageFile._safe_read(self.fp, length) + try: + k, v = s.split(b"\0", 1) + except ValueError: + k = s + v = b"" + if v: + comp_method = v[0] + else: + comp_method = 0 + if comp_method != 0: + msg = f"Unknown compression method {comp_method} in zTXt chunk" + raise SyntaxError(msg) + try: + v = _safe_zlib_decompress(v[1:]) + except ValueError: + if ImageFile.LOAD_TRUNCATED_IMAGES: + v = b"" + else: + raise + except zlib.error: + v = b"" + + if k: + k_str = k.decode("latin-1", "strict") + v_str = v.decode("latin-1", "replace") + + self.im_info[k_str] = self.im_text[k_str] = v_str + self.check_text_memory(len(v_str)) + + return s + + def chunk_iTXt(self, pos: int, length: int) -> bytes: + # international text + assert self.fp is not None + r = s = ImageFile._safe_read(self.fp, length) + try: + k, r = r.split(b"\0", 1) + except ValueError: + return s + if len(r) < 2: + return s + cf, cm, r = r[0], r[1], r[2:] + try: + lang, tk, v = r.split(b"\0", 2) + except ValueError: + return s + if cf != 0: + if cm == 0: + try: + v = _safe_zlib_decompress(v) + except ValueError: + if ImageFile.LOAD_TRUNCATED_IMAGES: + return s + else: + raise + except zlib.error: + return s + else: + return s + if k == b"XML:com.adobe.xmp": + self.im_info["xmp"] = v + try: + k_str = k.decode("latin-1", "strict") + lang_str = lang.decode("utf-8", "strict") + tk_str = tk.decode("utf-8", "strict") + v_str = v.decode("utf-8", "strict") + except UnicodeError: + return s + + self.im_info[k_str] = self.im_text[k_str] = iTXt(v_str, lang_str, tk_str) + self.check_text_memory(len(v_str)) + + return s + + def chunk_eXIf(self, pos: int, length: int) -> bytes: + assert self.fp is not None + s = ImageFile._safe_read(self.fp, length) + self.im_info["exif"] = b"Exif\x00\x00" + s + return s + + # APNG chunks + def chunk_acTL(self, pos: int, length: int) -> bytes: + assert self.fp is not None + s = ImageFile._safe_read(self.fp, length) + if length < 8: + if ImageFile.LOAD_TRUNCATED_IMAGES: + return s + msg = "APNG contains truncated acTL chunk" + raise ValueError(msg) + if self.im_n_frames is not None: + self.im_n_frames = None + warnings.warn("Invalid APNG, will use default PNG image if possible") + return s + n_frames = i32(s) + if n_frames == 0 or n_frames > 0x80000000: + warnings.warn("Invalid APNG, will use default PNG image if possible") + return s + self.im_n_frames = n_frames + self.im_info["loop"] = i32(s, 4) + self.im_custom_mimetype = "image/apng" + return s + + def chunk_fcTL(self, pos: int, length: int) -> bytes: + assert self.fp is not None + s = ImageFile._safe_read(self.fp, length) + if length < 26: + if ImageFile.LOAD_TRUNCATED_IMAGES: + return s + msg = "APNG contains truncated fcTL chunk" + raise ValueError(msg) + seq = i32(s) + if (self._seq_num is None and seq != 0) or ( + self._seq_num is not None and self._seq_num != seq - 1 + ): + msg = "APNG contains frame sequence errors" + raise SyntaxError(msg) + self._seq_num = seq + width, height = i32(s, 4), i32(s, 8) + px, py = i32(s, 12), i32(s, 16) + im_w, im_h = self.im_size + if px + width > im_w or py + height > im_h: + msg = "APNG contains invalid frames" + raise SyntaxError(msg) + self.im_info["bbox"] = (px, py, px + width, py + height) + delay_num, delay_den = i16(s, 20), i16(s, 22) + if delay_den == 0: + delay_den = 100 + self.im_info["duration"] = float(delay_num) / float(delay_den) * 1000 + self.im_info["disposal"] = s[24] + self.im_info["blend"] = s[25] + return s + + def chunk_fdAT(self, pos: int, length: int) -> bytes: + assert self.fp is not None + if length < 4: + if ImageFile.LOAD_TRUNCATED_IMAGES: + s = ImageFile._safe_read(self.fp, length) + return s + msg = "APNG contains truncated fDAT chunk" + raise ValueError(msg) + s = ImageFile._safe_read(self.fp, 4) + seq = i32(s) + if self._seq_num != seq - 1: + msg = "APNG contains frame sequence errors" + raise SyntaxError(msg) + self._seq_num = seq + return self.chunk_IDAT(pos + 4, length - 4) + + +# -------------------------------------------------------------------- +# PNG reader + + +def _accept(prefix: bytes) -> bool: + return prefix.startswith(_MAGIC) + + +## +# Image plugin for PNG images. + + +class PngImageFile(ImageFile.ImageFile): + format = "PNG" + format_description = "Portable network graphics" + + def _open(self) -> None: + assert self.fp is not None + if not _accept(self.fp.read(8)): + msg = "not a PNG file" + raise SyntaxError(msg) + self._fp = self.fp + self.__frame = 0 + + # + # Parse headers up to the first IDAT or fDAT chunk + + self.private_chunks: list[tuple[bytes, bytes] | tuple[bytes, bytes, bool]] = [] + self.png: PngStream | None = PngStream(self.fp) + + while True: + # + # get next chunk + + cid, pos, length = self.png.read() + + try: + s = self.png.call(cid, pos, length) + except EOFError: + break + except AttributeError: + logger.debug("%r %s %s (unknown)", cid, pos, length) + s = ImageFile._safe_read(self.fp, length) + if cid[1:2].islower(): + self.private_chunks.append((cid, s)) + + self.png.crc(cid, s) + + # + # Copy relevant attributes from the PngStream. An alternative + # would be to let the PngStream class modify these attributes + # directly, but that introduces circular references which are + # difficult to break if things go wrong in the decoder... + # (believe me, I've tried ;-) + + self._mode = self.png.im_mode + self._size = self.png.im_size + self.info = self.png.im_info + self._text: dict[str, str | iTXt] | None = None + self.tile = self.png.im_tile + self.custom_mimetype = self.png.im_custom_mimetype + self.n_frames = self.png.im_n_frames or 1 + self.default_image = self.info.get("default_image", False) + + if self.png.im_palette: + rawmode, data = self.png.im_palette + self.palette = ImagePalette.raw(rawmode, data) + + if cid == b"fdAT": + self.__prepare_idat = length - 4 + else: + self.__prepare_idat = length # used by load_prepare() + + if self.png.im_n_frames is not None: + self._close_exclusive_fp_after_loading = False + self.png.save_rewind() + self.__rewind_idat = self.__prepare_idat + self.__rewind = self._fp.tell() + if self.default_image: + # IDAT chunk contains default image and not first animation frame + self.n_frames += 1 + self._seek(0) + self.is_animated = self.n_frames > 1 + + @property + def text(self) -> dict[str, str | iTXt]: + # experimental + if self._text is None: + # iTxt, tEXt and zTXt chunks may appear at the end of the file + # So load the file to ensure that they are read + if self.is_animated: + frame = self.__frame + # for APNG, seek to the final frame before loading + self.seek(self.n_frames - 1) + self.load() + if self.is_animated: + self.seek(frame) + assert self._text is not None + return self._text + + def verify(self) -> None: + """Verify PNG file""" + + if self.fp is None: + msg = "verify must be called directly after open" + raise RuntimeError(msg) + + # back up to beginning of IDAT block + self.fp.seek(self.tile[0][2] - 8) + + assert self.png is not None + self.png.verify() + self.png.close() + + super().verify() + + def seek(self, frame: int) -> None: + if not self._seek_check(frame): + return + if frame < self.__frame: + self._seek(0, True) + + last_frame = self.__frame + try: + for f in range(self.__frame + 1, frame + 1): + self._seek(f) + except EOFError as e: + self.seek(last_frame) + msg = "no more images in APNG file" + raise EOFError(msg) from e + + def _seek(self, frame: int, rewind: bool = False) -> None: + assert self.png is not None + if isinstance(self._fp, DeferredError): + raise self._fp.ex + + self.dispose: _imaging.ImagingCore | None + dispose_extent = None + if frame == 0: + if rewind: + self._fp.seek(self.__rewind) + self.png.rewind() + self.__prepare_idat = self.__rewind_idat + self._im = None + self.info = self.png.im_info + self.tile = self.png.im_tile + self.fp = self._fp + self._prev_im = None + self.dispose = None + self.default_image = self.info.get("default_image", False) + self.dispose_op = self.info.get("disposal") + self.blend_op = self.info.get("blend") + dispose_extent = self.info.get("bbox") + self.__frame = 0 + else: + if frame != self.__frame + 1: + msg = f"cannot seek to frame {frame}" + raise ValueError(msg) + + # ensure previous frame was loaded + self.load() + + if self.dispose: + self.im.paste(self.dispose, self.dispose_extent) + self._prev_im = self.im.copy() + + self.fp = self._fp + + # advance to the next frame + if self.__prepare_idat: + ImageFile._safe_read(self.fp, self.__prepare_idat) + self.__prepare_idat = 0 + frame_start = False + while True: + self.fp.read(4) # CRC + + try: + cid, pos, length = self.png.read() + except (struct.error, SyntaxError): + break + + if cid == b"IEND": + msg = "No more images in APNG file" + raise EOFError(msg) + if cid == b"fcTL": + if frame_start: + # there must be at least one fdAT chunk between fcTL chunks + msg = "APNG missing frame data" + raise SyntaxError(msg) + frame_start = True + + try: + self.png.call(cid, pos, length) + except UnicodeDecodeError: + break + except EOFError: + if cid == b"fdAT": + length -= 4 + if frame_start: + self.__prepare_idat = length + break + ImageFile._safe_read(self.fp, length) + except AttributeError: + logger.debug("%r %s %s (unknown)", cid, pos, length) + ImageFile._safe_read(self.fp, length) + + self.__frame = frame + self.tile = self.png.im_tile + self.dispose_op = self.info.get("disposal") + self.blend_op = self.info.get("blend") + dispose_extent = self.info.get("bbox") + + if not self.tile: + msg = "image not found in APNG frame" + raise EOFError(msg) + if dispose_extent: + self.dispose_extent: tuple[float, float, float, float] = dispose_extent + + # setup frame disposal (actual disposal done when needed in the next _seek()) + if self._prev_im is None and self.dispose_op == Disposal.OP_PREVIOUS: + self.dispose_op = Disposal.OP_BACKGROUND + + self.dispose = None + if self.dispose_op == Disposal.OP_PREVIOUS: + if self._prev_im: + self.dispose = self._prev_im.copy() + self.dispose = self._crop(self.dispose, self.dispose_extent) + elif self.dispose_op == Disposal.OP_BACKGROUND: + self.dispose = Image.core.fill(self.mode, self.size) + self.dispose = self._crop(self.dispose, self.dispose_extent) + + def tell(self) -> int: + return self.__frame + + def load_prepare(self) -> None: + """internal: prepare to read PNG file""" + + if self.info.get("interlace"): + self.decoderconfig = self.decoderconfig + (1,) + + self.__idat = self.__prepare_idat # used by load_read() + ImageFile.ImageFile.load_prepare(self) + + def load_read(self, read_bytes: int) -> bytes: + """internal: read more image data""" + + assert self.png is not None + assert self.fp is not None + while self.__idat == 0: + # end of chunk, skip forward to next one + + self.fp.read(4) # CRC + + cid, pos, length = self.png.read() + + if cid not in [b"IDAT", b"DDAT", b"fdAT"]: + self.png.push(cid, pos, length) + return b"" + + if cid == b"fdAT": + try: + self.png.call(cid, pos, length) + except EOFError: + pass + self.__idat = length - 4 # sequence_num has already been read + else: + self.__idat = length # empty chunks are allowed + + # read more data from this chunk + if read_bytes <= 0: + read_bytes = self.__idat + else: + read_bytes = min(read_bytes, self.__idat) + + self.__idat = self.__idat - read_bytes + + return self.fp.read(read_bytes) + + def load_end(self) -> None: + """internal: finished reading image data""" + assert self.png is not None + assert self.fp is not None + if self.__idat != 0: + self.fp.read(self.__idat) + while True: + self.fp.read(4) # CRC + + try: + cid, pos, length = self.png.read() + except (struct.error, SyntaxError): + break + + if cid == b"IEND": + break + elif cid == b"fcTL" and self.is_animated: + # start of the next frame, stop reading + self.__prepare_idat = 0 + self.png.push(cid, pos, length) + break + + try: + self.png.call(cid, pos, length) + except UnicodeDecodeError: + break + except EOFError: + if cid == b"fdAT": + length -= 4 + try: + ImageFile._safe_read(self.fp, length) + except OSError as e: + if ImageFile.LOAD_TRUNCATED_IMAGES: + break + else: + raise e + except AttributeError: + logger.debug("%r %s %s (unknown)", cid, pos, length) + s = ImageFile._safe_read(self.fp, length) + if cid[1:2].islower(): + self.private_chunks.append((cid, s, True)) + self._text = self.png.im_text + if not self.is_animated: + self.png.close() + self.png = None + else: + if self._prev_im and self.blend_op == Blend.OP_OVER: + updated = self._crop(self.im, self.dispose_extent) + if self.im.mode == "RGB" and "transparency" in self.info: + mask = updated.convert_transparent( + "RGBA", self.info["transparency"] + ) + else: + if self.im.mode == "P" and "transparency" in self.info: + t = self.info["transparency"] + if isinstance(t, bytes): + updated.putpalettealphas(t) + elif isinstance(t, int): + updated.putpalettealpha(t) + mask = updated.convert("RGBA") + self._prev_im.paste(updated, self.dispose_extent, mask) + self.im = self._prev_im + + def _getexif(self) -> dict[int, Any] | None: + if "exif" not in self.info: + self.load() + if "exif" not in self.info and "Raw profile type exif" not in self.info: + return None + return self.getexif()._get_merged_dict() + + def getexif(self) -> Image.Exif: + if "exif" not in self.info: + self.load() + + return super().getexif() + + +# -------------------------------------------------------------------- +# PNG writer + +_OUTMODES = { + # supported PIL modes, and corresponding rawmode, bit depth and color type + "1": ("1", b"\x01", b"\x00"), + "L;1": ("L;1", b"\x01", b"\x00"), + "L;2": ("L;2", b"\x02", b"\x00"), + "L;4": ("L;4", b"\x04", b"\x00"), + "L": ("L", b"\x08", b"\x00"), + "LA": ("LA", b"\x08", b"\x04"), + "I": ("I;16B", b"\x10", b"\x00"), + "I;16": ("I;16B", b"\x10", b"\x00"), + "I;16B": ("I;16B", b"\x10", b"\x00"), + "P;1": ("P;1", b"\x01", b"\x03"), + "P;2": ("P;2", b"\x02", b"\x03"), + "P;4": ("P;4", b"\x04", b"\x03"), + "P": ("P", b"\x08", b"\x03"), + "RGB": ("RGB", b"\x08", b"\x02"), + "RGBA": ("RGBA", b"\x08", b"\x06"), +} + + +def putchunk(fp: IO[bytes], cid: bytes, *data: bytes) -> None: + """Write a PNG chunk (including CRC field)""" + + byte_data = b"".join(data) + + fp.write(o32(len(byte_data)) + cid) + fp.write(byte_data) + crc = _crc32(byte_data, _crc32(cid)) + fp.write(o32(crc)) + + +class _idat: + # wrap output from the encoder in IDAT chunks + + def __init__(self, fp: IO[bytes], chunk: Callable[..., None]) -> None: + self.fp = fp + self.chunk = chunk + + def write(self, data: bytes) -> None: + self.chunk(self.fp, b"IDAT", data) + + +class _fdat: + # wrap encoder output in fdAT chunks + + def __init__(self, fp: IO[bytes], chunk: Callable[..., None], seq_num: int) -> None: + self.fp = fp + self.chunk = chunk + self.seq_num = seq_num + + def write(self, data: bytes) -> None: + self.chunk(self.fp, b"fdAT", o32(self.seq_num), data) + self.seq_num += 1 + + +def _apply_encoderinfo(im: Image.Image, encoderinfo: dict[str, Any]) -> None: + im.encoderconfig = ( + encoderinfo.get("optimize", False), + encoderinfo.get("compress_level", -1), + encoderinfo.get("compress_type", -1), + encoderinfo.get("dictionary", b""), + ) + + +class _Frame(NamedTuple): + im: Image.Image + bbox: tuple[int, int, int, int] | None + encoderinfo: dict[str, Any] + + +def _write_multiple_frames( + im: Image.Image, + fp: IO[bytes], + chunk: Callable[..., None], + mode: str, + rawmode: str, + default_image: Image.Image | None, + append_images: list[Image.Image], +) -> Image.Image | None: + duration = im.encoderinfo.get("duration") + loop = im.encoderinfo.get("loop", im.info.get("loop", 0)) + disposal = im.encoderinfo.get("disposal", im.info.get("disposal", Disposal.OP_NONE)) + blend = im.encoderinfo.get("blend", im.info.get("blend", Blend.OP_SOURCE)) + + if default_image: + chain = itertools.chain(append_images) + else: + chain = itertools.chain([im], append_images) + + im_frames: list[_Frame] = [] + frame_count = 0 + for im_seq in chain: + for im_frame in ImageSequence.Iterator(im_seq): + if im_frame.mode == mode: + im_frame = im_frame.copy() + else: + im_frame = im_frame.convert(mode) + encoderinfo = im.encoderinfo.copy() + if isinstance(duration, (list, tuple)): + encoderinfo["duration"] = duration[frame_count] + elif duration is None and "duration" in im_frame.info: + encoderinfo["duration"] = im_frame.info["duration"] + if isinstance(disposal, (list, tuple)): + encoderinfo["disposal"] = disposal[frame_count] + if isinstance(blend, (list, tuple)): + encoderinfo["blend"] = blend[frame_count] + frame_count += 1 + + if im_frames: + previous = im_frames[-1] + prev_disposal = previous.encoderinfo.get("disposal") + prev_blend = previous.encoderinfo.get("blend") + if prev_disposal == Disposal.OP_PREVIOUS and len(im_frames) < 2: + prev_disposal = Disposal.OP_BACKGROUND + + if prev_disposal == Disposal.OP_BACKGROUND: + base_im = previous.im.copy() + dispose = Image.core.fill("RGBA", im.size, (0, 0, 0, 0)) + bbox = previous.bbox + if bbox: + dispose = dispose.crop(bbox) + else: + bbox = (0, 0) + im.size + base_im.paste(dispose, bbox) + elif prev_disposal == Disposal.OP_PREVIOUS: + base_im = im_frames[-2].im + else: + base_im = previous.im + delta = ImageChops.subtract_modulo( + im_frame.convert("RGBA"), base_im.convert("RGBA") + ) + bbox = delta.getbbox(alpha_only=False) + if ( + not bbox + and prev_disposal == encoderinfo.get("disposal") + and prev_blend == encoderinfo.get("blend") + and "duration" in encoderinfo + ): + previous.encoderinfo["duration"] += encoderinfo["duration"] + continue + else: + bbox = None + im_frames.append(_Frame(im_frame, bbox, encoderinfo)) + + if len(im_frames) == 1 and not default_image: + return im_frames[0].im + + # animation control + chunk( + fp, + b"acTL", + o32(len(im_frames)), # 0: num_frames + o32(loop), # 4: num_plays + ) + + # default image IDAT (if it exists) + if default_image: + default_im = im if im.mode == mode else im.convert(mode) + _apply_encoderinfo(default_im, im.encoderinfo) + ImageFile._save( + default_im, + cast(IO[bytes], _idat(fp, chunk)), + [ImageFile._Tile("zip", (0, 0) + im.size, 0, rawmode)], + ) + + seq_num = 0 + for frame, frame_data in enumerate(im_frames): + im_frame = frame_data.im + if not frame_data.bbox: + bbox = (0, 0) + im_frame.size + else: + bbox = frame_data.bbox + im_frame = im_frame.crop(bbox) + size = im_frame.size + encoderinfo = frame_data.encoderinfo + frame_duration = encoderinfo.get("duration", 0) + delay = Fraction(frame_duration / 1000).limit_denominator(65535) + if delay.numerator > 65535: + msg = "cannot write duration" + raise ValueError(msg) + frame_disposal = encoderinfo.get("disposal", disposal) + frame_blend = encoderinfo.get("blend", blend) + # frame control + chunk( + fp, + b"fcTL", + o32(seq_num), # sequence_number + o32(size[0]), # width + o32(size[1]), # height + o32(bbox[0]), # x_offset + o32(bbox[1]), # y_offset + o16(delay.numerator), # delay_numerator + o16(delay.denominator), # delay_denominator + o8(frame_disposal), # dispose_op + o8(frame_blend), # blend_op + ) + seq_num += 1 + # frame data + _apply_encoderinfo(im_frame, im.encoderinfo) + if frame == 0 and not default_image: + # first frame must be in IDAT chunks for backwards compatibility + ImageFile._save( + im_frame, + cast(IO[bytes], _idat(fp, chunk)), + [ImageFile._Tile("zip", (0, 0) + im_frame.size, 0, rawmode)], + ) + else: + fdat_chunks = _fdat(fp, chunk, seq_num) + ImageFile._save( + im_frame, + cast(IO[bytes], fdat_chunks), + [ImageFile._Tile("zip", (0, 0) + im_frame.size, 0, rawmode)], + ) + seq_num = fdat_chunks.seq_num + return None + + +def _save_all(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + _save(im, fp, filename, save_all=True) + + +def _save( + im: Image.Image, + fp: IO[bytes], + filename: str | bytes, + chunk: Callable[..., None] = putchunk, + save_all: bool = False, +) -> None: + # save an image to disk (called by the save method) + + if save_all: + default_image = im.encoderinfo.get( + "default_image", im.info.get("default_image") + ) + modes = set() + sizes = set() + append_images = im.encoderinfo.get("append_images", []) + for im_seq in itertools.chain([im], append_images): + for im_frame in ImageSequence.Iterator(im_seq): + modes.add(im_frame.mode) + sizes.add(im_frame.size) + for mode in ("RGBA", "RGB", "P"): + if mode in modes: + break + else: + mode = modes.pop() + size = tuple(max(frame_size[i] for frame_size in sizes) for i in range(2)) + else: + size = im.size + mode = im.mode + + outmode = mode + palette = [] + if im.palette: + palette = im.getpalette() or [] + if mode == "P": + # + # attempt to minimize storage requirements for palette images + if "bits" in im.encoderinfo: + # number of bits specified by user + colors = min(1 << im.encoderinfo["bits"], 256) + else: + # check palette contents + if im.palette: + colors = max(min(len(palette) // 3, 256), 1) + else: + colors = 256 + + if colors <= 16: + if colors <= 2: + bits = 1 + elif colors <= 4: + bits = 2 + else: + bits = 4 + outmode += f";{bits}" + + # get the corresponding PNG mode + try: + rawmode, bit_depth, color_type = _OUTMODES[outmode] + except KeyError as e: + msg = f"cannot write mode {mode} as PNG" + raise OSError(msg) from e + if outmode == "I": + deprecate("Saving I mode images as PNG", 13, stacklevel=4) + + # + # write minimal PNG file + + fp.write(_MAGIC) + + chunk( + fp, + b"IHDR", + o32(size[0]), # 0: size + o32(size[1]), + bit_depth, + color_type, + b"\0", # 10: compression + b"\0", # 11: filter category + b"\0", # 12: interlace flag + ) + + chunks = [b"cHRM", b"cICP", b"gAMA", b"sBIT", b"sRGB", b"tIME"] + + if icc := im.encoderinfo.get("icc_profile", im.info.get("icc_profile")): + # ICC profile + # according to PNG spec, the iCCP chunk contains: + # Profile name 1-79 bytes (character string) + # Null separator 1 byte (null character) + # Compression method 1 byte (0) + # Compressed profile n bytes (zlib with deflate compression) + name = b"ICC Profile" + data = name + b"\0\0" + zlib.compress(icc) + chunk(fp, b"iCCP", data) + + # You must either have sRGB or iCCP. + # Disallow sRGB chunks when an iCCP-chunk has been emitted. + chunks.remove(b"sRGB") + + if info := im.encoderinfo.get("pnginfo"): + chunks_multiple_allowed = [b"sPLT", b"iTXt", b"tEXt", b"zTXt"] + for info_chunk in info.chunks: + cid, data = info_chunk[:2] + if cid in chunks: + chunks.remove(cid) + chunk(fp, cid, data) + elif cid in chunks_multiple_allowed: + chunk(fp, cid, data) + elif cid[1:2].islower(): + # Private chunk + after_idat = len(info_chunk) == 3 and info_chunk[2] + if not after_idat: + chunk(fp, cid, data) + + if im.mode == "P": + palette_byte_number = colors * 3 + palette_bytes = bytes(palette[:palette_byte_number]) + while len(palette_bytes) < palette_byte_number: + palette_bytes += b"\0" + chunk(fp, b"PLTE", palette_bytes) + + transparency = im.encoderinfo.get("transparency", im.info.get("transparency")) + + if transparency is not None: + if im.mode == "P": + # limit to actual palette size + alpha_bytes = colors + if isinstance(transparency, bytes): + chunk(fp, b"tRNS", transparency[:alpha_bytes]) + elif isinstance(transparency, int): + transparency = max(0, min(255, transparency)) + alpha = b"\xff" * transparency + b"\0" + chunk(fp, b"tRNS", alpha[:alpha_bytes]) + else: + msg = "transparency for P must be an integer or bytes" + raise ValueError(msg) + elif im.mode in ("1", "L", "I", "I;16"): + if isinstance(transparency, int): + transparency = max(0, min(65535, transparency)) + chunk(fp, b"tRNS", o16(transparency)) + else: + msg = f"transparency for {im.mode} must be an integer" + raise ValueError(msg) + elif im.mode == "RGB": + if not isinstance(transparency, (list, tuple)): + msg = "transparency for RGB must be list or tuple" + raise ValueError(msg) + elif len(transparency) != 3: + msg = "transparency for RGB must have length 3" + raise ValueError(msg) + else: + red, green, blue = transparency + chunk(fp, b"tRNS", o16(red) + o16(green) + o16(blue)) + elif im.encoderinfo.get("transparency") is not None: + # don't bother with transparency if it's an RGBA + # and it's in the info dict. It's probably just stale. + msg = "cannot use transparency for this mode" + raise OSError(msg) + elif im.mode == "P" and im.im.getpalettemode() == "RGBA": + alpha = im.im.getpalette("RGBA", "A") + alpha_bytes = colors + chunk(fp, b"tRNS", alpha[:alpha_bytes]) + + if dpi := im.encoderinfo.get("dpi"): + chunk( + fp, + b"pHYs", + o32(int(dpi[0] / 0.0254 + 0.5)), + o32(int(dpi[1] / 0.0254 + 0.5)), + b"\x01", + ) + + if info: + chunks = [b"bKGD", b"hIST"] + for info_chunk in info.chunks: + cid, data = info_chunk[:2] + if cid in chunks: + chunks.remove(cid) + chunk(fp, cid, data) + + if exif := im.encoderinfo.get("exif"): + if isinstance(exif, Image.Exif): + exif = exif.tobytes(8) + if exif.startswith(b"Exif\x00\x00"): + exif = exif[6:] + chunk(fp, b"eXIf", exif) + + single_im: Image.Image | None = im + if save_all: + single_im = _write_multiple_frames( + im, fp, chunk, mode, rawmode, default_image, append_images + ) + if single_im: + _apply_encoderinfo(single_im, im.encoderinfo) + ImageFile._save( + single_im, + cast(IO[bytes], _idat(fp, chunk)), + [ImageFile._Tile("zip", (0, 0) + single_im.size, 0, rawmode)], + ) + + if info: + for info_chunk in info.chunks: + cid, data = info_chunk[:2] + if cid[1:2].islower(): + # Private chunk + after_idat = len(info_chunk) == 3 and info_chunk[2] + if after_idat: + chunk(fp, cid, data) + + chunk(fp, b"IEND", b"") + + if hasattr(fp, "flush"): + fp.flush() + + +# -------------------------------------------------------------------- +# PNG chunk converter + + +def getchunks(im: Image.Image, **params: Any) -> list[tuple[bytes, bytes, bytes]]: + """Return a list of PNG chunks representing this image.""" + from io import BytesIO + + chunks = [] + + def append(fp: IO[bytes], cid: bytes, *data: bytes) -> None: + byte_data = b"".join(data) + crc = o32(_crc32(byte_data, _crc32(cid))) + chunks.append((cid, byte_data, crc)) + + fp = BytesIO() + + try: + im.encoderinfo = params + _save(im, fp, "", append) + finally: + del im.encoderinfo + + return chunks + + +# -------------------------------------------------------------------- +# Registry + +Image.register_open(PngImageFile.format, PngImageFile, _accept) +Image.register_save(PngImageFile.format, _save) +Image.register_save_all(PngImageFile.format, _save_all) + +Image.register_extensions(PngImageFile.format, [".png", ".apng"]) + +Image.register_mime(PngImageFile.format, "image/png") diff --git a/.venv/lib/python3.11/site-packages/PIL/PpmImagePlugin.py b/.venv/lib/python3.11/site-packages/PIL/PpmImagePlugin.py new file mode 100644 index 0000000000000000000000000000000000000000..ca6093385be56186c2561c449d590fc1500cb04c --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/PpmImagePlugin.py @@ -0,0 +1,375 @@ +# +# The Python Imaging Library. +# $Id$ +# +# PPM support for PIL +# +# History: +# 96-03-24 fl Created +# 98-03-06 fl Write RGBA images (as RGB, that is) +# +# Copyright (c) Secret Labs AB 1997-98. +# Copyright (c) Fredrik Lundh 1996. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import math +from typing import IO + +from . import Image, ImageFile +from ._binary import i16be as i16 +from ._binary import o8 +from ._binary import o32le as o32 + +# +# -------------------------------------------------------------------- + +b_whitespace = b"\x20\x09\x0a\x0b\x0c\x0d" + +MODES = { + # standard + b"P1": "1", + b"P2": "L", + b"P3": "RGB", + b"P4": "1", + b"P5": "L", + b"P6": "RGB", + # extensions + b"P0CMYK": "CMYK", + b"Pf": "F", + # PIL extensions (for test purposes only) + b"PyP": "P", + b"PyRGBA": "RGBA", + b"PyCMYK": "CMYK", +} + + +def _accept(prefix: bytes) -> bool: + return len(prefix) >= 2 and prefix.startswith(b"P") and prefix[1] in b"0123456fy" + + +## +# Image plugin for PBM, PGM, and PPM images. + + +class PpmImageFile(ImageFile.ImageFile): + format = "PPM" + format_description = "Pbmplus image" + + def _read_magic(self) -> bytes: + assert self.fp is not None + + magic = b"" + # read until whitespace or longest available magic number + for _ in range(6): + c = self.fp.read(1) + if not c or c in b_whitespace: + break + magic += c + return magic + + def _read_token(self) -> bytes: + assert self.fp is not None + + token = b"" + while len(token) <= 10: # read until next whitespace or limit of 10 characters + c = self.fp.read(1) + if not c: + break + elif c in b_whitespace: # token ended + if not token: + # skip whitespace at start + continue + break + elif c == b"#": + # ignores rest of the line; stops at CR, LF or EOF + while self.fp.read(1) not in b"\r\n": + pass + continue + token += c + if not token: + # Token was not even 1 byte + msg = "Reached EOF while reading header" + raise ValueError(msg) + elif len(token) > 10: + msg_too_long = b"Token too long in file header: %s" % token + raise ValueError(msg_too_long) + return token + + def _open(self) -> None: + assert self.fp is not None + + magic_number = self._read_magic() + try: + mode = MODES[magic_number] + except KeyError: + msg = "not a PPM file" + raise SyntaxError(msg) + self._mode = mode + + if magic_number in (b"P1", b"P4"): + self.custom_mimetype = "image/x-portable-bitmap" + elif magic_number in (b"P2", b"P5"): + self.custom_mimetype = "image/x-portable-graymap" + elif magic_number in (b"P3", b"P6"): + self.custom_mimetype = "image/x-portable-pixmap" + + self._size = int(self._read_token()), int(self._read_token()) + + decoder_name = "raw" + if magic_number in (b"P1", b"P2", b"P3"): + decoder_name = "ppm_plain" + + args: str | tuple[str | int, ...] + if mode == "1": + args = "1;I" + elif mode == "F": + scale = float(self._read_token()) + if scale == 0.0 or not math.isfinite(scale): + msg = "scale must be finite and non-zero" + raise ValueError(msg) + self.info["scale"] = abs(scale) + + rawmode = "F;32F" if scale < 0 else "F;32BF" + args = (rawmode, 0, -1) + else: + maxval = int(self._read_token()) + if not 0 < maxval < 65536: + msg = "maxval must be greater than 0 and less than 65536" + raise ValueError(msg) + if maxval > 255 and mode == "L": + self._mode = "I" + + rawmode = mode + if decoder_name != "ppm_plain": + # If maxval matches a bit depth, use the raw decoder directly + if maxval == 65535 and mode == "L": + rawmode = "I;16B" + elif maxval != 255: + decoder_name = "ppm" + + args = rawmode if decoder_name == "raw" else (rawmode, maxval) + self.tile = [ + ImageFile._Tile(decoder_name, (0, 0) + self.size, self.fp.tell(), args) + ] + + +# +# -------------------------------------------------------------------- + + +class PpmPlainDecoder(ImageFile.PyDecoder): + _pulls_fd = True + _comment_spans: bool + + def _read_block(self) -> bytes: + assert self.fd is not None + + return self.fd.read(ImageFile.SAFEBLOCK) + + def _find_comment_end(self, block: bytes, start: int = 0) -> int: + a = block.find(b"\n", start) + b = block.find(b"\r", start) + return min(a, b) if a * b > 0 else max(a, b) # lowest nonnegative index (or -1) + + def _ignore_comments(self, block: bytes) -> bytes: + if self._comment_spans: + # Finish current comment + while block: + comment_end = self._find_comment_end(block) + if comment_end != -1: + # Comment ends in this block + # Delete tail of comment + block = block[comment_end + 1 :] + break + else: + # Comment spans whole block + # So read the next block, looking for the end + block = self._read_block() + + # Search for any further comments + self._comment_spans = False + while True: + comment_start = block.find(b"#") + if comment_start == -1: + # No comment found + break + comment_end = self._find_comment_end(block, comment_start) + if comment_end != -1: + # Comment ends in this block + # Delete comment + block = block[:comment_start] + block[comment_end + 1 :] + else: + # Comment continues to next block(s) + block = block[:comment_start] + self._comment_spans = True + break + return block + + def _decode_bitonal(self) -> bytearray: + """ + This is a separate method because in the plain PBM format, all data tokens are + exactly one byte, so the inter-token whitespace is optional. + """ + data = bytearray() + total_bytes = self.state.xsize * self.state.ysize + + while len(data) != total_bytes: + block = self._read_block() # read next block + if not block: + # eof + break + + block = self._ignore_comments(block) + + tokens = b"".join(block.split()) + for token in tokens: + if token not in (48, 49): + msg = b"Invalid token for this mode: %s" % bytes([token]) + raise ValueError(msg) + data = (data + tokens)[:total_bytes] + invert = bytes.maketrans(b"01", b"\xff\x00") + return data.translate(invert) + + def _decode_blocks(self, maxval: int) -> bytearray: + data = bytearray() + max_len = 10 + out_byte_count = 4 if self.mode == "I" else 1 + out_max = 65535 if self.mode == "I" else 255 + bands = Image.getmodebands(self.mode) + total_bytes = self.state.xsize * self.state.ysize * bands * out_byte_count + + half_token = b"" + while len(data) != total_bytes: + block = self._read_block() # read next block + if not block: + if half_token: + block = b" " # flush half_token + else: + # eof + break + + block = self._ignore_comments(block) + + if half_token: + block = half_token + block # stitch half_token to new block + half_token = b"" + + tokens = block.split() + + if block and not block[-1:].isspace(): # block might split token + half_token = tokens.pop() # save half token for later + if len(half_token) > max_len: # prevent buildup of half_token + msg = ( + b"Token too long found in data: %s" % half_token[: max_len + 1] + ) + raise ValueError(msg) + + for token in tokens: + if len(token) > max_len: + msg = b"Token too long found in data: %s" % token[: max_len + 1] + raise ValueError(msg) + value = int(token) + if value < 0: + msg_str = f"Channel value is negative: {value}" + raise ValueError(msg_str) + if value > maxval: + msg_str = f"Channel value too large for this mode: {value}" + raise ValueError(msg_str) + value = round(value / maxval * out_max) + data += o32(value) if self.mode == "I" else o8(value) + if len(data) == total_bytes: # finished! + break + return data + + def decode(self, buffer: Image.DecoderInput) -> tuple[int, int]: + self._comment_spans = False + if self.mode == "1": + data = self._decode_bitonal() + rawmode = "1;8" + else: + maxval = self.args[-1] + data = self._decode_blocks(maxval) + rawmode = "I;32" if self.mode == "I" else self.mode + self.set_as_raw(bytes(data), rawmode) + return -1, 0 + + +class PpmDecoder(ImageFile.PyDecoder): + _pulls_fd = True + + def decode(self, buffer: Image.DecoderInput) -> tuple[int, int]: + assert self.fd is not None + + data = bytearray() + maxval = self.args[-1] + in_byte_count = 1 if maxval < 256 else 2 + out_byte_count = 4 if self.mode == "I" else 1 + out_max = 65535 if self.mode == "I" else 255 + bands = Image.getmodebands(self.mode) + dest_length = self.state.xsize * self.state.ysize * bands * out_byte_count + while len(data) < dest_length: + pixels = self.fd.read(in_byte_count * bands) + if len(pixels) < in_byte_count * bands: + # eof + break + for b in range(bands): + value = ( + pixels[b] if in_byte_count == 1 else i16(pixels, b * in_byte_count) + ) + value = min(out_max, round(value / maxval * out_max)) + data += o32(value) if self.mode == "I" else o8(value) + rawmode = "I;32" if self.mode == "I" else self.mode + self.set_as_raw(bytes(data), rawmode) + return -1, 0 + + +# +# -------------------------------------------------------------------- + + +def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + if im.mode == "1": + rawmode, head = "1;I", b"P4" + elif im.mode == "L": + rawmode, head = "L", b"P5" + elif im.mode in ("I", "I;16"): + rawmode, head = "I;16B", b"P5" + elif im.mode in ("RGB", "RGBA"): + rawmode, head = "RGB", b"P6" + elif im.mode == "F": + rawmode, head = "F;32F", b"Pf" + else: + msg = f"cannot write mode {im.mode} as PPM" + raise OSError(msg) + fp.write(head + b"\n%d %d\n" % im.size) + if head == b"P6": + fp.write(b"255\n") + elif head == b"P5": + if rawmode == "L": + fp.write(b"255\n") + else: + fp.write(b"65535\n") + elif head == b"Pf": + fp.write(b"-1.0\n") + row_order = -1 if im.mode == "F" else 1 + ImageFile._save( + im, fp, [ImageFile._Tile("raw", (0, 0) + im.size, 0, (rawmode, 0, row_order))] + ) + + +# +# -------------------------------------------------------------------- + + +Image.register_open(PpmImageFile.format, PpmImageFile, _accept) +Image.register_save(PpmImageFile.format, _save) + +Image.register_decoder("ppm", PpmDecoder) +Image.register_decoder("ppm_plain", PpmPlainDecoder) + +Image.register_extensions(PpmImageFile.format, [".pbm", ".pgm", ".ppm", ".pnm", ".pfm"]) + +Image.register_mime(PpmImageFile.format, "image/x-portable-anymap") diff --git a/.venv/lib/python3.11/site-packages/PIL/PsdImagePlugin.py b/.venv/lib/python3.11/site-packages/PIL/PsdImagePlugin.py new file mode 100644 index 0000000000000000000000000000000000000000..201909abde63cd459dfd73f361e4fcda33ec2917 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/PsdImagePlugin.py @@ -0,0 +1,339 @@ +# +# The Python Imaging Library +# $Id$ +# +# Adobe PSD 2.5/3.0 file handling +# +# History: +# 1995-09-01 fl Created +# 1997-01-03 fl Read most PSD images +# 1997-01-18 fl Fixed P and CMYK support +# 2001-10-21 fl Added seek/tell support (for layers) +# +# Copyright (c) 1997-2001 by Secret Labs AB. +# Copyright (c) 1995-2001 by Fredrik Lundh +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import io +from functools import cached_property +from typing import IO + +from . import Image, ImageFile, ImagePalette +from ._binary import i8 +from ._binary import i16be as i16 +from ._binary import i32be as i32 +from ._binary import si16be as si16 +from ._binary import si32be as si32 +from ._util import DeferredError + +MODES = { + # (photoshop mode, bits) -> (pil mode, required channels) + (0, 1): ("1", 1), + (0, 8): ("L", 1), + (1, 8): ("L", 1), + (2, 8): ("P", 1), + (3, 8): ("RGB", 3), + (4, 8): ("CMYK", 4), + (7, 8): ("L", 1), # FIXME: multilayer + (8, 8): ("L", 1), # duotone + (9, 8): ("LAB", 3), +} + + +# --------------------------------------------------------------------. +# read PSD images + + +def _accept(prefix: bytes) -> bool: + return prefix.startswith(b"8BPS") + + +## +# Image plugin for Photoshop images. + + +class PsdImageFile(ImageFile.ImageFile): + format = "PSD" + format_description = "Adobe Photoshop" + _close_exclusive_fp_after_loading = False + + def _open(self) -> None: + assert self.fp is not None + read = self.fp.read + + # + # header + + s = read(26) + if not _accept(s) or i16(s, 4) != 1: + msg = "not a PSD file" + raise SyntaxError(msg) + + psd_bits = i16(s, 22) + psd_channels = i16(s, 12) + psd_mode = i16(s, 24) + + mode, channels = MODES[(psd_mode, psd_bits)] + + if channels > psd_channels: + msg = "not enough channels" + raise OSError(msg) + if mode == "RGB" and psd_channels == 4: + mode = "RGBA" + channels = 4 + + self._mode = mode + self._size = i32(s, 18), i32(s, 14) + + # + # color mode data + + size = i32(read(4)) + if size: + data = read(size) + if mode == "P" and size == 768: + self.palette = ImagePalette.raw("RGB;L", data) + + # + # image resources + + self.resources = [] + + size = i32(read(4)) + if size: + # load resources + end = self.fp.tell() + size + while self.fp.tell() < end: + read(4) # signature + id = i16(read(2)) + name = read(i8(read(1))) + if not (len(name) & 1): + read(1) # padding + data = read(i32(read(4))) + if len(data) & 1: + read(1) # padding + self.resources.append((id, name, data)) + if id == 1039: # ICC profile + self.info["icc_profile"] = data + + # + # layer and mask information + + self._layers_position = None + + size = i32(read(4)) + if size: + end = self.fp.tell() + size + size = i32(read(4)) + if size: + self._layers_position = self.fp.tell() + self._layers_size = size + self.fp.seek(end) + self._n_frames: int | None = None + + # + # image descriptor + + self.tile = _maketile(self.fp, mode, (0, 0) + self.size, channels) + + # keep the file open + self._fp = self.fp + self.frame = 1 + self._min_frame = 1 + + @cached_property + def layers( + self, + ) -> list[tuple[str, str, tuple[int, int, int, int], list[ImageFile._Tile]]]: + layers = [] + if self._layers_position is not None: + if isinstance(self._fp, DeferredError): + raise self._fp.ex + self._fp.seek(self._layers_position) + _layer_data = io.BytesIO(ImageFile._safe_read(self._fp, self._layers_size)) + layers = _layerinfo(_layer_data, self._layers_size) + self._n_frames = len(layers) + return layers + + @property + def n_frames(self) -> int: + if self._n_frames is None: + self._n_frames = len(self.layers) + return self._n_frames + + @property + def is_animated(self) -> bool: + return len(self.layers) > 1 + + def seek(self, layer: int) -> None: + if not self._seek_check(layer): + return + if isinstance(self._fp, DeferredError): + raise self._fp.ex + + # seek to given layer (1..max) + if layer > len(self.layers): + msg = "no more images in PSD file" + raise EOFError(msg) + _, mode, _, tile = self.layers[layer - 1] + self._mode = mode + self.tile = tile + self.frame = layer + self.fp = self._fp + + def tell(self) -> int: + # return layer number (0=image, 1..max=layers) + return self.frame + + +def _layerinfo( + fp: IO[bytes], ct_bytes: int +) -> list[tuple[str, str, tuple[int, int, int, int], list[ImageFile._Tile]]]: + # read layerinfo block + layers = [] + + def read(size: int) -> bytes: + return ImageFile._safe_read(fp, size) + + ct = si16(read(2)) + + # sanity check + if ct_bytes < (abs(ct) * 20): + msg = "Layer block too short for number of layers requested" + raise SyntaxError(msg) + + for _ in range(abs(ct)): + # bounding box + y0 = si32(read(4)) + x0 = si32(read(4)) + y1 = si32(read(4)) + x1 = si32(read(4)) + + # image info + bands = [] + ct_types = i16(read(2)) + if ct_types > 4: + fp.seek(ct_types * 6 + 12, io.SEEK_CUR) + size = i32(read(4)) + fp.seek(size, io.SEEK_CUR) + continue + + for _ in range(ct_types): + channel_id = i16(read(2)) + + if channel_id == 65535: + b = "A" + elif channel_id < 4: + b = "RGBA"[channel_id] + else: + b = "" + + bands.append(b) + read(4) # size + + # figure out the image mode + bands.sort() + if bands == ["R"]: + mode = "L" + elif bands == ["B", "G", "R"]: + mode = "RGB" + elif bands == ["A", "B", "G", "R"]: + mode = "RGBA" + else: + mode = "" # unknown + + # skip over blend flags and extra information + read(12) # filler + name = "" + size = i32(read(4)) # length of the extra data field + if size: + data_end = fp.tell() + size + + length = i32(read(4)) + if length: + fp.seek(length - 16, io.SEEK_CUR) + + length = i32(read(4)) + if length: + fp.seek(length, io.SEEK_CUR) + + length = i8(read(1)) + if length: + # Don't know the proper encoding, + # Latin-1 should be a good guess + name = read(length).decode("latin-1", "replace") + + fp.seek(data_end) + layers.append((name, mode, (x0, y0, x1, y1))) + + # get tiles + layerinfo = [] + for i, (name, mode, bbox) in enumerate(layers): + tile = [] + for m in mode: + t = _maketile(fp, m, bbox, 1) + if t: + tile.extend(t) + layerinfo.append((name, mode, bbox, tile)) + + return layerinfo + + +def _maketile( + file: IO[bytes], mode: str, bbox: tuple[int, int, int, int], channels: int +) -> list[ImageFile._Tile]: + tiles = [] + read = file.read + + compression = i16(read(2)) + + xsize = bbox[2] - bbox[0] + ysize = bbox[3] - bbox[1] + + offset = file.tell() + + if compression == 0: + # + # raw compression + for channel in range(channels): + layer = mode[channel] + if mode == "CMYK": + layer += ";I" + tiles.append(ImageFile._Tile("raw", bbox, offset, layer)) + offset = offset + xsize * ysize + + elif compression == 1: + # + # packbits compression + i = 0 + bytecount = read(channels * ysize * 2) + offset = file.tell() + for channel in range(channels): + layer = mode[channel] + if mode == "CMYK": + layer += ";I" + tiles.append(ImageFile._Tile("packbits", bbox, offset, layer)) + for y in range(ysize): + offset = offset + i16(bytecount, i) + i += 2 + + file.seek(offset) + + if offset & 1: + read(1) # padding + + return tiles + + +# -------------------------------------------------------------------- +# registry + + +Image.register_open(PsdImageFile.format, PsdImageFile, _accept) + +Image.register_extension(PsdImageFile.format, ".psd") + +Image.register_mime(PsdImageFile.format, "image/vnd.adobe.photoshop") diff --git a/.venv/lib/python3.11/site-packages/PIL/QoiImagePlugin.py b/.venv/lib/python3.11/site-packages/PIL/QoiImagePlugin.py new file mode 100644 index 0000000000000000000000000000000000000000..e7a6cee16db07cc9b3c95306a3faa14d36c79fa3 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/QoiImagePlugin.py @@ -0,0 +1,235 @@ +# +# The Python Imaging Library. +# +# QOI support for PIL +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import os +from typing import IO + +from . import Image, ImageFile +from ._binary import i32be as i32 +from ._binary import o8 +from ._binary import o32be as o32 + + +def _accept(prefix: bytes) -> bool: + return prefix.startswith(b"qoif") + + +class QoiImageFile(ImageFile.ImageFile): + format = "QOI" + format_description = "Quite OK Image" + + def _open(self) -> None: + assert self.fp is not None + if not _accept(self.fp.read(4)): + msg = "not a QOI file" + raise SyntaxError(msg) + + self._size = i32(self.fp.read(4)), i32(self.fp.read(4)) + + channels = self.fp.read(1)[0] + self._mode = "RGB" if channels == 3 else "RGBA" + + self.fp.seek(1, os.SEEK_CUR) # colorspace + self.tile = [ImageFile._Tile("qoi", (0, 0) + self._size, self.fp.tell())] + + +class QoiDecoder(ImageFile.PyDecoder): + _pulls_fd = True + _previous_pixel: bytes | bytearray | None = None + _previously_seen_pixels: dict[int, bytes | bytearray] = {} + + def _add_to_previous_pixels(self, value: bytes | bytearray) -> None: + self._previous_pixel = value + + r, g, b, a = value + hash_value = (r * 3 + g * 5 + b * 7 + a * 11) % 64 + self._previously_seen_pixels[hash_value] = value + + def decode(self, buffer: Image.DecoderInput) -> tuple[int, int]: + assert self.fd is not None + + self._previously_seen_pixels = {} + self._previous_pixel = bytearray((0, 0, 0, 255)) + + data = bytearray() + bands = Image.getmodebands(self.mode) + dest_length = self.state.xsize * self.state.ysize * bands + while len(data) < dest_length: + byte = self.fd.read(1)[0] + value: bytes | bytearray + if byte == 0b11111110 and self._previous_pixel: # QOI_OP_RGB + value = bytearray(self.fd.read(3)) + self._previous_pixel[3:] + elif byte == 0b11111111: # QOI_OP_RGBA + value = self.fd.read(4) + else: + op = byte >> 6 + if op == 0: # QOI_OP_INDEX + op_index = byte & 0b00111111 + value = self._previously_seen_pixels.get( + op_index, bytearray((0, 0, 0, 0)) + ) + elif op == 1 and self._previous_pixel: # QOI_OP_DIFF + value = bytearray( + ( + (self._previous_pixel[0] + ((byte & 0b00110000) >> 4) - 2) + % 256, + (self._previous_pixel[1] + ((byte & 0b00001100) >> 2) - 2) + % 256, + (self._previous_pixel[2] + (byte & 0b00000011) - 2) % 256, + self._previous_pixel[3], + ) + ) + elif op == 2 and self._previous_pixel: # QOI_OP_LUMA + second_byte = self.fd.read(1)[0] + diff_green = (byte & 0b00111111) - 32 + diff_red = ((second_byte & 0b11110000) >> 4) - 8 + diff_blue = (second_byte & 0b00001111) - 8 + + value = bytearray( + tuple( + (self._previous_pixel[i] + diff_green + diff) % 256 + for i, diff in enumerate((diff_red, 0, diff_blue)) + ) + ) + value += self._previous_pixel[3:] + elif op == 3 and self._previous_pixel: # QOI_OP_RUN + run_length = (byte & 0b00111111) + 1 + value = self._previous_pixel + if bands == 3: + value = value[:3] + data += value * run_length + continue + self._add_to_previous_pixels(value) + + if bands == 3: + value = value[:3] + data += value + self.set_as_raw(data) + return -1, 0 + + +def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + if im.mode == "RGB": + channels = 3 + elif im.mode == "RGBA": + channels = 4 + else: + msg = "Unsupported QOI image mode" + raise ValueError(msg) + + colorspace = 0 if im.encoderinfo.get("colorspace") == "sRGB" else 1 + + fp.write(b"qoif") + fp.write(o32(im.size[0])) + fp.write(o32(im.size[1])) + fp.write(o8(channels)) + fp.write(o8(colorspace)) + + ImageFile._save(im, fp, [ImageFile._Tile("qoi", (0, 0) + im.size)]) + + +class QoiEncoder(ImageFile.PyEncoder): + _pushes_fd = True + _previous_pixel: tuple[int, int, int, int] | None = None + _previously_seen_pixels: dict[int, tuple[int, int, int, int]] = {} + _run = 0 + + def _write_run(self) -> bytes: + data = o8(0b11000000 | (self._run - 1)) # QOI_OP_RUN + self._run = 0 + return data + + def _delta(self, left: int, right: int) -> int: + result = (left - right) & 255 + if result >= 128: + result -= 256 + return result + + def encode(self, bufsize: int) -> tuple[int, int, bytes]: + assert self.im is not None + + self._previously_seen_pixels = {0: (0, 0, 0, 0)} + self._previous_pixel = (0, 0, 0, 255) + + data = bytearray() + w, h = self.im.size + bands = Image.getmodebands(self.mode) + + for y in range(h): + for x in range(w): + pixel = self.im.getpixel((x, y)) + if bands == 3: + pixel = (*pixel, 255) + + if pixel == self._previous_pixel: + self._run += 1 + if self._run == 62: + data += self._write_run() + else: + if self._run: + data += self._write_run() + + r, g, b, a = pixel + hash_value = (r * 3 + g * 5 + b * 7 + a * 11) % 64 + if self._previously_seen_pixels.get(hash_value) == pixel: + data += o8(hash_value) # QOI_OP_INDEX + elif self._previous_pixel: + self._previously_seen_pixels[hash_value] = pixel + + prev_r, prev_g, prev_b, prev_a = self._previous_pixel + if prev_a == a: + delta_r = self._delta(r, prev_r) + delta_g = self._delta(g, prev_g) + delta_b = self._delta(b, prev_b) + + if ( + -2 <= delta_r < 2 + and -2 <= delta_g < 2 + and -2 <= delta_b < 2 + ): + data += o8( + 0b01000000 + | (delta_r + 2) << 4 + | (delta_g + 2) << 2 + | (delta_b + 2) + ) # QOI_OP_DIFF + else: + delta_gr = self._delta(delta_r, delta_g) + delta_gb = self._delta(delta_b, delta_g) + if ( + -8 <= delta_gr < 8 + and -32 <= delta_g < 32 + and -8 <= delta_gb < 8 + ): + data += o8( + 0b10000000 | (delta_g + 32) + ) # QOI_OP_LUMA + data += o8((delta_gr + 8) << 4 | (delta_gb + 8)) + else: + data += o8(0b11111110) # QOI_OP_RGB + data += bytes(pixel[:3]) + else: + data += o8(0b11111111) # QOI_OP_RGBA + data += bytes(pixel) + + self._previous_pixel = pixel + + if self._run: + data += self._write_run() + data += bytes((0, 0, 0, 0, 0, 0, 0, 1)) # padding + + return len(data), 0, bytes(data) + + +Image.register_open(QoiImageFile.format, QoiImageFile, _accept) +Image.register_decoder("qoi", QoiDecoder) +Image.register_extension(QoiImageFile.format, ".qoi") + +Image.register_save(QoiImageFile.format, _save) +Image.register_encoder("qoi", QoiEncoder) diff --git a/.venv/lib/python3.11/site-packages/PIL/SgiImagePlugin.py b/.venv/lib/python3.11/site-packages/PIL/SgiImagePlugin.py new file mode 100644 index 0000000000000000000000000000000000000000..76688ba57245705015d04250eab44bae74c7d35c --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/SgiImagePlugin.py @@ -0,0 +1,231 @@ +# +# The Python Imaging Library. +# $Id$ +# +# SGI image file handling +# +# See "The SGI Image File Format (Draft version 0.97)", Paul Haeberli. +# +# +# +# History: +# 2017-22-07 mb Add RLE decompression +# 2016-16-10 mb Add save method without compression +# 1995-09-10 fl Created +# +# Copyright (c) 2016 by Mickael Bonfill. +# Copyright (c) 2008 by Karsten Hiddemann. +# Copyright (c) 1997 by Secret Labs AB. +# Copyright (c) 1995 by Fredrik Lundh. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import os +import struct +from typing import IO + +from . import Image, ImageFile +from ._binary import i16be as i16 +from ._binary import o8 + + +def _accept(prefix: bytes) -> bool: + return len(prefix) >= 2 and i16(prefix) == 474 + + +MODES = { + (1, 1, 1): "L", + (1, 2, 1): "L", + (2, 1, 1): "L;16B", + (2, 2, 1): "L;16B", + (1, 3, 3): "RGB", + (2, 3, 3): "RGB;16B", + (1, 3, 4): "RGBA", + (2, 3, 4): "RGBA;16B", +} + + +## +# Image plugin for SGI images. +class SgiImageFile(ImageFile.ImageFile): + format = "SGI" + format_description = "SGI Image File Format" + + def _open(self) -> None: + # HEAD + assert self.fp is not None + + headlen = 512 + s = self.fp.read(headlen) + + if not _accept(s): + msg = "Not an SGI image file" + raise ValueError(msg) + + # compression : verbatim or RLE + compression = s[2] + + # bpc : 1 or 2 bytes (8bits or 16bits) + bpc = s[3] + + # dimension : 1, 2 or 3 (depending on xsize, ysize and zsize) + dimension = i16(s, 4) + + # xsize : width + xsize = i16(s, 6) + + # ysize : height + ysize = i16(s, 8) + + # zsize : channels count + zsize = i16(s, 10) + + # determine mode from bits/zsize + try: + rawmode = MODES[(bpc, dimension, zsize)] + except KeyError: + msg = "Unsupported SGI image mode" + raise ValueError(msg) + + self._size = xsize, ysize + self._mode = rawmode.split(";")[0] + if self.mode == "RGB": + self.custom_mimetype = "image/rgb" + + # orientation -1 : scanlines begins at the bottom-left corner + orientation = -1 + + # decoder info + if compression == 0: + pagesize = xsize * ysize * bpc + if bpc == 2: + self.tile = [ + ImageFile._Tile( + "SGI16", + (0, 0) + self.size, + headlen, + (self.mode, 0, orientation), + ) + ] + else: + self.tile = [] + offset = headlen + for layer in self.mode: + self.tile.append( + ImageFile._Tile( + "raw", (0, 0) + self.size, offset, (layer, 0, orientation) + ) + ) + offset += pagesize + elif compression == 1: + self.tile = [ + ImageFile._Tile( + "sgi_rle", (0, 0) + self.size, headlen, (rawmode, orientation, bpc) + ) + ] + + +def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + if im.mode not in {"RGB", "RGBA", "L"}: + msg = "Unsupported SGI image mode" + raise ValueError(msg) + + # Get the keyword arguments + info = im.encoderinfo + + # Byte-per-pixel precision, 1 = 8bits per pixel + bpc = info.get("bpc", 1) + + if bpc not in (1, 2): + msg = "Unsupported number of bytes per pixel" + raise ValueError(msg) + + # Flip the image, since the origin of SGI file is the bottom-left corner + orientation = -1 + # Define the file as SGI File Format + magic_number = 474 + # Run-Length Encoding Compression - Unsupported at this time + rle = 0 + + # X Dimension = width / Y Dimension = height + x, y = im.size + # Z Dimension: Number of channels + z = len(im.mode) + # Number of dimensions (x,y,z) + if im.mode == "L": + dimension = 1 if y == 1 else 2 + else: + dimension = 3 + + # Minimum Byte value + pinmin = 0 + # Maximum Byte value (255 = 8bits per pixel) + pinmax = 255 + # Image name (79 characters max, truncated below in write) + img_name = os.path.splitext(os.path.basename(filename))[0] + if isinstance(img_name, str): + img_name = img_name.encode("ascii", "ignore") + # Standard representation of pixel in the file + colormap = 0 + fp.write(struct.pack(">h", magic_number)) + fp.write(o8(rle)) + fp.write(o8(bpc)) + fp.write(struct.pack(">H", dimension)) + fp.write(struct.pack(">H", x)) + fp.write(struct.pack(">H", y)) + fp.write(struct.pack(">H", z)) + fp.write(struct.pack(">l", pinmin)) + fp.write(struct.pack(">l", pinmax)) + fp.write(struct.pack("4s", b"")) # dummy + fp.write(struct.pack("79s", img_name)) # truncates to 79 chars + fp.write(struct.pack("s", b"")) # force null byte after img_name + fp.write(struct.pack(">l", colormap)) + fp.write(struct.pack("404s", b"")) # dummy + + rawmode = "L" + if bpc == 2: + rawmode = "L;16B" + + for channel in im.split(): + fp.write(channel.tobytes("raw", rawmode, 0, orientation)) + + if hasattr(fp, "flush"): + fp.flush() + + +class SGI16Decoder(ImageFile.PyDecoder): + _pulls_fd = True + + def decode(self, buffer: Image.DecoderInput) -> tuple[int, int]: + assert self.fd is not None + assert self.im is not None + + rawmode, stride, orientation = self.args + pagesize = self.state.xsize * self.state.ysize + zsize = len(self.mode) + self.fd.seek(512) + + for band in range(zsize): + channel = Image.new("L", (self.state.xsize, self.state.ysize)) + channel.frombytes( + self.fd.read(2 * pagesize), "raw", "L;16B", stride, orientation + ) + self.im.putband(channel.im, band) + + return -1, 0 + + +# +# registry + + +Image.register_decoder("SGI16", SGI16Decoder) +Image.register_open(SgiImageFile.format, SgiImageFile, _accept) +Image.register_save(SgiImageFile.format, _save) +Image.register_mime(SgiImageFile.format, "image/sgi") + +Image.register_extensions(SgiImageFile.format, [".bw", ".rgb", ".rgba", ".sgi"]) + +# End of file diff --git a/.venv/lib/python3.11/site-packages/PIL/SpiderImagePlugin.py b/.venv/lib/python3.11/site-packages/PIL/SpiderImagePlugin.py new file mode 100644 index 0000000000000000000000000000000000000000..b8bf2282d74ad01dc25459dcf4187952c056182b --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/SpiderImagePlugin.py @@ -0,0 +1,332 @@ +# +# The Python Imaging Library. +# +# SPIDER image file handling +# +# History: +# 2004-08-02 Created BB +# 2006-03-02 added save method +# 2006-03-13 added support for stack images +# +# Copyright (c) 2004 by Health Research Inc. (HRI) RENSSELAER, NY 12144. +# Copyright (c) 2004 by William Baxter. +# Copyright (c) 2004 by Secret Labs AB. +# Copyright (c) 2004 by Fredrik Lundh. +# + +## +# Image plugin for the Spider image format. This format is used +# by the SPIDER software, in processing image data from electron +# microscopy and tomography. +## + +# +# SpiderImagePlugin.py +# +# The Spider image format is used by SPIDER software, in processing +# image data from electron microscopy and tomography. +# +# Spider home page: +# https://spider.wadsworth.org/spider_doc/spider/docs/spider.html +# +# Details about the Spider image format: +# https://spider.wadsworth.org/spider_doc/spider/docs/image_doc.html +# +from __future__ import annotations + +import os +import struct +import sys +from typing import IO, Any + +from . import Image, ImageFile +from ._util import DeferredError + +TYPE_CHECKING = False + + +def isInt(f: Any) -> int: + try: + i = int(f) + if f - i == 0: + return 1 + else: + return 0 + except (ValueError, OverflowError): + return 0 + + +iforms = [1, 3, -11, -12, -21, -22] + + +# There is no magic number to identify Spider files, so just check a +# series of header locations to see if they have reasonable values. +# Returns no. of bytes in the header, if it is a valid Spider header, +# otherwise returns 0 + + +def isSpiderHeader(t: tuple[float, ...]) -> int: + h = (99,) + t # add 1 value so can use spider header index start=1 + # header values 1,2,5,12,13,22,23 should be integers + for i in [1, 2, 5, 12, 13, 22, 23]: + if not isInt(h[i]): + return 0 + # check iform + iform = int(h[5]) + if iform not in iforms: + return 0 + # check other header values + labrec = int(h[13]) # no. records in file header + labbyt = int(h[22]) # total no. of bytes in header + lenbyt = int(h[23]) # record length in bytes + if labbyt != (labrec * lenbyt): + return 0 + # looks like a valid header + return labbyt + + +def isSpiderImage(filename: str) -> int: + with open(filename, "rb") as fp: + f = fp.read(92) # read 23 * 4 bytes + t = struct.unpack(">23f", f) # try big-endian first + hdrlen = isSpiderHeader(t) + if hdrlen == 0: + t = struct.unpack("<23f", f) # little-endian + hdrlen = isSpiderHeader(t) + return hdrlen + + +class SpiderImageFile(ImageFile.ImageFile): + format = "SPIDER" + format_description = "Spider 2D image" + _close_exclusive_fp_after_loading = False + + def _open(self) -> None: + # check header + n = 27 * 4 # read 27 float values + assert self.fp is not None + f = self.fp.read(n) + + try: + self.bigendian = 1 + t = struct.unpack(">27f", f) # try big-endian first + hdrlen = isSpiderHeader(t) + if hdrlen == 0: + self.bigendian = 0 + t = struct.unpack("<27f", f) # little-endian + hdrlen = isSpiderHeader(t) + if hdrlen == 0: + msg = "not a valid Spider file" + raise SyntaxError(msg) + except struct.error as e: + msg = "not a valid Spider file" + raise SyntaxError(msg) from e + + h = (99,) + t # add 1 value : spider header index starts at 1 + iform = int(h[5]) + if iform != 1: + msg = "not a Spider 2D image" + raise SyntaxError(msg) + + self._size = int(h[12]), int(h[2]) # size in pixels (width, height) + self.istack = int(h[24]) + self.imgnumber = int(h[27]) + + if self.istack == 0 and self.imgnumber == 0: + # stk=0, img=0: a regular 2D image + offset = hdrlen + self._nimages = 1 + elif self.istack > 0 and self.imgnumber == 0: + # stk>0, img=0: Opening the stack for the first time + self.imgbytes = int(h[12]) * int(h[2]) * 4 + self.hdrlen = hdrlen + self._nimages = int(h[26]) + # Point to the first image in the stack + offset = hdrlen * 2 + self.imgnumber = 1 + elif self.istack == 0 and self.imgnumber > 0: + # stk=0, img>0: an image within the stack + offset = hdrlen + self.stkoffset + self.istack = 2 # So Image knows it's still a stack + else: + msg = "inconsistent stack header values" + raise SyntaxError(msg) + + if self.bigendian: + self.rawmode = "F;32BF" + else: + self.rawmode = "F;32F" + self._mode = "F" + + self.tile = [ImageFile._Tile("raw", (0, 0) + self.size, offset, self.rawmode)] + self._fp = self.fp # FIXME: hack + + @property + def n_frames(self) -> int: + return self._nimages + + @property + def is_animated(self) -> bool: + return self._nimages > 1 + + # 1st image index is zero (although SPIDER imgnumber starts at 1) + def tell(self) -> int: + if self.imgnumber < 1: + return 0 + else: + return self.imgnumber - 1 + + def seek(self, frame: int) -> None: + if self.istack == 0: + msg = "attempt to seek in a non-stack file" + raise EOFError(msg) + if not self._seek_check(frame): + return + if isinstance(self._fp, DeferredError): + raise self._fp.ex + self.stkoffset = self.hdrlen + frame * (self.hdrlen + self.imgbytes) + self.fp = self._fp + self.fp.seek(self.stkoffset) + self._open() + + # returns a byte image after rescaling to 0..255 + def convert2byte(self, depth: int = 255) -> Image.Image: + extrema = self.getextrema() + assert isinstance(extrema[0], float) + minimum, maximum = extrema + m: float = 1 + if maximum != minimum: + m = depth / (maximum - minimum) + b = -m * minimum + return self.point(lambda i: i * m + b).convert("L") + + if TYPE_CHECKING: + from . import ImageTk + + # returns a ImageTk.PhotoImage object, after rescaling to 0..255 + def tkPhotoImage(self) -> ImageTk.PhotoImage: + from . import ImageTk + + return ImageTk.PhotoImage(self.convert2byte(), palette=256) + + +# -------------------------------------------------------------------- +# Image series + + +# given a list of filenames, return a list of images +def loadImageSeries(filelist: list[str] | None = None) -> list[Image.Image] | None: + """create a list of :py:class:`~PIL.Image.Image` objects for use in a montage""" + if filelist is None or len(filelist) < 1: + return None + + byte_imgs = [] + for img in filelist: + if not os.path.exists(img): + print(f"unable to find {img}") + continue + try: + with Image.open(img) as im: + assert isinstance(im, SpiderImageFile) + byte_im = im.convert2byte() + except Exception: + if not isSpiderImage(img): + print(f"{img} is not a Spider image file") + continue + byte_im.info["filename"] = img + byte_imgs.append(byte_im) + return byte_imgs + + +# -------------------------------------------------------------------- +# For saving images in Spider format + + +def makeSpiderHeader(im: Image.Image) -> list[bytes]: + nsam, nrow = im.size + lenbyt = max(1, nsam) * 4 # There are labrec records in the header + labrec = int(1024 / lenbyt) + if 1024 % lenbyt != 0: + labrec += 1 + labbyt = labrec * lenbyt + nvalues = int(labbyt / 4) + if nvalues < 23: + return [] + + hdr = [0.0] * nvalues + + # NB these are Fortran indices + hdr[1] = 1.0 # nslice (=1 for an image) + hdr[2] = float(nrow) # number of rows per slice + hdr[3] = float(nrow) # number of records in the image + hdr[5] = 1.0 # iform for 2D image + hdr[12] = float(nsam) # number of pixels per line + hdr[13] = float(labrec) # number of records in file header + hdr[22] = float(labbyt) # total number of bytes in header + hdr[23] = float(lenbyt) # record length in bytes + + # adjust for Fortran indexing + hdr = hdr[1:] + hdr.append(0.0) + # pack binary data into a string + return [struct.pack("f", v) for v in hdr] + + +def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + if im.mode != "F": + im = im.convert("F") + + hdr = makeSpiderHeader(im) + if len(hdr) < 256: + msg = "Error creating Spider header" + raise OSError(msg) + + # write the SPIDER header + fp.writelines(hdr) + + rawmode = "F;32NF" # 32-bit native floating point + ImageFile._save(im, fp, [ImageFile._Tile("raw", (0, 0) + im.size, 0, rawmode)]) + + +def _save_spider(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + # get the filename extension and register it with Image + if filename_ext := os.path.splitext(filename)[1]: + ext = filename_ext.decode() if isinstance(filename_ext, bytes) else filename_ext + Image.register_extension(SpiderImageFile.format, ext) + _save(im, fp, filename) + + +# -------------------------------------------------------------------- + + +Image.register_open(SpiderImageFile.format, SpiderImageFile) +Image.register_save(SpiderImageFile.format, _save_spider) + +if __name__ == "__main__": + if len(sys.argv) < 2: + print("Syntax: python3 SpiderImagePlugin.py [infile] [outfile]") + sys.exit() + + filename = sys.argv[1] + if not isSpiderImage(filename): + print("input image must be in Spider format") + sys.exit() + + with Image.open(filename) as im: + print(f"image: {im}") + print(f"format: {im.format}") + print(f"size: {im.size}") + print(f"mode: {im.mode}") + print("max, min: ", end=" ") + print(im.getextrema()) + + if len(sys.argv) > 2: + outfile = sys.argv[2] + + # perform some image operation + transposed_im = im.transpose(Image.Transpose.FLIP_LEFT_RIGHT) + print( + f"saving a flipped version of {os.path.basename(filename)} " + f"as {outfile} " + ) + transposed_im.save(outfile, SpiderImageFile.format) diff --git a/.venv/lib/python3.11/site-packages/PIL/SunImagePlugin.py b/.venv/lib/python3.11/site-packages/PIL/SunImagePlugin.py new file mode 100644 index 0000000000000000000000000000000000000000..8912379ea3e7801cdac9a557d2bc0c557bce8991 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/SunImagePlugin.py @@ -0,0 +1,145 @@ +# +# The Python Imaging Library. +# $Id$ +# +# Sun image file handling +# +# History: +# 1995-09-10 fl Created +# 1996-05-28 fl Fixed 32-bit alignment +# 1998-12-29 fl Import ImagePalette module +# 2001-12-18 fl Fixed palette loading (from Jean-Claude Rimbault) +# +# Copyright (c) 1997-2001 by Secret Labs AB +# Copyright (c) 1995-1996 by Fredrik Lundh +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +from . import Image, ImageFile, ImagePalette +from ._binary import i32be as i32 + + +def _accept(prefix: bytes) -> bool: + return len(prefix) >= 4 and i32(prefix) == 0x59A66A95 + + +## +# Image plugin for Sun raster files. + + +class SunImageFile(ImageFile.ImageFile): + format = "SUN" + format_description = "Sun Raster File" + + def _open(self) -> None: + # The Sun Raster file header is 32 bytes in length + # and has the following format: + + # typedef struct _SunRaster + # { + # DWORD MagicNumber; /* Magic (identification) number */ + # DWORD Width; /* Width of image in pixels */ + # DWORD Height; /* Height of image in pixels */ + # DWORD Depth; /* Number of bits per pixel */ + # DWORD Length; /* Size of image data in bytes */ + # DWORD Type; /* Type of raster file */ + # DWORD ColorMapType; /* Type of color map */ + # DWORD ColorMapLength; /* Size of the color map in bytes */ + # } SUNRASTER; + + assert self.fp is not None + + # HEAD + s = self.fp.read(32) + if not _accept(s): + msg = "not an SUN raster file" + raise SyntaxError(msg) + + offset = 32 + + self._size = i32(s, 4), i32(s, 8) + + depth = i32(s, 12) + # data_length = i32(s, 16) # unreliable, ignore. + file_type = i32(s, 20) + palette_type = i32(s, 24) # 0: None, 1: RGB, 2: Raw/arbitrary + palette_length = i32(s, 28) + + if depth == 1: + self._mode, rawmode = "1", "1;I" + elif depth == 4: + self._mode, rawmode = "L", "L;4" + elif depth == 8: + self._mode = rawmode = "L" + elif depth == 24: + if file_type == 3: + self._mode, rawmode = "RGB", "RGB" + else: + self._mode, rawmode = "RGB", "BGR" + elif depth == 32: + if file_type == 3: + self._mode, rawmode = "RGB", "RGBX" + else: + self._mode, rawmode = "RGB", "BGRX" + else: + msg = "Unsupported Mode/Bit Depth" + raise SyntaxError(msg) + + if palette_length: + if palette_length > 1024: + msg = "Unsupported Color Palette Length" + raise SyntaxError(msg) + + if palette_type != 1: + msg = "Unsupported Palette Type" + raise SyntaxError(msg) + + offset = offset + palette_length + self.palette = ImagePalette.raw("RGB;L", self.fp.read(palette_length)) + if self.mode == "L": + self._mode = "P" + rawmode = rawmode.replace("L", "P") + + # 16 bit boundaries on stride + stride = ((self.size[0] * depth + 15) // 16) * 2 + + # file type: Type is the version (or flavor) of the bitmap + # file. The following values are typically found in the Type + # field: + # 0000h Old + # 0001h Standard + # 0002h Byte-encoded + # 0003h RGB format + # 0004h TIFF format + # 0005h IFF format + # FFFFh Experimental + + # Old and standard are the same, except for the length tag. + # byte-encoded is run-length-encoded + # RGB looks similar to standard, but RGB byte order + # TIFF and IFF mean that they were converted from T/IFF + # Experimental means that it's something else. + # (https://www.fileformat.info/format/sunraster/egff.htm) + + if file_type in (0, 1, 3, 4, 5): + self.tile = [ + ImageFile._Tile("raw", (0, 0) + self.size, offset, (rawmode, stride)) + ] + elif file_type == 2: + self.tile = [ + ImageFile._Tile("sun_rle", (0, 0) + self.size, offset, rawmode) + ] + else: + msg = "Unsupported Sun Raster file type" + raise SyntaxError(msg) + + +# +# registry + + +Image.register_open(SunImageFile.format, SunImageFile, _accept) + +Image.register_extension(SunImageFile.format, ".ras") diff --git a/.venv/lib/python3.11/site-packages/PIL/TarIO.py b/.venv/lib/python3.11/site-packages/PIL/TarIO.py new file mode 100644 index 0000000000000000000000000000000000000000..86490a496f3f106fcc042c03fb235ed5fb41f3a7 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/TarIO.py @@ -0,0 +1,61 @@ +# +# The Python Imaging Library. +# $Id$ +# +# read files from within a tar file +# +# History: +# 95-06-18 fl Created +# 96-05-28 fl Open files in binary mode +# +# Copyright (c) Secret Labs AB 1997. +# Copyright (c) Fredrik Lundh 1995-96. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import io + +from . import ContainerIO + + +class TarIO(ContainerIO.ContainerIO[bytes]): + """A file object that provides read access to a given member of a TAR file.""" + + def __init__(self, tarfile: str, file: str) -> None: + """ + Create file object. + + :param tarfile: Name of TAR file. + :param file: Name of member file. + """ + self.fh = open(tarfile, "rb") + + while True: + s = self.fh.read(512) + if len(s) != 512: + self.fh.close() + + msg = "unexpected end of tar file" + raise OSError(msg) + + name = s[:100].decode("utf-8") + i = name.find("\0") + if i == 0: + self.fh.close() + + msg = "cannot find subfile" + raise OSError(msg) + if i > 0: + name = name[:i] + + size = int(s[124:135], 8) + + if file == name: + break + + self.fh.seek((size + 511) & (~511), io.SEEK_CUR) + + # Open region + super().__init__(self.fh, self.fh.tell(), size) diff --git a/.venv/lib/python3.11/site-packages/PIL/TgaImagePlugin.py b/.venv/lib/python3.11/site-packages/PIL/TgaImagePlugin.py new file mode 100644 index 0000000000000000000000000000000000000000..8fd63b1df5bb2d694b99b6bdd5bbbbbb95a855af --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/TgaImagePlugin.py @@ -0,0 +1,284 @@ +# +# The Python Imaging Library. +# $Id$ +# +# TGA file handling +# +# History: +# 95-09-01 fl created (reads 24-bit files only) +# 97-01-04 fl support more TGA versions, including compressed images +# 98-07-04 fl fixed orientation and alpha layer bugs +# 98-09-11 fl fixed orientation for runlength decoder +# +# Copyright (c) Secret Labs AB 1997-98. +# Copyright (c) Fredrik Lundh 1995-97. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import os +import warnings +from typing import IO + +from . import Image, ImageFile, ImagePalette +from ._binary import i16le as i16 +from ._binary import i32le as i32 +from ._binary import o8 +from ._binary import o16le as o16 + +# +# -------------------------------------------------------------------- +# Read RGA file + + +MODES = { + # map imagetype/depth to rawmode + (1, 8): "P", + (3, 1): "1", + (3, 8): "L", + (3, 16): "LA", + (2, 16): "BGRA;15Z", + (2, 24): "BGR", + (2, 32): "BGRA", +} + + +## +# Image plugin for Targa files. + + +class TgaImageFile(ImageFile.ImageFile): + format = "TGA" + format_description = "Targa" + + def _open(self) -> None: + # process header + assert self.fp is not None + + s = self.fp.read(18) + + id_len = s[0] + + colormaptype = s[1] + imagetype = s[2] + + depth = s[16] + + flags = s[17] + + self._size = i16(s, 12), i16(s, 14) + + # validate header fields + if ( + colormaptype not in (0, 1) + or self.size[0] <= 0 + or self.size[1] <= 0 + or depth not in (1, 8, 16, 24, 32) + ): + msg = "not a TGA file" + raise SyntaxError(msg) + + # image mode + if imagetype in (3, 11): + self._mode = "L" + if depth == 1: + self._mode = "1" # ??? + elif depth == 16: + self._mode = "LA" + elif imagetype in (1, 9): + self._mode = "P" if colormaptype else "L" + elif imagetype in (2, 10): + self._mode = "RGB" if depth == 24 else "RGBA" + else: + msg = "unknown TGA mode" + raise SyntaxError(msg) + + # orientation + orientation = flags & 0x30 + self._flip_horizontally = orientation in [0x10, 0x30] + if orientation in [0x20, 0x30]: + orientation = 1 + elif orientation in [0, 0x10]: + orientation = -1 + else: + msg = "unknown TGA orientation" + raise SyntaxError(msg) + + self.info["orientation"] = orientation + + if imagetype & 8: + self.info["compression"] = "tga_rle" + + if id_len: + self.info["id_section"] = self.fp.read(id_len) + + if colormaptype: + # read palette + start, size, mapdepth = i16(s, 3), i16(s, 5), s[7] + if mapdepth == 16: + self.palette = ImagePalette.raw( + "BGRA;15Z", bytes(2 * start) + self.fp.read(2 * size) + ) + self.palette.mode = "RGBA" + elif mapdepth == 24: + self.palette = ImagePalette.raw( + "BGR", bytes(3 * start) + self.fp.read(3 * size) + ) + elif mapdepth == 32: + self.palette = ImagePalette.raw( + "BGRA", bytes(4 * start) + self.fp.read(4 * size) + ) + else: + msg = "unknown TGA map depth" + raise SyntaxError(msg) + + # setup tile descriptor + try: + rawmode = MODES[(imagetype & 7, depth)] + if imagetype & 8: + # compressed + self.tile = [ + ImageFile._Tile( + "tga_rle", + (0, 0) + self.size, + self.fp.tell(), + (rawmode, orientation, depth), + ) + ] + else: + self.tile = [ + ImageFile._Tile( + "raw", + (0, 0) + self.size, + self.fp.tell(), + (rawmode, 0, orientation), + ) + ] + except KeyError: + pass # cannot decode + + def load_end(self) -> None: + if self.mode == "RGBA": + assert self.fp is not None + self.fp.seek(-26, os.SEEK_END) + footer = self.fp.read(26) + if footer.endswith(b"TRUEVISION-XFILE.\x00"): + # version 2 + extension_offset = i32(footer) + if extension_offset: + self.fp.seek(extension_offset + 494) + attributes_type = self.fp.read(1) + if attributes_type == b"\x00": + # No alpha + self.im.fillband(3, 255) + + if self._flip_horizontally: + self.im = self.im.transpose(Image.Transpose.FLIP_LEFT_RIGHT) + + +# +# -------------------------------------------------------------------- +# Write TGA file + + +SAVE = { + "1": ("1", 1, 0, 3), + "L": ("L", 8, 0, 3), + "LA": ("LA", 16, 0, 3), + "P": ("P", 8, 1, 1), + "RGB": ("BGR", 24, 0, 2), + "RGBA": ("BGRA", 32, 0, 2), +} + + +def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + try: + rawmode, bits, colormaptype, imagetype = SAVE[im.mode] + except KeyError as e: + msg = f"cannot write mode {im.mode} as TGA" + raise OSError(msg) from e + + if "rle" in im.encoderinfo: + rle = im.encoderinfo["rle"] + else: + compression = im.encoderinfo.get("compression", im.info.get("compression")) + rle = compression == "tga_rle" + if rle: + if im.mode == "1": + msg = f"cannot write mode {im.mode} as TGA with run-length encoding" + raise OSError(msg) + + imagetype += 8 + + id_section = im.encoderinfo.get("id_section", im.info.get("id_section", "")) + id_len = len(id_section) + if id_len > 255: + id_len = 255 + id_section = id_section[:255] + warnings.warn("id_section has been trimmed to 255 characters") + + if colormaptype: + palette = im.im.getpalette("RGB", "BGR") + colormaplength, colormapentry = len(palette) // 3, 24 + else: + colormaplength, colormapentry = 0, 0 + + if im.mode in ("LA", "RGBA"): + flags = 8 + else: + flags = 0 + + orientation = im.encoderinfo.get("orientation", im.info.get("orientation", -1)) + if orientation > 0: + flags = flags | 0x20 + + fp.write( + o8(id_len) + + o8(colormaptype) + + o8(imagetype) + + o16(0) # colormapfirst + + o16(colormaplength) + + o8(colormapentry) + + o16(0) + + o16(0) + + o16(im.size[0]) + + o16(im.size[1]) + + o8(bits) + + o8(flags) + ) + + if id_section: + fp.write(id_section) + + if colormaptype: + fp.write(palette) + + if rle: + ImageFile._save( + im, + fp, + [ImageFile._Tile("tga_rle", (0, 0) + im.size, 0, (rawmode, orientation))], + ) + else: + ImageFile._save( + im, + fp, + [ImageFile._Tile("raw", (0, 0) + im.size, 0, (rawmode, 0, orientation))], + ) + + # write targa version 2 footer + fp.write(b"\000" * 8 + b"TRUEVISION-XFILE." + b"\000") + + +# +# -------------------------------------------------------------------- +# Registry + + +Image.register_open(TgaImageFile.format, TgaImageFile) +Image.register_save(TgaImageFile.format, _save) + +Image.register_extensions(TgaImageFile.format, [".tga", ".icb", ".vda", ".vst"]) + +Image.register_mime(TgaImageFile.format, "image/x-tga") diff --git a/.venv/lib/python3.11/site-packages/PIL/TiffImagePlugin.py b/.venv/lib/python3.11/site-packages/PIL/TiffImagePlugin.py new file mode 100644 index 0000000000000000000000000000000000000000..472dfcf5802c769faea374123c6872ce13ff9bc6 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/TiffImagePlugin.py @@ -0,0 +1,2354 @@ +# +# The Python Imaging Library. +# $Id$ +# +# TIFF file handling +# +# TIFF is a flexible, if somewhat aged, image file format originally +# defined by Aldus. Although TIFF supports a wide variety of pixel +# layouts and compression methods, the name doesn't really stand for +# "thousands of incompatible file formats," it just feels that way. +# +# To read TIFF data from a stream, the stream must be seekable. For +# progressive decoding, make sure to use TIFF files where the tag +# directory is placed first in the file. +# +# History: +# 1995-09-01 fl Created +# 1996-05-04 fl Handle JPEGTABLES tag +# 1996-05-18 fl Fixed COLORMAP support +# 1997-01-05 fl Fixed PREDICTOR support +# 1997-08-27 fl Added support for rational tags (from Perry Stoll) +# 1998-01-10 fl Fixed seek/tell (from Jan Blom) +# 1998-07-15 fl Use private names for internal variables +# 1999-06-13 fl Rewritten for PIL 1.0 (1.0) +# 2000-10-11 fl Additional fixes for Python 2.0 (1.1) +# 2001-04-17 fl Fixed rewind support (seek to frame 0) (1.2) +# 2001-05-12 fl Added write support for more tags (from Greg Couch) (1.3) +# 2001-12-18 fl Added workaround for broken Matrox library +# 2002-01-18 fl Don't mess up if photometric tag is missing (D. Alan Stewart) +# 2003-05-19 fl Check FILLORDER tag +# 2003-09-26 fl Added RGBa support +# 2004-02-24 fl Added DPI support; fixed rational write support +# 2005-02-07 fl Added workaround for broken Corel Draw 10 files +# 2006-01-09 fl Added support for float/double tags (from Russell Nelson) +# +# Copyright (c) 1997-2006 by Secret Labs AB. All rights reserved. +# Copyright (c) 1995-1997 by Fredrik Lundh +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import io +import itertools +import logging +import math +import os +import struct +import warnings +from collections.abc import Callable, MutableMapping +from fractions import Fraction +from numbers import Number, Rational +from typing import IO, Any, cast + +from . import ExifTags, Image, ImageFile, ImageOps, ImagePalette, TiffTags +from ._binary import i16be as i16 +from ._binary import i32be as i32 +from ._binary import o8 +from ._util import DeferredError, is_path +from .TiffTags import TYPES + +TYPE_CHECKING = False +if TYPE_CHECKING: + from collections.abc import Iterator + from typing import NoReturn + + from ._typing import Buffer, IntegralLike, StrOrBytesPath + +logger = logging.getLogger(__name__) + +# Set these to true to force use of libtiff for reading or writing. +READ_LIBTIFF = False +WRITE_LIBTIFF = False +STRIP_SIZE = 65536 + +II = b"II" # little-endian (Intel style) +MM = b"MM" # big-endian (Motorola style) + +# +# -------------------------------------------------------------------- +# Read TIFF files + +# a few tag names, just to make the code below a bit more readable +OSUBFILETYPE = 255 +IMAGEWIDTH = 256 +IMAGELENGTH = 257 +BITSPERSAMPLE = 258 +COMPRESSION = 259 +PHOTOMETRIC_INTERPRETATION = 262 +FILLORDER = 266 +IMAGEDESCRIPTION = 270 +STRIPOFFSETS = 273 +SAMPLESPERPIXEL = 277 +ROWSPERSTRIP = 278 +STRIPBYTECOUNTS = 279 +X_RESOLUTION = 282 +Y_RESOLUTION = 283 +PLANAR_CONFIGURATION = 284 +RESOLUTION_UNIT = 296 +TRANSFERFUNCTION = 301 +SOFTWARE = 305 +DATE_TIME = 306 +ARTIST = 315 +PREDICTOR = 317 +COLORMAP = 320 +TILEWIDTH = 322 +TILELENGTH = 323 +TILEOFFSETS = 324 +TILEBYTECOUNTS = 325 +SUBIFD = 330 +EXTRASAMPLES = 338 +SAMPLEFORMAT = 339 +JPEGTABLES = 347 +YCBCRSUBSAMPLING = 530 +REFERENCEBLACKWHITE = 532 +COPYRIGHT = 33432 +IPTC_NAA_CHUNK = 33723 # newsphoto properties +PHOTOSHOP_CHUNK = 34377 # photoshop properties +ICCPROFILE = 34675 +EXIFIFD = 34665 +XMP = 700 +JPEGQUALITY = 65537 # pseudo-tag by libtiff + +# https://github.com/imagej/ImageJA/blob/master/src/main/java/ij/io/TiffDecoder.java +IMAGEJ_META_DATA_BYTE_COUNTS = 50838 +IMAGEJ_META_DATA = 50839 + +COMPRESSION_INFO = { + # Compression => pil compression name + 1: "raw", + 2: "tiff_ccitt", + 3: "group3", + 4: "group4", + 5: "tiff_lzw", + 6: "tiff_jpeg", # obsolete + 7: "jpeg", + 8: "tiff_adobe_deflate", + 32771: "tiff_raw_16", # 16-bit padding + 32773: "packbits", + 32809: "tiff_thunderscan", + 32946: "tiff_deflate", + 34676: "tiff_sgilog", + 34677: "tiff_sgilog24", + 34925: "lzma", + 50000: "zstd", + 50001: "webp", +} + +COMPRESSION_INFO_REV = {v: k for k, v in COMPRESSION_INFO.items()} + +OPEN_INFO = { + # (ByteOrder, PhotoInterpretation, SampleFormat, FillOrder, BitsPerSample, + # ExtraSamples) => mode, rawmode + (II, 0, (1,), 1, (1,), ()): ("1", "1;I"), + (MM, 0, (1,), 1, (1,), ()): ("1", "1;I"), + (II, 0, (1,), 2, (1,), ()): ("1", "1;IR"), + (MM, 0, (1,), 2, (1,), ()): ("1", "1;IR"), + (II, 1, (1,), 1, (1,), ()): ("1", "1"), + (MM, 1, (1,), 1, (1,), ()): ("1", "1"), + (II, 1, (1,), 2, (1,), ()): ("1", "1;R"), + (MM, 1, (1,), 2, (1,), ()): ("1", "1;R"), + (II, 0, (1,), 1, (2,), ()): ("L", "L;2I"), + (MM, 0, (1,), 1, (2,), ()): ("L", "L;2I"), + (II, 0, (1,), 2, (2,), ()): ("L", "L;2IR"), + (MM, 0, (1,), 2, (2,), ()): ("L", "L;2IR"), + (II, 1, (1,), 1, (2,), ()): ("L", "L;2"), + (MM, 1, (1,), 1, (2,), ()): ("L", "L;2"), + (II, 1, (1,), 2, (2,), ()): ("L", "L;2R"), + (MM, 1, (1,), 2, (2,), ()): ("L", "L;2R"), + (II, 0, (1,), 1, (4,), ()): ("L", "L;4I"), + (MM, 0, (1,), 1, (4,), ()): ("L", "L;4I"), + (II, 0, (1,), 2, (4,), ()): ("L", "L;4IR"), + (MM, 0, (1,), 2, (4,), ()): ("L", "L;4IR"), + (II, 1, (1,), 1, (4,), ()): ("L", "L;4"), + (MM, 1, (1,), 1, (4,), ()): ("L", "L;4"), + (II, 1, (1,), 2, (4,), ()): ("L", "L;4R"), + (MM, 1, (1,), 2, (4,), ()): ("L", "L;4R"), + (II, 0, (1,), 1, (8,), ()): ("L", "L;I"), + (MM, 0, (1,), 1, (8,), ()): ("L", "L;I"), + (II, 0, (1,), 2, (8,), ()): ("L", "L;IR"), + (MM, 0, (1,), 2, (8,), ()): ("L", "L;IR"), + (II, 1, (1,), 1, (8,), ()): ("L", "L"), + (MM, 1, (1,), 1, (8,), ()): ("L", "L"), + (II, 1, (2,), 1, (8,), ()): ("L", "L"), + (MM, 1, (2,), 1, (8,), ()): ("L", "L"), + (II, 1, (1,), 2, (8,), ()): ("L", "L;R"), + (MM, 1, (1,), 2, (8,), ()): ("L", "L;R"), + (II, 1, (1,), 1, (12,), ()): ("I;16", "I;12"), + (II, 0, (1,), 1, (16,), ()): ("I;16", "I;16"), + (II, 1, (1,), 1, (16,), ()): ("I;16", "I;16"), + (MM, 1, (1,), 1, (16,), ()): ("I;16B", "I;16B"), + (II, 1, (1,), 2, (16,), ()): ("I;16", "I;16R"), + (II, 1, (2,), 1, (16,), ()): ("I", "I;16S"), + (MM, 1, (2,), 1, (16,), ()): ("I", "I;16BS"), + (II, 0, (3,), 1, (32,), ()): ("F", "F;32F"), + (MM, 0, (3,), 1, (32,), ()): ("F", "F;32BF"), + (II, 1, (1,), 1, (32,), ()): ("I", "I;32N"), + (II, 1, (2,), 1, (32,), ()): ("I", "I;32S"), + (MM, 1, (2,), 1, (32,), ()): ("I", "I;32BS"), + (II, 1, (3,), 1, (32,), ()): ("F", "F;32F"), + (MM, 1, (3,), 1, (32,), ()): ("F", "F;32BF"), + (II, 1, (1,), 1, (8, 8), (2,)): ("LA", "LA"), + (MM, 1, (1,), 1, (8, 8), (2,)): ("LA", "LA"), + (II, 2, (1,), 1, (8, 8, 8), ()): ("RGB", "RGB"), + (MM, 2, (1,), 1, (8, 8, 8), ()): ("RGB", "RGB"), + (II, 2, (1,), 2, (8, 8, 8), ()): ("RGB", "RGB;R"), + (MM, 2, (1,), 2, (8, 8, 8), ()): ("RGB", "RGB;R"), + (II, 2, (1,), 1, (8, 8, 8, 8), ()): ("RGBA", "RGBA"), # missing ExtraSamples + (MM, 2, (1,), 1, (8, 8, 8, 8), ()): ("RGBA", "RGBA"), # missing ExtraSamples + (II, 2, (1,), 1, (8, 8, 8, 8), (0,)): ("RGB", "RGBX"), + (MM, 2, (1,), 1, (8, 8, 8, 8), (0,)): ("RGB", "RGBX"), + (II, 2, (1,), 1, (8, 8, 8, 8, 8), (0, 0)): ("RGB", "RGBXX"), + (MM, 2, (1,), 1, (8, 8, 8, 8, 8), (0, 0)): ("RGB", "RGBXX"), + (II, 2, (1,), 1, (8, 8, 8, 8, 8, 8), (0, 0, 0)): ("RGB", "RGBXXX"), + (MM, 2, (1,), 1, (8, 8, 8, 8, 8, 8), (0, 0, 0)): ("RGB", "RGBXXX"), + (II, 2, (1,), 1, (8, 8, 8, 8), (1,)): ("RGBA", "RGBa"), + (MM, 2, (1,), 1, (8, 8, 8, 8), (1,)): ("RGBA", "RGBa"), + (II, 2, (1,), 1, (8, 8, 8, 8, 8), (1, 0)): ("RGBA", "RGBaX"), + (MM, 2, (1,), 1, (8, 8, 8, 8, 8), (1, 0)): ("RGBA", "RGBaX"), + (II, 2, (1,), 1, (8, 8, 8, 8, 8, 8), (1, 0, 0)): ("RGBA", "RGBaXX"), + (MM, 2, (1,), 1, (8, 8, 8, 8, 8, 8), (1, 0, 0)): ("RGBA", "RGBaXX"), + (II, 2, (1,), 1, (8, 8, 8, 8), (2,)): ("RGBA", "RGBA"), + (MM, 2, (1,), 1, (8, 8, 8, 8), (2,)): ("RGBA", "RGBA"), + (II, 2, (1,), 1, (8, 8, 8, 8, 8), (2, 0)): ("RGBA", "RGBAX"), + (MM, 2, (1,), 1, (8, 8, 8, 8, 8), (2, 0)): ("RGBA", "RGBAX"), + (II, 2, (1,), 1, (8, 8, 8, 8, 8, 8), (2, 0, 0)): ("RGBA", "RGBAXX"), + (MM, 2, (1,), 1, (8, 8, 8, 8, 8, 8), (2, 0, 0)): ("RGBA", "RGBAXX"), + (II, 2, (1,), 1, (8, 8, 8, 8), (999,)): ("RGBA", "RGBA"), # Corel Draw 10 + (MM, 2, (1,), 1, (8, 8, 8, 8), (999,)): ("RGBA", "RGBA"), # Corel Draw 10 + (II, 2, (1,), 1, (16, 16, 16), ()): ("RGB", "RGB;16L"), + (MM, 2, (1,), 1, (16, 16, 16), ()): ("RGB", "RGB;16B"), + (II, 2, (1,), 1, (16, 16, 16, 16), ()): ("RGBA", "RGBA;16L"), + (MM, 2, (1,), 1, (16, 16, 16, 16), ()): ("RGBA", "RGBA;16B"), + (II, 2, (1,), 1, (16, 16, 16, 16), (0,)): ("RGB", "RGBX;16L"), + (MM, 2, (1,), 1, (16, 16, 16, 16), (0,)): ("RGB", "RGBX;16B"), + (II, 2, (1,), 1, (16, 16, 16, 16), (1,)): ("RGBA", "RGBa;16L"), + (MM, 2, (1,), 1, (16, 16, 16, 16), (1,)): ("RGBA", "RGBa;16B"), + (II, 2, (1,), 1, (16, 16, 16, 16), (2,)): ("RGBA", "RGBA;16L"), + (MM, 2, (1,), 1, (16, 16, 16, 16), (2,)): ("RGBA", "RGBA;16B"), + (II, 3, (1,), 1, (1,), ()): ("P", "P;1"), + (MM, 3, (1,), 1, (1,), ()): ("P", "P;1"), + (II, 3, (1,), 2, (1,), ()): ("P", "P;1R"), + (MM, 3, (1,), 2, (1,), ()): ("P", "P;1R"), + (II, 3, (1,), 1, (2,), ()): ("P", "P;2"), + (MM, 3, (1,), 1, (2,), ()): ("P", "P;2"), + (II, 3, (1,), 2, (2,), ()): ("P", "P;2R"), + (MM, 3, (1,), 2, (2,), ()): ("P", "P;2R"), + (II, 3, (1,), 1, (4,), ()): ("P", "P;4"), + (MM, 3, (1,), 1, (4,), ()): ("P", "P;4"), + (II, 3, (1,), 2, (4,), ()): ("P", "P;4R"), + (MM, 3, (1,), 2, (4,), ()): ("P", "P;4R"), + (II, 3, (1,), 1, (8,), ()): ("P", "P"), + (MM, 3, (1,), 1, (8,), ()): ("P", "P"), + (II, 3, (1,), 1, (8, 8), (0,)): ("P", "PX"), + (MM, 3, (1,), 1, (8, 8), (0,)): ("P", "PX"), + (II, 3, (1,), 1, (8, 8), (2,)): ("PA", "PA"), + (MM, 3, (1,), 1, (8, 8), (2,)): ("PA", "PA"), + (II, 3, (1,), 2, (8,), ()): ("P", "P;R"), + (MM, 3, (1,), 2, (8,), ()): ("P", "P;R"), + (II, 5, (1,), 1, (8, 8, 8, 8), ()): ("CMYK", "CMYK"), + (MM, 5, (1,), 1, (8, 8, 8, 8), ()): ("CMYK", "CMYK"), + (II, 5, (1,), 1, (8, 8, 8, 8, 8), (0,)): ("CMYK", "CMYKX"), + (MM, 5, (1,), 1, (8, 8, 8, 8, 8), (0,)): ("CMYK", "CMYKX"), + (II, 5, (1,), 1, (8, 8, 8, 8, 8, 8), (0, 0)): ("CMYK", "CMYKXX"), + (MM, 5, (1,), 1, (8, 8, 8, 8, 8, 8), (0, 0)): ("CMYK", "CMYKXX"), + (II, 5, (1,), 1, (16, 16, 16, 16), ()): ("CMYK", "CMYK;16L"), + (MM, 5, (1,), 1, (16, 16, 16, 16), ()): ("CMYK", "CMYK;16B"), + (II, 6, (1,), 1, (8,), ()): ("L", "L"), + (MM, 6, (1,), 1, (8,), ()): ("L", "L"), + # JPEG compressed images handled by LibTiff and auto-converted to RGBX + # Minimal Baseline TIFF requires YCbCr images to have 3 SamplesPerPixel + (II, 6, (1,), 1, (8, 8, 8), ()): ("RGB", "RGBX"), + (MM, 6, (1,), 1, (8, 8, 8), ()): ("RGB", "RGBX"), + (II, 8, (1,), 1, (8, 8, 8), ()): ("LAB", "LAB"), + (MM, 8, (1,), 1, (8, 8, 8), ()): ("LAB", "LAB"), +} + +MAX_SAMPLESPERPIXEL = max(len(key_tp[4]) for key_tp in OPEN_INFO) + +PREFIXES = [ + b"MM\x00\x2a", # Valid TIFF header with big-endian byte order + b"II\x2a\x00", # Valid TIFF header with little-endian byte order + b"MM\x2a\x00", # Invalid TIFF header, assume big-endian + b"II\x00\x2a", # Invalid TIFF header, assume little-endian + b"MM\x00\x2b", # BigTIFF with big-endian byte order + b"II\x2b\x00", # BigTIFF with little-endian byte order +] + + +def _accept(prefix: bytes) -> bool: + return prefix.startswith(tuple(PREFIXES)) + + +def _limit_rational( + val: float | Fraction | IFDRational, max_val: int +) -> tuple[IntegralLike, IntegralLike]: + inv = abs(val) > 1 + n_d = IFDRational(1 / val if inv else val).limit_rational(max_val) + return n_d[::-1] if inv else n_d + + +def _limit_signed_rational( + val: IFDRational, max_val: int, min_val: int +) -> tuple[IntegralLike, IntegralLike]: + frac = Fraction(val) + n_d: tuple[IntegralLike, IntegralLike] = frac.numerator, frac.denominator + + if min(float(i) for i in n_d) < min_val: + n_d = _limit_rational(val, abs(min_val)) + + n_d_float = tuple(float(i) for i in n_d) + if max(n_d_float) > max_val: + n_d = _limit_rational(n_d_float[0] / n_d_float[1], max_val) + + return n_d + + +## +# Wrapper for TIFF IFDs. + +_load_dispatch: dict[int, tuple[int, _LoaderFunc]] = {} +_write_dispatch: dict[int, Callable[..., Any]] = {} + + +def _delegate(op: str) -> Any: + def delegate( + self: IFDRational, *args: tuple[float, ...] + ) -> bool | float | Fraction: + return getattr(self._val, op)(*args) + + return delegate + + +class IFDRational(Rational): + """Implements a rational class where 0/0 is a legal value to match + the in the wild use of exif rationals. + + e.g., DigitalZoomRatio - 0.00/0.00 indicates that no digital zoom was used + """ + + """ If the denominator is 0, store this as a float('nan'), otherwise store + as a fractions.Fraction(). Delegate as appropriate + + """ + + __slots__ = ("_numerator", "_denominator", "_val") + + def __init__( + self, value: float | Fraction | IFDRational, denominator: int = 1 + ) -> None: + """ + :param value: either an integer numerator, a + float/rational/other number, or an IFDRational + :param denominator: Optional integer denominator + """ + self._val: Fraction | float + if isinstance(value, IFDRational): + self._numerator = value.numerator + self._denominator = value.denominator + self._val = value._val + return + + if isinstance(value, Fraction): + self._numerator = value.numerator + self._denominator = value.denominator + else: + if TYPE_CHECKING: + self._numerator = cast(IntegralLike, value) + else: + self._numerator = value + self._denominator = denominator + + if denominator == 0: + self._val = float("nan") + elif denominator == 1: + self._val = Fraction(value) + elif int(value) == value: + self._val = Fraction(int(value), denominator) + else: + self._val = Fraction(value / denominator) + + @property + def numerator(self) -> IntegralLike: + return self._numerator + + @property + def denominator(self) -> int: + return self._denominator + + def limit_rational(self, max_denominator: int) -> tuple[IntegralLike, int]: + """ + + :param max_denominator: Integer, the maximum denominator value + :returns: Tuple of (numerator, denominator) + """ + + if self.denominator == 0: + return self.numerator, self.denominator + + assert isinstance(self._val, Fraction) + f = self._val.limit_denominator(max_denominator) + return f.numerator, f.denominator + + def __repr__(self) -> str: + return str(float(self._val)) + + def __hash__(self) -> int: # type: ignore[override] + return self._val.__hash__() + + def __eq__(self, other: object) -> bool: + val = self._val + if isinstance(other, IFDRational): + other = other._val + if isinstance(other, float): + val = float(val) + return val == other + + def __getstate__(self) -> list[float | Fraction | IntegralLike]: + return [self._val, self._numerator, self._denominator] + + def __setstate__(self, state: list[float | Fraction | IntegralLike]) -> None: + IFDRational.__init__(self, 0) + _val, _numerator, _denominator = state + assert isinstance(_val, (float, Fraction)) + self._val = _val + if TYPE_CHECKING: + self._numerator = cast(IntegralLike, _numerator) + else: + self._numerator = _numerator + assert isinstance(_denominator, int) + self._denominator = _denominator + + """ a = ['add','radd', 'sub', 'rsub', 'mul', 'rmul', + 'truediv', 'rtruediv', 'floordiv', 'rfloordiv', + 'mod','rmod', 'pow','rpow', 'pos', 'neg', + 'abs', 'trunc', 'lt', 'gt', 'le', 'ge', 'bool', + 'ceil', 'floor', 'round'] + print("\n".join("__%s__ = _delegate('__%s__')" % (s,s) for s in a)) + """ + + __add__ = _delegate("__add__") + __radd__ = _delegate("__radd__") + __sub__ = _delegate("__sub__") + __rsub__ = _delegate("__rsub__") + __mul__ = _delegate("__mul__") + __rmul__ = _delegate("__rmul__") + __truediv__ = _delegate("__truediv__") + __rtruediv__ = _delegate("__rtruediv__") + __floordiv__ = _delegate("__floordiv__") + __rfloordiv__ = _delegate("__rfloordiv__") + __mod__ = _delegate("__mod__") + __rmod__ = _delegate("__rmod__") + __pow__ = _delegate("__pow__") + __rpow__ = _delegate("__rpow__") + __pos__ = _delegate("__pos__") + __neg__ = _delegate("__neg__") + __abs__ = _delegate("__abs__") + __trunc__ = _delegate("__trunc__") + __lt__ = _delegate("__lt__") + __gt__ = _delegate("__gt__") + __le__ = _delegate("__le__") + __ge__ = _delegate("__ge__") + __bool__ = _delegate("__bool__") + __ceil__ = _delegate("__ceil__") + __floor__ = _delegate("__floor__") + __round__ = _delegate("__round__") + __float__ = _delegate("__float__") + # Python >= 3.11 + if hasattr(Fraction, "__int__"): + __int__ = _delegate("__int__") + + +_LoaderFunc = Callable[["ImageFileDirectory_v2", bytes, bool], Any] + + +def _register_loader(idx: int, size: int) -> Callable[[_LoaderFunc], _LoaderFunc]: + def decorator(func: _LoaderFunc) -> _LoaderFunc: + from .TiffTags import TYPES + + if func.__name__.startswith("load_"): + TYPES[idx] = func.__name__[5:].replace("_", " ") + _load_dispatch[idx] = size, func # noqa: F821 + return func + + return decorator + + +def _register_writer(idx: int) -> Callable[[Callable[..., Any]], Callable[..., Any]]: + def decorator(func: Callable[..., Any]) -> Callable[..., Any]: + _write_dispatch[idx] = func # noqa: F821 + return func + + return decorator + + +def _register_basic(idx_fmt_name: tuple[int, str, str]) -> None: + from .TiffTags import TYPES + + idx, fmt, name = idx_fmt_name + TYPES[idx] = name + size = struct.calcsize(f"={fmt}") + + def basic_handler( + self: ImageFileDirectory_v2, data: bytes, legacy_api: bool = True + ) -> tuple[Any, ...]: + return self._unpack(f"{len(data) // size}{fmt}", data) + + _load_dispatch[idx] = size, basic_handler # noqa: F821 + _write_dispatch[idx] = lambda self, *values: ( # noqa: F821 + b"".join(self._pack(fmt, value) for value in values) + ) + + +if TYPE_CHECKING: + _IFDv2Base = MutableMapping[int, Any] +else: + _IFDv2Base = MutableMapping + + +class ImageFileDirectory_v2(_IFDv2Base): + """This class represents a TIFF tag directory. To speed things up, we + don't decode tags unless they're asked for. + + Exposes a dictionary interface of the tags in the directory:: + + ifd = ImageFileDirectory_v2() + ifd[key] = 'Some Data' + ifd.tagtype[key] = TiffTags.ASCII + print(ifd[key]) + 'Some Data' + + Individual values are returned as the strings or numbers, sequences are + returned as tuples of the values. + + The tiff metadata type of each item is stored in a dictionary of + tag types in + :attr:`~PIL.TiffImagePlugin.ImageFileDirectory_v2.tagtype`. The types + are read from a tiff file, guessed from the type added, or added + manually. + + Data Structures: + + * ``self.tagtype = {}`` + + * Key: numerical TIFF tag number + * Value: integer corresponding to the data type from + :py:data:`.TiffTags.TYPES` + + .. versionadded:: 3.0.0 + + 'Internal' data structures: + + * ``self._tags_v2 = {}`` + + * Key: numerical TIFF tag number + * Value: decoded data, as tuple for multiple values + + * ``self._tagdata = {}`` + + * Key: numerical TIFF tag number + * Value: undecoded byte string from file + + * ``self._tags_v1 = {}`` + + * Key: numerical TIFF tag number + * Value: decoded data in the v1 format + + Tags will be found in the private attributes ``self._tagdata``, and in + ``self._tags_v2`` once decoded. + + ``self.legacy_api`` is a value for internal use, and shouldn't be changed + from outside code. In cooperation with + :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1`, if ``legacy_api`` + is true, then decoded tags will be populated into both ``_tags_v1`` and + ``_tags_v2``. ``_tags_v2`` will be used if this IFD is used in the TIFF + save routine. Tags should be read from ``_tags_v1`` if + ``legacy_api == true``. + + """ + + _load_dispatch: dict[int, tuple[int, _LoaderFunc]] = {} + _write_dispatch: dict[int, Callable[..., Any]] = {} + + def __init__( + self, + ifh: bytes = b"II\x2a\x00\x00\x00\x00\x00", + prefix: bytes | None = None, + group: int | None = None, + ) -> None: + """Initialize an ImageFileDirectory. + + To construct an ImageFileDirectory from a real file, pass the 8-byte + magic header to the constructor. To only set the endianness, pass it + as the 'prefix' keyword argument. + + :param ifh: One of the accepted magic headers (cf. PREFIXES); also sets + endianness. + :param prefix: Override the endianness of the file. + """ + if not _accept(ifh): + msg = f"not a TIFF file (header {repr(ifh)} not valid)" + raise SyntaxError(msg) + self._prefix = prefix if prefix is not None else ifh[:2] + if self._prefix == MM: + self._endian = ">" + elif self._prefix == II: + self._endian = "<" + else: + msg = "not a TIFF IFD" + raise SyntaxError(msg) + self._bigtiff = ifh[2] == 43 + self.group = group + self.tagtype: dict[int, int] = {} + """ Dictionary of tag types """ + self.reset() + self.next = ( + self._unpack("Q", ifh[8:])[0] + if self._bigtiff + else self._unpack("L", ifh[4:])[0] + ) + self._legacy_api = False + + prefix = property(lambda self: self._prefix) + offset = property(lambda self: self._offset) + + @property + def legacy_api(self) -> bool: + return self._legacy_api + + @legacy_api.setter + def legacy_api(self, value: bool) -> NoReturn: + msg = "Not allowing setting of legacy api" + raise Exception(msg) + + def reset(self) -> None: + self._tags_v1: dict[int, Any] = {} # will remain empty if legacy_api is false + self._tags_v2: dict[int, Any] = {} # main tag storage + self._tagdata: dict[int, bytes] = {} + self.tagtype = {} # added 2008-06-05 by Florian Hoech + self._next = None + self._offset: int | None = None + + def __str__(self) -> str: + return str(dict(self)) + + def named(self) -> dict[str, Any]: + """ + :returns: dict of name|key: value + + Returns the complete tag dictionary, with named tags where possible. + """ + return { + TiffTags.lookup(code, self.group).name: value + for code, value in self.items() + } + + def __len__(self) -> int: + return len(set(self._tagdata) | set(self._tags_v2)) + + def __getitem__(self, tag: int) -> Any: + if tag not in self._tags_v2: # unpack on the fly + data = self._tagdata[tag] + typ = self.tagtype[tag] + size, handler = self._load_dispatch[typ] + self[tag] = handler(self, data, self.legacy_api) # check type + val = self._tags_v2[tag] + if self.legacy_api and not isinstance(val, (tuple, bytes)): + val = (val,) + return val + + def __contains__(self, tag: object) -> bool: + return tag in self._tags_v2 or tag in self._tagdata + + def __setitem__(self, tag: int, value: Any) -> None: + self._setitem(tag, value, self.legacy_api) + + def _setitem(self, tag: int, value: Any, legacy_api: bool) -> None: + basetypes = (Number, bytes, str) + + info = TiffTags.lookup(tag, self.group) + values = [value] if isinstance(value, basetypes) else value + + if tag not in self.tagtype: + if info.type: + self.tagtype[tag] = info.type + else: + self.tagtype[tag] = TiffTags.UNDEFINED + if all(isinstance(v, IFDRational) for v in values): + for v in values: + assert isinstance(v, IFDRational) + if v < 0: + self.tagtype[tag] = TiffTags.SIGNED_RATIONAL + break + else: + self.tagtype[tag] = TiffTags.RATIONAL + elif all(isinstance(v, int) for v in values): + short = True + signed_short = True + long = True + for v in values: + assert isinstance(v, int) + if short and not (0 <= v < 2**16): + short = False + if signed_short and not (-(2**15) < v < 2**15): + signed_short = False + if long and v < 0: + long = False + if short: + self.tagtype[tag] = TiffTags.SHORT + elif signed_short: + self.tagtype[tag] = TiffTags.SIGNED_SHORT + elif long: + self.tagtype[tag] = TiffTags.LONG + else: + self.tagtype[tag] = TiffTags.SIGNED_LONG + elif all(isinstance(v, float) for v in values): + self.tagtype[tag] = TiffTags.DOUBLE + elif all(isinstance(v, str) for v in values): + self.tagtype[tag] = TiffTags.ASCII + elif all(isinstance(v, bytes) for v in values): + self.tagtype[tag] = TiffTags.BYTE + + if self.tagtype[tag] == TiffTags.UNDEFINED: + values = [ + v.encode("ascii", "replace") if isinstance(v, str) else v + for v in values + ] + elif self.tagtype[tag] == TiffTags.RATIONAL: + values = [float(v) if isinstance(v, int) else v for v in values] + + is_ifd = self.tagtype[tag] == TiffTags.LONG and isinstance(values, dict) + if not is_ifd: + values = tuple( + info.cvt_enum(value) if isinstance(value, str) else value + for value in values + ) + + dest = self._tags_v1 if legacy_api else self._tags_v2 + + # Three branches: + # Spec'd length == 1, Actual length 1, store as element + # Spec'd length == 1, Actual > 1, Warn and truncate. Formerly barfed. + # No Spec, Actual length 1, Formerly (<4.2) returned a 1 element tuple. + # Don't mess with the legacy api, since it's frozen. + if not is_ifd and ( + (info.length == 1) + or self.tagtype[tag] == TiffTags.BYTE + or (info.length is None and len(values) == 1 and not legacy_api) + ): + # Don't mess with the legacy api, since it's frozen. + if legacy_api and self.tagtype[tag] in [ + TiffTags.RATIONAL, + TiffTags.SIGNED_RATIONAL, + ]: # rationals + values = (values,) + try: + (dest[tag],) = values + except ValueError: + # We've got a builtin tag with 1 expected entry + warnings.warn( + f"Metadata Warning, tag {tag} had too many entries: " + f"{len(values)}, expected 1" + ) + dest[tag] = values[0] + + else: + # Spec'd length > 1 or undefined + # Unspec'd, and length > 1 + dest[tag] = values + + def __delitem__(self, tag: int) -> None: + self._tags_v2.pop(tag, None) + self._tags_v1.pop(tag, None) + self._tagdata.pop(tag, None) + + def __iter__(self) -> Iterator[int]: + return iter(set(self._tagdata) | set(self._tags_v2)) + + def _unpack(self, fmt: str, data: bytes) -> tuple[Any, ...]: + return struct.unpack(self._endian + fmt, data) + + def _pack(self, fmt: str, *values: Any) -> bytes: + return struct.pack(self._endian + fmt, *values) + + list( + map( + _register_basic, + [ + (TiffTags.SHORT, "H", "short"), + (TiffTags.LONG, "L", "long"), + (TiffTags.SIGNED_BYTE, "b", "signed byte"), + (TiffTags.SIGNED_SHORT, "h", "signed short"), + (TiffTags.SIGNED_LONG, "l", "signed long"), + (TiffTags.FLOAT, "f", "float"), + (TiffTags.DOUBLE, "d", "double"), + (TiffTags.IFD, "L", "long"), + (TiffTags.LONG8, "Q", "long8"), + ], + ) + ) + + @_register_loader(1, 1) # Basic type, except for the legacy API. + def load_byte(self, data: bytes, legacy_api: bool = True) -> bytes: + return data + + @_register_writer(1) # Basic type, except for the legacy API. + def write_byte(self, data: bytes | int | IFDRational) -> bytes: + if isinstance(data, IFDRational): + data = int(data) + if isinstance(data, int): + data = bytes((data,)) + return data + + @_register_loader(2, 1) + def load_string(self, data: bytes, legacy_api: bool = True) -> str: + if data.endswith(b"\0"): + data = data[:-1] + return data.decode("latin-1", "replace") + + @_register_writer(2) + def write_string(self, value: str | bytes | int) -> bytes: + # remerge of https://github.com/python-pillow/Pillow/pull/1416 + if isinstance(value, int): + value = str(value) + if not isinstance(value, bytes): + value = value.encode("ascii", "replace") + return value + b"\0" + + @_register_loader(5, 8) + def load_rational( + self, data: bytes, legacy_api: bool = True + ) -> tuple[tuple[int, int] | IFDRational, ...]: + vals = self._unpack(f"{len(data) // 4}L", data) + + def combine(a: int, b: int) -> tuple[int, int] | IFDRational: + return (a, b) if legacy_api else IFDRational(a, b) + + return tuple(combine(num, denom) for num, denom in zip(vals[::2], vals[1::2])) + + @_register_writer(5) + def write_rational(self, *values: IFDRational) -> bytes: + return b"".join( + self._pack("2L", *_limit_rational(frac, 2**32 - 1)) for frac in values + ) + + @_register_loader(7, 1) + def load_undefined(self, data: bytes, legacy_api: bool = True) -> bytes: + return data + + @_register_writer(7) + def write_undefined(self, value: bytes | int | IFDRational) -> bytes: + if isinstance(value, IFDRational): + value = int(value) + if isinstance(value, int): + value = str(value).encode("ascii", "replace") + return value + + @_register_loader(10, 8) + def load_signed_rational( + self, data: bytes, legacy_api: bool = True + ) -> tuple[tuple[int, int] | IFDRational, ...]: + vals = self._unpack(f"{len(data) // 4}l", data) + + def combine(a: int, b: int) -> tuple[int, int] | IFDRational: + return (a, b) if legacy_api else IFDRational(a, b) + + return tuple(combine(num, denom) for num, denom in zip(vals[::2], vals[1::2])) + + @_register_writer(10) + def write_signed_rational(self, *values: IFDRational) -> bytes: + return b"".join( + self._pack("2l", *_limit_signed_rational(frac, 2**31 - 1, -(2**31))) + for frac in values + ) + + def _ensure_read(self, fp: IO[bytes], size: int) -> bytes: + ret = fp.read(size) + if len(ret) != size: + msg = ( + "Corrupt EXIF data. " + f"Expecting to read {size} bytes but only got {len(ret)}. " + ) + raise OSError(msg) + return ret + + def load(self, fp: IO[bytes]) -> None: + self.reset() + self._offset = fp.tell() + + try: + tag_count = ( + self._unpack("Q", self._ensure_read(fp, 8)) + if self._bigtiff + else self._unpack("H", self._ensure_read(fp, 2)) + )[0] + for i in range(tag_count): + tag, typ, count, data = ( + self._unpack("HHQ8s", self._ensure_read(fp, 20)) + if self._bigtiff + else self._unpack("HHL4s", self._ensure_read(fp, 12)) + ) + + tagname = TiffTags.lookup(tag, self.group).name + typname = TYPES.get(typ, "unknown") + msg = f"tag: {tagname} ({tag}) - type: {typname} ({typ})" + + try: + unit_size, handler = self._load_dispatch[typ] + except KeyError: + logger.debug("%s - unsupported type %s", msg, typ) + continue # ignore unsupported type + size = count * unit_size + if size > (8 if self._bigtiff else 4): + here = fp.tell() + (offset,) = self._unpack("Q" if self._bigtiff else "L", data) + msg += f" Tag Location: {here} - Data Location: {offset}" + fp.seek(offset) + data = ImageFile._safe_read(fp, size) + fp.seek(here) + else: + data = data[:size] + + if len(data) != size: + warnings.warn( + "Possibly corrupt EXIF data. " + f"Expecting to read {size} bytes but only got {len(data)}." + f" Skipping tag {tag}" + ) + logger.debug(msg) + continue + + if not data: + logger.debug(msg) + continue + + self._tagdata[tag] = data + self.tagtype[tag] = typ + + msg += " - value: " + msg += f"" if size > 32 else repr(data) + + logger.debug(msg) + + (self.next,) = ( + self._unpack("Q", self._ensure_read(fp, 8)) + if self._bigtiff + else self._unpack("L", self._ensure_read(fp, 4)) + ) + except OSError as msg: + warnings.warn(str(msg)) + return + + def _get_ifh(self) -> bytes: + ifh = self._prefix + self._pack("H", 43 if self._bigtiff else 42) + if self._bigtiff: + ifh += self._pack("HH", 8, 0) + ifh += self._pack("Q", 16) if self._bigtiff else self._pack("L", 8) + + return ifh + + def tobytes(self, offset: int = 0) -> bytes: + # FIXME What about tagdata? + result = self._pack("Q" if self._bigtiff else "H", len(self._tags_v2)) + + entries: list[tuple[int, int, int, bytes, bytes]] = [] + + fmt = "Q" if self._bigtiff else "L" + fmt_size = 8 if self._bigtiff else 4 + offset += ( + len(result) + len(self._tags_v2) * (20 if self._bigtiff else 12) + fmt_size + ) + stripoffsets = None + + # pass 1: convert tags to binary format + # always write tags in ascending order + for tag, value in sorted(self._tags_v2.items()): + if tag == STRIPOFFSETS: + stripoffsets = len(entries) + typ = self.tagtype[tag] + logger.debug("Tag %s, Type: %s, Value: %s", tag, typ, repr(value)) + is_ifd = typ == TiffTags.LONG and isinstance(value, dict) + if is_ifd: + ifd = ImageFileDirectory_v2(self._get_ifh(), group=tag) + values = self._tags_v2[tag] + for ifd_tag, ifd_value in values.items(): + ifd[ifd_tag] = ifd_value + data = ifd.tobytes(offset) + else: + values = value if isinstance(value, tuple) else (value,) + data = self._write_dispatch[typ](self, *values) + + tagname = TiffTags.lookup(tag, self.group).name + typname = "ifd" if is_ifd else TYPES.get(typ, "unknown") + msg = f"save: {tagname} ({tag}) - type: {typname} ({typ}) - value: " + msg += f"" if len(data) >= 16 else str(values) + logger.debug(msg) + + # count is sum of lengths for string and arbitrary data + if is_ifd: + count = 1 + elif typ in [TiffTags.BYTE, TiffTags.ASCII, TiffTags.UNDEFINED]: + count = len(data) + else: + count = len(values) + # figure out if data fits into the entry + if len(data) <= fmt_size: + entries.append((tag, typ, count, data.ljust(fmt_size, b"\0"), b"")) + else: + entries.append((tag, typ, count, self._pack(fmt, offset), data)) + offset += (len(data) + 1) // 2 * 2 # pad to word + + # update strip offset data to point beyond auxiliary data + if stripoffsets is not None: + tag, typ, count, value, data = entries[stripoffsets] + if data: + size, handler = self._load_dispatch[typ] + values = [val + offset for val in handler(self, data, self.legacy_api)] + data = self._write_dispatch[typ](self, *values) + else: + value = self._pack(fmt, self._unpack(fmt, value)[0] + offset) + entries[stripoffsets] = tag, typ, count, value, data + + # pass 2: write entries to file + for tag, typ, count, value, data in entries: + logger.debug("%s %s %s %s %s", tag, typ, count, repr(value), repr(data)) + result += self._pack( + "HHQ8s" if self._bigtiff else "HHL4s", tag, typ, count, value + ) + + # -- overwrite here for multi-page -- + result += self._pack(fmt, 0) # end of entries + + # pass 3: write auxiliary data to file + for tag, typ, count, value, data in entries: + result += data + if len(data) & 1: + result += b"\0" + + return result + + def save(self, fp: IO[bytes]) -> int: + if fp.tell() == 0: # skip TIFF header on subsequent pages + fp.write(self._get_ifh()) + + offset = fp.tell() + result = self.tobytes(offset) + fp.write(result) + return offset + len(result) + + +ImageFileDirectory_v2._load_dispatch = _load_dispatch +ImageFileDirectory_v2._write_dispatch = _write_dispatch +for idx, name in TYPES.items(): + name = name.replace(" ", "_") + setattr(ImageFileDirectory_v2, f"load_{name}", _load_dispatch[idx][1]) + setattr(ImageFileDirectory_v2, f"write_{name}", _write_dispatch[idx]) +del _load_dispatch, _write_dispatch, idx, name + + +# Legacy ImageFileDirectory support. +class ImageFileDirectory_v1(ImageFileDirectory_v2): + """This class represents the **legacy** interface to a TIFF tag directory. + + Exposes a dictionary interface of the tags in the directory:: + + ifd = ImageFileDirectory_v1() + ifd[key] = 'Some Data' + ifd.tagtype[key] = TiffTags.ASCII + print(ifd[key]) + ('Some Data',) + + Also contains a dictionary of tag types as read from the tiff image file, + :attr:`~PIL.TiffImagePlugin.ImageFileDirectory_v1.tagtype`. + + Values are returned as a tuple. + + .. deprecated:: 3.0.0 + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self._legacy_api = True + + tags = property(lambda self: self._tags_v1) + tagdata = property(lambda self: self._tagdata) + + # defined in ImageFileDirectory_v2 + tagtype: dict[int, int] + """Dictionary of tag types""" + + @classmethod + def from_v2(cls, original: ImageFileDirectory_v2) -> ImageFileDirectory_v1: + """Returns an + :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1` + instance with the same data as is contained in the original + :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2` + instance. + + :returns: :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1` + + """ + + ifd = cls(prefix=original.prefix) + ifd._tagdata = original._tagdata + ifd.tagtype = original.tagtype + ifd.next = original.next # an indicator for multipage tiffs + return ifd + + def to_v2(self) -> ImageFileDirectory_v2: + """Returns an + :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2` + instance with the same data as is contained in the original + :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1` + instance. + + :returns: :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2` + + """ + + ifd = ImageFileDirectory_v2(prefix=self.prefix) + ifd._tagdata = dict(self._tagdata) + ifd.tagtype = dict(self.tagtype) + ifd._tags_v2 = dict(self._tags_v2) + return ifd + + def __contains__(self, tag: object) -> bool: + return tag in self._tags_v1 or tag in self._tagdata + + def __len__(self) -> int: + return len(set(self._tagdata) | set(self._tags_v1)) + + def __iter__(self) -> Iterator[int]: + return iter(set(self._tagdata) | set(self._tags_v1)) + + def __setitem__(self, tag: int, value: Any) -> None: + for legacy_api in (False, True): + self._setitem(tag, value, legacy_api) + + def __getitem__(self, tag: int) -> Any: + if tag not in self._tags_v1: # unpack on the fly + data = self._tagdata[tag] + typ = self.tagtype[tag] + size, handler = self._load_dispatch[typ] + for legacy in (False, True): + self._setitem(tag, handler(self, data, legacy), legacy) + val = self._tags_v1[tag] + if not isinstance(val, (tuple, bytes)): + val = (val,) + return val + + +# undone -- switch this pointer +ImageFileDirectory = ImageFileDirectory_v1 + + +## +# Image plugin for TIFF files. + + +class TiffImageFile(ImageFile.ImageFile): + format = "TIFF" + format_description = "Adobe TIFF" + _close_exclusive_fp_after_loading = False + + def __init__( + self, + fp: StrOrBytesPath | IO[bytes], + filename: str | bytes | None = None, + ) -> None: + self.tag_v2: ImageFileDirectory_v2 + """ Image file directory (tag dictionary) """ + + self.tag: ImageFileDirectory_v1 + """ Legacy tag entries """ + + super().__init__(fp, filename) + + def _open(self) -> None: + """Open the first image in a TIFF file""" + + # Header + assert self.fp is not None + ifh = self.fp.read(8) + if ifh[2] == 43: + ifh += self.fp.read(8) + + self.tag_v2 = ImageFileDirectory_v2(ifh) + + # setup frame pointers + self.__first = self.__next = self.tag_v2.next + self.__frame = -1 + self._fp = self.fp + self._frame_pos: list[int] = [] + self._n_frames: int | None = None + + logger.debug("*** TiffImageFile._open ***") + logger.debug("- __first: %s", self.__first) + logger.debug("- ifh: %s", repr(ifh)) # Use repr to avoid str(bytes) + + # and load the first frame + self._seek(0) + + @property + def n_frames(self) -> int: + current_n_frames = self._n_frames + if current_n_frames is None: + current = self.tell() + self._seek(len(self._frame_pos)) + while self._n_frames is None: + self._seek(self.tell() + 1) + self.seek(current) + assert self._n_frames is not None + return self._n_frames + + def seek(self, frame: int) -> None: + """Select a given frame as current image""" + if not self._seek_check(frame): + return + self._seek(frame) + if self._im is not None and ( + self.im.size != self._tile_size + or self.im.mode != self.mode + or self.readonly + ): + self._im = None + + def _seek(self, frame: int) -> None: + if isinstance(self._fp, DeferredError): + raise self._fp.ex + self.fp = self._fp + + while len(self._frame_pos) <= frame: + if not self.__next: + msg = "no more images in TIFF file" + raise EOFError(msg) + logger.debug( + "Seeking to frame %s, on frame %s, __next %s, location: %s", + frame, + self.__frame, + self.__next, + self.fp.tell(), + ) + if self.__next >= 2**63: + msg = "Unable to seek to frame" + raise ValueError(msg) + self.fp.seek(self.__next) + self._frame_pos.append(self.__next) + logger.debug("Loading tags, location: %s", self.fp.tell()) + self.tag_v2.load(self.fp) + if self.tag_v2.next in self._frame_pos: + # This IFD has already been processed + # Declare this to be the end of the image + self.__next = 0 + else: + self.__next = self.tag_v2.next + if self.__next == 0: + self._n_frames = frame + 1 + if len(self._frame_pos) == 1: + self.is_animated = self.__next != 0 + self.__frame += 1 + self.fp.seek(self._frame_pos[frame]) + self.tag_v2.load(self.fp) + if XMP in self.tag_v2: + xmp = self.tag_v2[XMP] + if isinstance(xmp, tuple) and len(xmp) == 1: + xmp = xmp[0] + self.info["xmp"] = xmp + elif "xmp" in self.info: + del self.info["xmp"] + self._reload_exif() + # fill the legacy tag/ifd entries + self.tag = self.ifd = ImageFileDirectory_v1.from_v2(self.tag_v2) + self.__frame = frame + self._setup() + + def tell(self) -> int: + """Return the current frame number""" + return self.__frame + + def get_photoshop_blocks(self) -> dict[int, dict[str, bytes]]: + """ + Returns a dictionary of Photoshop "Image Resource Blocks". + The keys are the image resource ID. For more information, see + https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#50577409_pgfId-1037727 + + :returns: Photoshop "Image Resource Blocks" in a dictionary. + """ + blocks = {} + val = self.tag_v2.get(ExifTags.Base.ImageResources) + if val: + while val.startswith(b"8BIM") and len(val) >= 12: + id = i16(val[4:6]) + n = math.ceil((val[6] + 1) / 2) * 2 + try: + size = i32(val[6 + n : 10 + n]) + except struct.error: + break + data = val[10 + n : 10 + n + size] + blocks[id] = {"data": data} + + val = val[math.ceil((10 + n + size) / 2) * 2 :] + return blocks + + def load(self) -> Image.core.PixelAccess | None: + if self.tile and self.use_load_libtiff: + return self._load_libtiff() + return super().load() + + def load_prepare(self) -> None: + if self._im is None: + Image._decompression_bomb_check(self._tile_size) + self.im = Image.core.new(self.mode, self._tile_size) + ImageFile.ImageFile.load_prepare(self) + + def load_end(self) -> None: + # allow closing if we're on the first frame, there's no next + # This is the ImageFile.load path only, libtiff specific below. + if not self.is_animated: + self._close_exclusive_fp_after_loading = True + + # load IFD data from fp before it is closed + exif = self.getexif() + for key in TiffTags.TAGS_V2_GROUPS: + if key not in exif: + continue + exif.get_ifd(key) + + ImageOps.exif_transpose(self, in_place=True) + if ExifTags.Base.Orientation in self.tag_v2: + del self.tag_v2[ExifTags.Base.Orientation] + + def _load_libtiff(self) -> Image.core.PixelAccess | None: + """Overload method triggered when we detect a compressed tiff + Calls out to libtiff""" + + Image.Image.load(self) + + self.load_prepare() + + if not len(self.tile) == 1: + msg = "Not exactly one tile" + raise OSError(msg) + + # (self._compression, (extents tuple), + # 0, (rawmode, self._compression, fp)) + extents = self.tile[0][1] + args = self.tile[0][3] + + # To be nice on memory footprint, if there's a + # file descriptor, use that instead of reading + # into a string in python. + assert self.fp is not None + try: + fp = hasattr(self.fp, "fileno") and self.fp.fileno() + # flush the file descriptor, prevents error on pypy 2.4+ + # should also eliminate the need for fp.tell + # in _seek + if hasattr(self.fp, "flush"): + self.fp.flush() + except OSError: + # io.BytesIO have a fileno, but returns an OSError if + # it doesn't use a file descriptor. + fp = False + + if fp: + assert isinstance(args, tuple) + args_list = list(args) + args_list[2] = fp + args = tuple(args_list) + + decoder = Image._getdecoder(self.mode, "libtiff", args, self.decoderconfig) + try: + decoder.setimage(self.im, extents) + except ValueError as e: + msg = "Couldn't set the image" + raise OSError(msg) from e + + close_self_fp = self._exclusive_fp and not self.is_animated + if hasattr(self.fp, "getvalue"): + # We've got a stringio like thing passed in. Yay for all in memory. + # The decoder needs the entire file in one shot, so there's not + # a lot we can do here other than give it the entire file. + # unless we could do something like get the address of the + # underlying string for stringio. + # + # Rearranging for supporting byteio items, since they have a fileno + # that returns an OSError if there's no underlying fp. Easier to + # deal with here by reordering. + logger.debug("have getvalue. just sending in a string from getvalue") + n, err = decoder.decode(self.fp.getvalue()) + elif fp: + # we've got a actual file on disk, pass in the fp. + logger.debug("have fileno, calling fileno version of the decoder.") + if not close_self_fp: + self.fp.seek(0) + # Save and restore the file position, because libtiff will move it + # outside of the Python runtime, and that will confuse + # io.BufferedReader and possible others. + # NOTE: This must use os.lseek(), and not fp.tell()/fp.seek(), + # because the buffer read head already may not equal the actual + # file position, and fp.seek() may just adjust it's internal + # pointer and not actually seek the OS file handle. + pos = os.lseek(fp, 0, os.SEEK_CUR) + # 4 bytes, otherwise the trace might error out + n, err = decoder.decode(b"fpfp") + os.lseek(fp, pos, os.SEEK_SET) + else: + # we have something else. + logger.debug("don't have fileno or getvalue. just reading") + self.fp.seek(0) + # UNDONE -- so much for that buffer size thing. + n, err = decoder.decode(self.fp.read()) + + self.tile = [] + self.readonly = 0 + + self.load_end() + + if close_self_fp: + self.fp.close() + self.fp = None # might be shared + + if err < 0: + msg = f"decoder error {err}" + raise OSError(msg) + + return Image.Image.load(self) + + def _setup(self) -> None: + """Setup this image object based on current tags""" + + if 0xBC01 in self.tag_v2: + msg = "Windows Media Photo files not yet supported" + raise OSError(msg) + + # extract relevant tags + self._compression = COMPRESSION_INFO[self.tag_v2.get(COMPRESSION, 1)] + self._planar_configuration = self.tag_v2.get(PLANAR_CONFIGURATION, 1) + + # photometric is a required tag, but not everyone is reading + # the specification + photo = self.tag_v2.get(PHOTOMETRIC_INTERPRETATION, 0) + + # old style jpeg compression images most certainly are YCbCr + if self._compression == "tiff_jpeg": + photo = 6 + + fillorder = self.tag_v2.get(FILLORDER, 1) + + logger.debug("*** Summary ***") + logger.debug("- compression: %s", self._compression) + logger.debug("- photometric_interpretation: %s", photo) + logger.debug("- planar_configuration: %s", self._planar_configuration) + logger.debug("- fill_order: %s", fillorder) + logger.debug("- YCbCr subsampling: %s", self.tag_v2.get(YCBCRSUBSAMPLING)) + + # size + try: + xsize = self.tag_v2[IMAGEWIDTH] + ysize = self.tag_v2[IMAGELENGTH] + except KeyError as e: + msg = "Missing dimensions" + raise TypeError(msg) from e + if not isinstance(xsize, int) or not isinstance(ysize, int): + msg = "Invalid dimensions" + raise ValueError(msg) + self._tile_size = xsize, ysize + orientation = self.tag_v2.get(ExifTags.Base.Orientation) + if orientation in (5, 6, 7, 8): + self._size = ysize, xsize + else: + self._size = xsize, ysize + + logger.debug("- size: %s", self.size) + + sample_format = self.tag_v2.get(SAMPLEFORMAT, (1,)) + if len(sample_format) > 1 and max(sample_format) == min(sample_format): + # SAMPLEFORMAT is properly per band, so an RGB image will + # be (1,1,1). But, we don't support per band pixel types, + # and anything more than one band is a uint8. So, just + # take the first element. Revisit this if adding support + # for more exotic images. + sample_format = (sample_format[0],) + + bps_tuple = self.tag_v2.get(BITSPERSAMPLE, (1,)) + extra_tuple = self.tag_v2.get(EXTRASAMPLES, ()) + samples_per_pixel = self.tag_v2.get( + SAMPLESPERPIXEL, + 3 if self._compression == "tiff_jpeg" and photo in (2, 6) else 1, + ) + if photo in (2, 6, 8): # RGB, YCbCr, LAB + bps_count = 3 + elif photo == 5: # CMYK + bps_count = 4 + else: + bps_count = 1 + if self._planar_configuration == 2 and extra_tuple and max(extra_tuple) == 0: + # If components are stored separately, + # then unspecified extra components at the end can be ignored + bps_tuple = bps_tuple[: -len(extra_tuple)] + samples_per_pixel -= len(extra_tuple) + extra_tuple = () + bps_count += len(extra_tuple) + bps_actual_count = len(bps_tuple) + + if samples_per_pixel > MAX_SAMPLESPERPIXEL: + # DOS check, samples_per_pixel can be a Long, and we extend the tuple below + logger.error( + "More samples per pixel than can be decoded: %s", samples_per_pixel + ) + msg = "Invalid value for samples per pixel" + raise SyntaxError(msg) + + if samples_per_pixel < bps_actual_count: + # If a file has more values in bps_tuple than expected, + # remove the excess. + bps_tuple = bps_tuple[:samples_per_pixel] + elif samples_per_pixel > bps_actual_count and bps_actual_count == 1: + # If a file has only one value in bps_tuple, when it should have more, + # presume it is the same number of bits for all of the samples. + bps_tuple = bps_tuple * samples_per_pixel + + if len(bps_tuple) != samples_per_pixel: + msg = "unknown data organization" + raise SyntaxError(msg) + + # mode: check photometric interpretation and bits per pixel + key = ( + self.tag_v2.prefix, + photo, + sample_format, + fillorder, + bps_tuple, + extra_tuple, + ) + logger.debug("format key: %s", key) + try: + self._mode, rawmode = OPEN_INFO[key] + except KeyError as e: + logger.debug("- unsupported format") + msg = "unknown pixel mode" + raise SyntaxError(msg) from e + + logger.debug("- raw mode: %s", rawmode) + logger.debug("- pil mode: %s", self.mode) + + self.info["compression"] = self._compression + + xres = self.tag_v2.get(X_RESOLUTION, 1) + yres = self.tag_v2.get(Y_RESOLUTION, 1) + + if xres and yres: + resunit = self.tag_v2.get(RESOLUTION_UNIT) + if resunit == 2: # dots per inch + self.info["dpi"] = (xres, yres) + elif resunit == 3: # dots per centimeter. convert to dpi + self.info["dpi"] = (xres * 2.54, yres * 2.54) + elif resunit is None: # used to default to 1, but now 2) + self.info["dpi"] = (xres, yres) + # For backward compatibility, + # we also preserve the old behavior + self.info["resolution"] = xres, yres + else: # No absolute unit of measurement + self.info["resolution"] = xres, yres + + # build tile descriptors + x = y = layer = 0 + self.tile = [] + self.use_load_libtiff = READ_LIBTIFF or self._compression != "raw" + if self.use_load_libtiff: + # Decoder expects entire file as one tile. + # There's a buffer size limit in load (64k) + # so large g4 images will fail if we use that + # function. + # + # Setup the one tile for the whole image, then + # use the _load_libtiff function. + + # libtiff handles the fillmode for us, so 1;IR should + # actually be 1;I. Including the R double reverses the + # bits, so stripes of the image are reversed. See + # https://github.com/python-pillow/Pillow/issues/279 + if fillorder == 2: + # Replace fillorder with fillorder=1 + key = key[:3] + (1,) + key[4:] + logger.debug("format key: %s", key) + # this should always work, since all the + # fillorder==2 modes have a corresponding + # fillorder=1 mode + self._mode, rawmode = OPEN_INFO[key] + # YCbCr images with new jpeg compression with pixels in one plane + # unpacked straight into RGB values + if ( + photo == 6 + and self._compression == "jpeg" + and self._planar_configuration == 1 + ): + rawmode = "RGB" + # libtiff always returns the bytes in native order. + # we're expecting image byte order. So, if the rawmode + # contains I;16, we need to convert from native to image + # byte order. + elif rawmode == "I;16": + rawmode = "I;16N" + elif rawmode.endswith((";16B", ";16L")): + rawmode = rawmode[:-1] + "N" + + # Offset in the tile tuple is 0, we go from 0,0 to + # w,h, and we only do this once -- eds + a = (rawmode, self._compression, False, self.tag_v2.offset) + self.tile.append(ImageFile._Tile("libtiff", (0, 0, xsize, ysize), 0, a)) + + elif STRIPOFFSETS in self.tag_v2 or TILEOFFSETS in self.tag_v2: + # striped image + if STRIPOFFSETS in self.tag_v2: + offsets = self.tag_v2[STRIPOFFSETS] + h = self.tag_v2.get(ROWSPERSTRIP, ysize) + w = xsize + else: + # tiled image + offsets = self.tag_v2[TILEOFFSETS] + tilewidth = self.tag_v2.get(TILEWIDTH) + h = self.tag_v2.get(TILELENGTH) + if not isinstance(tilewidth, int) or not isinstance(h, int): + msg = "Invalid tile dimensions" + raise ValueError(msg) + w = tilewidth + + if w == xsize and h == ysize and self._planar_configuration != 2: + # Every tile covers the image. Only use the last offset + offsets = offsets[-1:] + + for offset in offsets: + if x + w > xsize: + stride = w * sum(bps_tuple) / 8 # bytes per line + else: + stride = 0 + + tile_rawmode = rawmode + if self._planar_configuration == 2: + # each band on it's own layer + tile_rawmode = rawmode[layer] + # adjust stride width accordingly + stride /= bps_count + + args = (tile_rawmode, int(stride), 1) + self.tile.append( + ImageFile._Tile( + self._compression, + (x, y, min(x + w, xsize), min(y + h, ysize)), + offset, + args, + ) + ) + x += w + if x >= xsize: + x, y = 0, y + h + if y >= ysize: + y = 0 + layer += 1 + else: + logger.debug("- unsupported data organization") + msg = "unknown data organization" + raise SyntaxError(msg) + + # Fix up info. + if ICCPROFILE in self.tag_v2: + self.info["icc_profile"] = self.tag_v2[ICCPROFILE] + + # fixup palette descriptor + + if self.mode in ["P", "PA"]: + palette = [o8(b // 256) for b in self.tag_v2[COLORMAP]] + self.palette = ImagePalette.raw("RGB;L", b"".join(palette)) + + +# +# -------------------------------------------------------------------- +# Write TIFF files + +# little endian is default except for image modes with +# explicit big endian byte-order + +SAVE_INFO = { + # mode => rawmode, byteorder, photometrics, + # sampleformat, bitspersample, extra + "1": ("1", II, 1, 1, (1,), None), + "L": ("L", II, 1, 1, (8,), None), + "LA": ("LA", II, 1, 1, (8, 8), 2), + "P": ("P", II, 3, 1, (8,), None), + "PA": ("PA", II, 3, 1, (8, 8), 2), + "I": ("I;32S", II, 1, 2, (32,), None), + "I;16": ("I;16", II, 1, 1, (16,), None), + "I;16L": ("I;16L", II, 1, 1, (16,), None), + "F": ("F;32F", II, 1, 3, (32,), None), + "RGB": ("RGB", II, 2, 1, (8, 8, 8), None), + "RGBX": ("RGBX", II, 2, 1, (8, 8, 8, 8), 0), + "RGBA": ("RGBA", II, 2, 1, (8, 8, 8, 8), 2), + "CMYK": ("CMYK", II, 5, 1, (8, 8, 8, 8), None), + "YCbCr": ("YCbCr", II, 6, 1, (8, 8, 8), None), + "LAB": ("LAB", II, 8, 1, (8, 8, 8), None), + "I;16B": ("I;16B", MM, 1, 1, (16,), None), +} + + +def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + try: + rawmode, prefix, photo, format, bits, extra = SAVE_INFO[im.mode] + except KeyError as e: + msg = f"cannot write mode {im.mode} as TIFF" + raise OSError(msg) from e + + encoderinfo = im.encoderinfo + encoderconfig = im.encoderconfig + + ifd = ImageFileDirectory_v2(prefix=prefix) + if encoderinfo.get("big_tiff"): + ifd._bigtiff = True + + try: + compression = encoderinfo["compression"] + except KeyError: + compression = im.info.get("compression") + if isinstance(compression, int): + # compression value may be from BMP. Ignore it + compression = None + if compression is None: + compression = "raw" + elif compression == "tiff_jpeg": + # OJPEG is obsolete, so use new-style JPEG compression instead + compression = "jpeg" + elif compression == "tiff_deflate": + compression = "tiff_adobe_deflate" + + libtiff = WRITE_LIBTIFF or compression != "raw" + + # required for color libtiff images + ifd[PLANAR_CONFIGURATION] = 1 + + ifd[IMAGEWIDTH] = im.size[0] + ifd[IMAGELENGTH] = im.size[1] + + # write any arbitrary tags passed in as an ImageFileDirectory + if "tiffinfo" in encoderinfo: + info = encoderinfo["tiffinfo"] + elif "exif" in encoderinfo: + info = encoderinfo["exif"] + if isinstance(info, bytes): + exif = Image.Exif() + exif.load(info) + info = exif + else: + info = {} + logger.debug("Tiffinfo Keys: %s", list(info)) + if isinstance(info, ImageFileDirectory_v1): + info = info.to_v2() + for key in info: + if isinstance(info, Image.Exif) and key in TiffTags.TAGS_V2_GROUPS: + ifd[key] = info.get_ifd(key) + else: + ifd[key] = info.get(key) + try: + ifd.tagtype[key] = info.tagtype[key] + except Exception: + pass # might not be an IFD. Might not have populated type + + legacy_ifd = {} + if hasattr(im, "tag"): + legacy_ifd = im.tag.to_v2() + + supplied_tags = {**legacy_ifd, **getattr(im, "tag_v2", {})} + if supplied_tags.get(PLANAR_CONFIGURATION) == 2 and EXTRASAMPLES in supplied_tags: + # If the image used separate component planes, + # then EXTRASAMPLES should be ignored when saving contiguously + if SAMPLESPERPIXEL in supplied_tags: + supplied_tags[SAMPLESPERPIXEL] -= len(supplied_tags[EXTRASAMPLES]) + del supplied_tags[EXTRASAMPLES] + for tag in ( + # IFD offset that may not be correct in the saved image + EXIFIFD, + # Determined by the image format and should not be copied from legacy_ifd. + SAMPLEFORMAT, + ): + if tag in supplied_tags: + del supplied_tags[tag] + + # additions written by Greg Couch, gregc@cgl.ucsf.edu + # inspired by image-sig posting from Kevin Cazabon, kcazabon@home.com + if hasattr(im, "tag_v2"): + # preserve tags from original TIFF image file + for key in ( + RESOLUTION_UNIT, + X_RESOLUTION, + Y_RESOLUTION, + IPTC_NAA_CHUNK, + PHOTOSHOP_CHUNK, + XMP, + ): + if key in im.tag_v2: + if key == IPTC_NAA_CHUNK and im.tag_v2.tagtype[key] not in ( + TiffTags.BYTE, + TiffTags.UNDEFINED, + ): + del supplied_tags[key] + else: + ifd[key] = im.tag_v2[key] + ifd.tagtype[key] = im.tag_v2.tagtype[key] + + # preserve ICC profile (should also work when saving other formats + # which support profiles as TIFF) -- 2008-06-06 Florian Hoech + icc = encoderinfo.get("icc_profile", im.info.get("icc_profile")) + if icc: + ifd[ICCPROFILE] = icc + + for key, name in [ + (IMAGEDESCRIPTION, "description"), + (X_RESOLUTION, "resolution"), + (Y_RESOLUTION, "resolution"), + (X_RESOLUTION, "x_resolution"), + (Y_RESOLUTION, "y_resolution"), + (RESOLUTION_UNIT, "resolution_unit"), + (SOFTWARE, "software"), + (DATE_TIME, "date_time"), + (ARTIST, "artist"), + (COPYRIGHT, "copyright"), + ]: + if name in encoderinfo: + ifd[key] = encoderinfo[name] + + dpi = encoderinfo.get("dpi") + if dpi: + ifd[RESOLUTION_UNIT] = 2 + ifd[X_RESOLUTION] = dpi[0] + ifd[Y_RESOLUTION] = dpi[1] + + if bits != (1,): + ifd[BITSPERSAMPLE] = bits + if len(bits) != 1: + ifd[SAMPLESPERPIXEL] = len(bits) + if extra is not None: + ifd[EXTRASAMPLES] = extra + if format != 1: + ifd[SAMPLEFORMAT] = format + + if PHOTOMETRIC_INTERPRETATION not in ifd: + ifd[PHOTOMETRIC_INTERPRETATION] = photo + elif im.mode in ("1", "L") and ifd[PHOTOMETRIC_INTERPRETATION] == 0: + if im.mode == "1": + inverted_im = im.copy() + px = inverted_im.load() + if px is not None: + for y in range(inverted_im.height): + for x in range(inverted_im.width): + px[x, y] = 0 if px[x, y] == 255 else 255 + im = inverted_im + else: + im = ImageOps.invert(im) + + if im.mode in ["P", "PA"]: + lut = im.im.getpalette("RGB", "RGB;L") + colormap = [] + colors = len(lut) // 3 + for i in range(3): + colormap += [v * 256 for v in lut[colors * i : colors * (i + 1)]] + colormap += [0] * (256 - colors) + ifd[COLORMAP] = colormap + # data orientation + w, h = ifd[IMAGEWIDTH], ifd[IMAGELENGTH] + stride = len(bits) * ((w * bits[0] + 7) // 8) + if ROWSPERSTRIP not in ifd: + # aim for given strip size (64 KB by default) when using libtiff writer + if libtiff: + im_strip_size = encoderinfo.get("strip_size", STRIP_SIZE) + rows_per_strip = 1 if stride == 0 else min(im_strip_size // stride, h) + # JPEG encoder expects multiple of 8 rows + if compression == "jpeg": + rows_per_strip = min(((rows_per_strip + 7) // 8) * 8, h) + else: + rows_per_strip = h + if rows_per_strip == 0: + rows_per_strip = 1 + ifd[ROWSPERSTRIP] = rows_per_strip + strip_byte_counts = 1 if stride == 0 else stride * ifd[ROWSPERSTRIP] + strips_per_image = (h + ifd[ROWSPERSTRIP] - 1) // ifd[ROWSPERSTRIP] + if strip_byte_counts >= 2**16: + ifd.tagtype[STRIPBYTECOUNTS] = TiffTags.LONG + ifd[STRIPBYTECOUNTS] = (strip_byte_counts,) * (strips_per_image - 1) + ( + stride * h - strip_byte_counts * (strips_per_image - 1), + ) + ifd[STRIPOFFSETS] = tuple( + range(0, strip_byte_counts * strips_per_image, strip_byte_counts) + ) # this is adjusted by IFD writer + # no compression by default: + ifd[COMPRESSION] = COMPRESSION_INFO_REV.get(compression, 1) + + if im.mode == "YCbCr": + for tag, default_value in { + YCBCRSUBSAMPLING: (1, 1), + REFERENCEBLACKWHITE: (0, 255, 128, 255, 128, 255), + }.items(): + ifd.setdefault(tag, default_value) + + blocklist = [TILEWIDTH, TILELENGTH, TILEOFFSETS, TILEBYTECOUNTS] + if libtiff: + if "quality" in encoderinfo: + quality = encoderinfo["quality"] + if not isinstance(quality, int) or quality < 0 or quality > 100: + msg = "Invalid quality setting" + raise ValueError(msg) + if compression != "jpeg": + msg = "quality setting only supported for 'jpeg' compression" + raise ValueError(msg) + ifd[JPEGQUALITY] = quality + + logger.debug("Saving using libtiff encoder") + logger.debug("Items: %s", sorted(ifd.items())) + _fp = 0 + if hasattr(fp, "fileno"): + try: + fp.seek(0) + _fp = fp.fileno() + except io.UnsupportedOperation: + pass + + # optional types for non core tags + types = {} + # STRIPOFFSETS and STRIPBYTECOUNTS are added by the library + # based on the data in the strip. + # OSUBFILETYPE is deprecated. + # The other tags expect arrays with a certain length (fixed or depending on + # BITSPERSAMPLE, etc), passing arrays with a different length will result in + # segfaults. Block these tags until we add extra validation. + # SUBIFD may also cause a segfault. + blocklist += [ + OSUBFILETYPE, + REFERENCEBLACKWHITE, + STRIPBYTECOUNTS, + STRIPOFFSETS, + TRANSFERFUNCTION, + SUBIFD, + ] + + # bits per sample is a single short in the tiff directory, not a list. + atts: dict[int, Any] = {BITSPERSAMPLE: bits[0]} + # Merge the ones that we have with (optional) more bits from + # the original file, e.g x,y resolution so that we can + # save(load('')) == original file. + for tag, value in itertools.chain(ifd.items(), supplied_tags.items()): + # Libtiff can only process certain core items without adding + # them to the custom dictionary. + # Custom items are supported for int, float, unicode, string and byte + # values. Other types and tuples require a tagtype. + if tag not in TiffTags.LIBTIFF_CORE: + if tag in TiffTags.TAGS_V2_GROUPS: + types[tag] = TiffTags.LONG8 + elif tag in ifd.tagtype: + types[tag] = ifd.tagtype[tag] + elif isinstance(value, (int, float, str, bytes)) or ( + isinstance(value, tuple) + and all(isinstance(v, (int, float, IFDRational)) for v in value) + ): + type = TiffTags.lookup(tag).type + if type: + types[tag] = type + if tag not in atts and tag not in blocklist: + if isinstance(value, str): + atts[tag] = value.encode("ascii", "replace") + b"\0" + elif isinstance(value, IFDRational): + atts[tag] = float(value) + else: + atts[tag] = value + + if SAMPLEFORMAT in atts and len(atts[SAMPLEFORMAT]) == 1: + atts[SAMPLEFORMAT] = atts[SAMPLEFORMAT][0] + + logger.debug("Converted items: %s", sorted(atts.items())) + + # libtiff always expects the bytes in native order. + # we're storing image byte order. So, if the rawmode + # contains I;16, we need to convert from native to image + # byte order. + if im.mode in ("I;16", "I;16B", "I;16L"): + rawmode = "I;16N" + + # Pass tags as sorted list so that the tags are set in a fixed order. + # This is required by libtiff for some tags. For example, the JPEGQUALITY + # pseudo tag requires that the COMPRESS tag was already set. + tags = list(atts.items()) + tags.sort() + a = (rawmode, compression, _fp, filename, tags, types) + encoder = Image._getencoder(im.mode, "libtiff", a, encoderconfig) + encoder.setimage(im.im, (0, 0) + im.size) + while True: + errcode, data = encoder.encode(ImageFile.MAXBLOCK)[1:] + if not _fp: + fp.write(data) + if errcode: + break + if errcode < 0: + msg = f"encoder error {errcode} when writing image file" + raise OSError(msg) + + else: + for tag in blocklist: + del ifd[tag] + offset = ifd.save(fp) + + ImageFile._save( + im, + fp, + [ImageFile._Tile("raw", (0, 0) + im.size, offset, (rawmode, stride, 1))], + ) + + # -- helper for multi-page save -- + if "_debug_multipage" in encoderinfo: + # just to access o32 and o16 (using correct byte order) + setattr(im, "_debug_multipage", ifd) + + +class AppendingTiffWriter(io.BytesIO): + fieldSizes = [ + 0, # None + 1, # byte + 1, # ascii + 2, # short + 4, # long + 8, # rational + 1, # sbyte + 1, # undefined + 2, # sshort + 4, # slong + 8, # srational + 4, # float + 8, # double + 4, # ifd + 2, # unicode + 4, # complex + 8, # long8 + ] + + Tags = { + 273, # StripOffsets + 288, # FreeOffsets + 324, # TileOffsets + 519, # JPEGQTables + 520, # JPEGDCTables + 521, # JPEGACTables + } + + def __init__(self, fn: StrOrBytesPath | IO[bytes], new: bool = False) -> None: + self.f: IO[bytes] + if is_path(fn): + self.name = fn + self.close_fp = True + try: + self.f = open(fn, "w+b" if new else "r+b") + except OSError: + self.f = open(fn, "w+b") + else: + self.f = cast(IO[bytes], fn) + self.close_fp = False + self.beginning = self.f.tell() + self.setup() + + def setup(self) -> None: + # Reset everything. + self.f.seek(self.beginning, os.SEEK_SET) + + self.whereToWriteNewIFDOffset: int | None = None + self.offsetOfNewPage = 0 + + self.IIMM = iimm = self.f.read(4) + self._bigtiff = b"\x2b" in iimm + if not iimm: + # empty file - first page + self.isFirst = True + return + + self.isFirst = False + if iimm not in PREFIXES: + msg = "Invalid TIFF file header" + raise RuntimeError(msg) + + self.setEndian("<" if iimm.startswith(II) else ">") + + if self._bigtiff: + self.f.seek(4, os.SEEK_CUR) + self.skipIFDs() + self.goToEnd() + + def finalize(self) -> None: + if self.isFirst: + return + + # fix offsets + self.f.seek(self.offsetOfNewPage) + + iimm = self.f.read(4) + if not iimm: + # Make it easy to finish a frame without committing to a new one. + return + + if iimm != self.IIMM: + msg = "IIMM of new page doesn't match IIMM of first page" + raise RuntimeError(msg) + + if self._bigtiff: + self.f.seek(4, os.SEEK_CUR) + ifd_offset = self._read(8 if self._bigtiff else 4) + ifd_offset += self.offsetOfNewPage + assert self.whereToWriteNewIFDOffset is not None + self.f.seek(self.whereToWriteNewIFDOffset) + self._write(ifd_offset, 8 if self._bigtiff else 4) + self.f.seek(ifd_offset) + self.fixIFD() + + def newFrame(self) -> None: + # Call this to finish a frame. + self.finalize() + self.setup() + + def __enter__(self) -> AppendingTiffWriter: + return self + + def __exit__(self, *args: object) -> None: + if self.close_fp: + self.close() + + def tell(self) -> int: + return self.f.tell() - self.offsetOfNewPage + + def seek(self, offset: int, whence: int = io.SEEK_SET) -> int: + """ + :param offset: Distance to seek. + :param whence: Whether the distance is relative to the start, + end or current position. + :returns: The resulting position, relative to the start. + """ + if whence == os.SEEK_SET: + offset += self.offsetOfNewPage + + self.f.seek(offset, whence) + return self.tell() + + def goToEnd(self) -> None: + self.f.seek(0, os.SEEK_END) + pos = self.f.tell() + + # pad to 16 byte boundary + pad_bytes = 16 - pos % 16 + if 0 < pad_bytes < 16: + self.f.write(bytes(pad_bytes)) + self.offsetOfNewPage = self.f.tell() + + def setEndian(self, endian: str) -> None: + self.endian = endian + self.longFmt = f"{self.endian}L" + self.shortFmt = f"{self.endian}H" + self.tagFormat = f"{self.endian}HH" + ("Q" if self._bigtiff else "L") + + def skipIFDs(self) -> None: + while True: + ifd_offset = self._read(8 if self._bigtiff else 4) + if ifd_offset == 0: + self.whereToWriteNewIFDOffset = self.f.tell() - ( + 8 if self._bigtiff else 4 + ) + break + + self.f.seek(ifd_offset) + num_tags = self._read(8 if self._bigtiff else 2) + self.f.seek(num_tags * (20 if self._bigtiff else 12), os.SEEK_CUR) + + def write(self, data: Buffer, /) -> int: + return self.f.write(data) + + def _fmt(self, field_size: int) -> str: + try: + return {2: "H", 4: "L", 8: "Q"}[field_size] + except KeyError: + msg = "offset is not supported" + raise RuntimeError(msg) + + def _read(self, field_size: int) -> int: + (value,) = struct.unpack( + self.endian + self._fmt(field_size), self.f.read(field_size) + ) + return value + + def readShort(self) -> int: + return self._read(2) + + def readLong(self) -> int: + return self._read(4) + + @staticmethod + def _verify_bytes_written(bytes_written: int | None, expected: int) -> None: + if bytes_written is not None and bytes_written != expected: + msg = f"wrote only {bytes_written} bytes but wanted {expected}" + raise RuntimeError(msg) + + def _rewriteLast( + self, value: int, field_size: int, new_field_size: int = 0 + ) -> None: + self.f.seek(-field_size, os.SEEK_CUR) + if not new_field_size: + new_field_size = field_size + bytes_written = self.f.write( + struct.pack(self.endian + self._fmt(new_field_size), value) + ) + self._verify_bytes_written(bytes_written, new_field_size) + + def rewriteLastShortToLong(self, value: int) -> None: + self._rewriteLast(value, 2, 4) + + def rewriteLastShort(self, value: int) -> None: + return self._rewriteLast(value, 2) + + def rewriteLastLong(self, value: int) -> None: + return self._rewriteLast(value, 4) + + def _write(self, value: int, field_size: int) -> None: + bytes_written = self.f.write( + struct.pack(self.endian + self._fmt(field_size), value) + ) + self._verify_bytes_written(bytes_written, field_size) + + def writeShort(self, value: int) -> None: + self._write(value, 2) + + def writeLong(self, value: int) -> None: + self._write(value, 4) + + def close(self) -> None: + self.finalize() + if self.close_fp: + self.f.close() + + def fixIFD(self) -> None: + num_tags = self._read(8 if self._bigtiff else 2) + + for i in range(num_tags): + tag, field_type, count = struct.unpack( + self.tagFormat, self.f.read(12 if self._bigtiff else 8) + ) + + field_size = self.fieldSizes[field_type] + total_size = field_size * count + fmt_size = 8 if self._bigtiff else 4 + is_local = total_size <= fmt_size + if not is_local: + offset = self._read(fmt_size) + self.offsetOfNewPage + self._rewriteLast(offset, fmt_size) + + if tag in self.Tags: + cur_pos = self.f.tell() + + logger.debug( + "fixIFD: %s (%d) - type: %s (%d) - type size: %d - count: %d", + TiffTags.lookup(tag).name, + tag, + TYPES.get(field_type, "unknown"), + field_type, + field_size, + count, + ) + + if is_local: + self._fixOffsets(count, field_size) + self.f.seek(cur_pos + fmt_size) + else: + self.f.seek(offset) + self._fixOffsets(count, field_size) + self.f.seek(cur_pos) + + elif is_local: + # skip the locally stored value that is not an offset + self.f.seek(fmt_size, os.SEEK_CUR) + + def _fixOffsets(self, count: int, field_size: int) -> None: + for i in range(count): + offset = self._read(field_size) + offset += self.offsetOfNewPage + + new_field_size = 0 + if self._bigtiff and field_size in (2, 4) and offset >= 2**32: + # offset is now too large - we must convert long to long8 + new_field_size = 8 + elif field_size == 2 and offset >= 2**16: + # offset is now too large - we must convert short to long + new_field_size = 4 + if new_field_size: + if count != 1: + msg = "not implemented" + raise RuntimeError(msg) # XXX TODO + + # simple case - the offset is just one and therefore it is + # local (not referenced with another offset) + self._rewriteLast(offset, field_size, new_field_size) + # Move back past the new offset, past 'count', and before 'field_type' + rewind = -new_field_size - 4 - 2 + self.f.seek(rewind, os.SEEK_CUR) + self.writeShort(new_field_size) # rewrite the type + self.f.seek(2 - rewind, os.SEEK_CUR) + else: + self._rewriteLast(offset, field_size) + + def fixOffsets( + self, count: int, isShort: bool = False, isLong: bool = False + ) -> None: + if isShort: + field_size = 2 + elif isLong: + field_size = 4 + else: + field_size = 0 + return self._fixOffsets(count, field_size) + + +def _save_all(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + append_images = list(im.encoderinfo.get("append_images", [])) + if not hasattr(im, "n_frames") and not append_images: + return _save(im, fp, filename) + + cur_idx = im.tell() + try: + with AppendingTiffWriter(fp) as tf: + for ims in [im] + append_images: + encoderinfo = ims._attach_default_encoderinfo(im) + if not hasattr(ims, "encoderconfig"): + ims.encoderconfig = () + nfr = getattr(ims, "n_frames", 1) + + for idx in range(nfr): + ims.seek(idx) + ims.load() + _save(ims, tf, filename) + tf.newFrame() + ims.encoderinfo = encoderinfo + finally: + im.seek(cur_idx) + + +# +# -------------------------------------------------------------------- +# Register + +Image.register_open(TiffImageFile.format, TiffImageFile, _accept) +Image.register_save(TiffImageFile.format, _save) +Image.register_save_all(TiffImageFile.format, _save_all) + +Image.register_extensions(TiffImageFile.format, [".tif", ".tiff"]) + +Image.register_mime(TiffImageFile.format, "image/tiff") diff --git a/.venv/lib/python3.11/site-packages/PIL/TiffTags.py b/.venv/lib/python3.11/site-packages/PIL/TiffTags.py new file mode 100644 index 0000000000000000000000000000000000000000..613a3b7def7149628039ddb817fcf8dbba395b18 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/TiffTags.py @@ -0,0 +1,566 @@ +# +# The Python Imaging Library. +# $Id$ +# +# TIFF tags +# +# This module provides clear-text names for various well-known +# TIFF tags. the TIFF codec works just fine without it. +# +# Copyright (c) Secret Labs AB 1999. +# +# See the README file for information on usage and redistribution. +# + +## +# This module provides constants and clear-text names for various +# well-known TIFF tags. +## +from __future__ import annotations + +from typing import NamedTuple + + +class _TagInfo(NamedTuple): + value: int | None + name: str + type: int | None + length: int | None + enum: dict[str, int] + + +class TagInfo(_TagInfo): + __slots__: list[str] = [] + + def __new__( + cls, + value: int | None = None, + name: str = "unknown", + type: int | None = None, + length: int | None = None, + enum: dict[str, int] | None = None, + ) -> TagInfo: + return super().__new__(cls, value, name, type, length, enum or {}) + + def cvt_enum(self, value: str) -> int | str: + # Using get will call hash(value), which can be expensive + # for some types (e.g. Fraction). Since self.enum is rarely + # used, it's usually better to test it first. + return self.enum.get(value, value) if self.enum else value + + +def lookup(tag: int, group: int | None = None) -> TagInfo: + """ + :param tag: Integer tag number + :param group: Which :py:data:`~PIL.TiffTags.TAGS_V2_GROUPS` to look in + + .. versionadded:: 8.3.0 + + :returns: Taginfo namedtuple, From the ``TAGS_V2`` info if possible, + otherwise just populating the value and name from ``TAGS``. + If the tag is not recognized, "unknown" is returned for the name + + """ + + if group is not None: + info = TAGS_V2_GROUPS[group].get(tag) if group in TAGS_V2_GROUPS else None + else: + info = TAGS_V2.get(tag) + return info or TagInfo(tag, TAGS.get(tag, "unknown")) + + +## +# Map tag numbers to tag info. +# +# id: (Name, Type, Length[, enum_values]) +# +# The length here differs from the length in the tiff spec. For +# numbers, the tiff spec is for the number of fields returned. We +# agree here. For string-like types, the tiff spec uses the length of +# field in bytes. In Pillow, we are using the number of expected +# fields, in general 1 for string-like types. + + +BYTE = 1 +ASCII = 2 +SHORT = 3 +LONG = 4 +RATIONAL = 5 +SIGNED_BYTE = 6 +UNDEFINED = 7 +SIGNED_SHORT = 8 +SIGNED_LONG = 9 +SIGNED_RATIONAL = 10 +FLOAT = 11 +DOUBLE = 12 +IFD = 13 +LONG8 = 16 + +_tags_v2: dict[int, tuple[str, int, int] | tuple[str, int, int, dict[str, int]]] = { + 254: ("NewSubfileType", LONG, 1), + 255: ("SubfileType", SHORT, 1), + 256: ("ImageWidth", LONG, 1), + 257: ("ImageLength", LONG, 1), + 258: ("BitsPerSample", SHORT, 0), + 259: ( + "Compression", + SHORT, + 1, + { + "Uncompressed": 1, + "CCITT 1d": 2, + "Group 3 Fax": 3, + "Group 4 Fax": 4, + "LZW": 5, + "JPEG": 6, + "PackBits": 32773, + }, + ), + 262: ( + "PhotometricInterpretation", + SHORT, + 1, + { + "WhiteIsZero": 0, + "BlackIsZero": 1, + "RGB": 2, + "RGB Palette": 3, + "Transparency Mask": 4, + "CMYK": 5, + "YCbCr": 6, + "CieLAB": 8, + "CFA": 32803, # TIFF/EP, Adobe DNG + "LinearRaw": 32892, # Adobe DNG + }, + ), + 263: ("Threshholding", SHORT, 1), + 264: ("CellWidth", SHORT, 1), + 265: ("CellLength", SHORT, 1), + 266: ("FillOrder", SHORT, 1), + 269: ("DocumentName", ASCII, 1), + 270: ("ImageDescription", ASCII, 1), + 271: ("Make", ASCII, 1), + 272: ("Model", ASCII, 1), + 273: ("StripOffsets", LONG, 0), + 274: ("Orientation", SHORT, 1), + 277: ("SamplesPerPixel", SHORT, 1), + 278: ("RowsPerStrip", LONG, 1), + 279: ("StripByteCounts", LONG, 0), + 280: ("MinSampleValue", SHORT, 0), + 281: ("MaxSampleValue", SHORT, 0), + 282: ("XResolution", RATIONAL, 1), + 283: ("YResolution", RATIONAL, 1), + 284: ("PlanarConfiguration", SHORT, 1, {"Contiguous": 1, "Separate": 2}), + 285: ("PageName", ASCII, 1), + 286: ("XPosition", RATIONAL, 1), + 287: ("YPosition", RATIONAL, 1), + 288: ("FreeOffsets", LONG, 1), + 289: ("FreeByteCounts", LONG, 1), + 290: ("GrayResponseUnit", SHORT, 1), + 291: ("GrayResponseCurve", SHORT, 0), + 292: ("T4Options", LONG, 1), + 293: ("T6Options", LONG, 1), + 296: ("ResolutionUnit", SHORT, 1, {"none": 1, "inch": 2, "cm": 3}), + 297: ("PageNumber", SHORT, 2), + 301: ("TransferFunction", SHORT, 0), + 305: ("Software", ASCII, 1), + 306: ("DateTime", ASCII, 1), + 315: ("Artist", ASCII, 1), + 316: ("HostComputer", ASCII, 1), + 317: ("Predictor", SHORT, 1, {"none": 1, "Horizontal Differencing": 2}), + 318: ("WhitePoint", RATIONAL, 2), + 319: ("PrimaryChromaticities", RATIONAL, 6), + 320: ("ColorMap", SHORT, 0), + 321: ("HalftoneHints", SHORT, 2), + 322: ("TileWidth", LONG, 1), + 323: ("TileLength", LONG, 1), + 324: ("TileOffsets", LONG, 0), + 325: ("TileByteCounts", LONG, 0), + 330: ("SubIFDs", LONG, 0), + 332: ("InkSet", SHORT, 1), + 333: ("InkNames", ASCII, 1), + 334: ("NumberOfInks", SHORT, 1), + 336: ("DotRange", SHORT, 0), + 337: ("TargetPrinter", ASCII, 1), + 338: ("ExtraSamples", SHORT, 0), + 339: ("SampleFormat", SHORT, 0), + 340: ("SMinSampleValue", DOUBLE, 0), + 341: ("SMaxSampleValue", DOUBLE, 0), + 342: ("TransferRange", SHORT, 6), + 347: ("JPEGTables", UNDEFINED, 1), + # obsolete JPEG tags + 512: ("JPEGProc", SHORT, 1), + 513: ("JPEGInterchangeFormat", LONG, 1), + 514: ("JPEGInterchangeFormatLength", LONG, 1), + 515: ("JPEGRestartInterval", SHORT, 1), + 517: ("JPEGLosslessPredictors", SHORT, 0), + 518: ("JPEGPointTransforms", SHORT, 0), + 519: ("JPEGQTables", LONG, 0), + 520: ("JPEGDCTables", LONG, 0), + 521: ("JPEGACTables", LONG, 0), + 529: ("YCbCrCoefficients", RATIONAL, 3), + 530: ("YCbCrSubSampling", SHORT, 2), + 531: ("YCbCrPositioning", SHORT, 1), + 532: ("ReferenceBlackWhite", RATIONAL, 6), + 700: ("XMP", BYTE, 0), + # Four private SGI tags + 32995: ("Matteing", SHORT, 1), + 32996: ("DataType", SHORT, 0), + 32997: ("ImageDepth", LONG, 1), + 32998: ("TileDepth", LONG, 1), + 33432: ("Copyright", ASCII, 1), + 33723: ("IptcNaaInfo", UNDEFINED, 1), + 34377: ("PhotoshopInfo", BYTE, 0), + # FIXME add more tags here + 34665: ("ExifIFD", LONG, 1), + 34675: ("ICCProfile", UNDEFINED, 1), + 34853: ("GPSInfoIFD", LONG, 1), + 36864: ("ExifVersion", UNDEFINED, 1), + 37724: ("ImageSourceData", UNDEFINED, 1), + 40965: ("InteroperabilityIFD", LONG, 1), + 41730: ("CFAPattern", UNDEFINED, 1), + # MPInfo + 45056: ("MPFVersion", UNDEFINED, 1), + 45057: ("NumberOfImages", LONG, 1), + 45058: ("MPEntry", UNDEFINED, 1), + 45059: ("ImageUIDList", UNDEFINED, 0), # UNDONE, check + 45060: ("TotalFrames", LONG, 1), + 45313: ("MPIndividualNum", LONG, 1), + 45569: ("PanOrientation", LONG, 1), + 45570: ("PanOverlap_H", RATIONAL, 1), + 45571: ("PanOverlap_V", RATIONAL, 1), + 45572: ("BaseViewpointNum", LONG, 1), + 45573: ("ConvergenceAngle", SIGNED_RATIONAL, 1), + 45574: ("BaselineLength", RATIONAL, 1), + 45575: ("VerticalDivergence", SIGNED_RATIONAL, 1), + 45576: ("AxisDistance_X", SIGNED_RATIONAL, 1), + 45577: ("AxisDistance_Y", SIGNED_RATIONAL, 1), + 45578: ("AxisDistance_Z", SIGNED_RATIONAL, 1), + 45579: ("YawAngle", SIGNED_RATIONAL, 1), + 45580: ("PitchAngle", SIGNED_RATIONAL, 1), + 45581: ("RollAngle", SIGNED_RATIONAL, 1), + 40960: ("FlashPixVersion", UNDEFINED, 1), + 50741: ("MakerNoteSafety", SHORT, 1, {"Unsafe": 0, "Safe": 1}), + 50780: ("BestQualityScale", RATIONAL, 1), + 50838: ("ImageJMetaDataByteCounts", LONG, 0), # Can be more than one + 50839: ("ImageJMetaData", UNDEFINED, 1), # see Issue #2006 +} +_tags_v2_groups = { + # ExifIFD + 34665: { + 36864: ("ExifVersion", UNDEFINED, 1), + 40960: ("FlashPixVersion", UNDEFINED, 1), + 40965: ("InteroperabilityIFD", LONG, 1), + 41730: ("CFAPattern", UNDEFINED, 1), + }, + # GPSInfoIFD + 34853: { + 0: ("GPSVersionID", BYTE, 4), + 1: ("GPSLatitudeRef", ASCII, 2), + 2: ("GPSLatitude", RATIONAL, 3), + 3: ("GPSLongitudeRef", ASCII, 2), + 4: ("GPSLongitude", RATIONAL, 3), + 5: ("GPSAltitudeRef", BYTE, 1), + 6: ("GPSAltitude", RATIONAL, 1), + 7: ("GPSTimeStamp", RATIONAL, 3), + 8: ("GPSSatellites", ASCII, 0), + 9: ("GPSStatus", ASCII, 2), + 10: ("GPSMeasureMode", ASCII, 2), + 11: ("GPSDOP", RATIONAL, 1), + 12: ("GPSSpeedRef", ASCII, 2), + 13: ("GPSSpeed", RATIONAL, 1), + 14: ("GPSTrackRef", ASCII, 2), + 15: ("GPSTrack", RATIONAL, 1), + 16: ("GPSImgDirectionRef", ASCII, 2), + 17: ("GPSImgDirection", RATIONAL, 1), + 18: ("GPSMapDatum", ASCII, 0), + 19: ("GPSDestLatitudeRef", ASCII, 2), + 20: ("GPSDestLatitude", RATIONAL, 3), + 21: ("GPSDestLongitudeRef", ASCII, 2), + 22: ("GPSDestLongitude", RATIONAL, 3), + 23: ("GPSDestBearingRef", ASCII, 2), + 24: ("GPSDestBearing", RATIONAL, 1), + 25: ("GPSDestDistanceRef", ASCII, 2), + 26: ("GPSDestDistance", RATIONAL, 1), + 27: ("GPSProcessingMethod", UNDEFINED, 0), + 28: ("GPSAreaInformation", UNDEFINED, 0), + 29: ("GPSDateStamp", ASCII, 11), + 30: ("GPSDifferential", SHORT, 1), + }, + # InteroperabilityIFD + 40965: {1: ("InteropIndex", ASCII, 1), 2: ("InteropVersion", UNDEFINED, 1)}, +} + +# Legacy Tags structure +# these tags aren't included above, but were in the previous versions +TAGS: dict[int | tuple[int, int], str] = { + 347: "JPEGTables", + 700: "XMP", + # Additional Exif Info + 32932: "Wang Annotation", + 33434: "ExposureTime", + 33437: "FNumber", + 33445: "MD FileTag", + 33446: "MD ScalePixel", + 33447: "MD ColorTable", + 33448: "MD LabName", + 33449: "MD SampleInfo", + 33450: "MD PrepDate", + 33451: "MD PrepTime", + 33452: "MD FileUnits", + 33550: "ModelPixelScaleTag", + 33723: "IptcNaaInfo", + 33918: "INGR Packet Data Tag", + 33919: "INGR Flag Registers", + 33920: "IrasB Transformation Matrix", + 33922: "ModelTiepointTag", + 34264: "ModelTransformationTag", + 34377: "PhotoshopInfo", + 34735: "GeoKeyDirectoryTag", + 34736: "GeoDoubleParamsTag", + 34737: "GeoAsciiParamsTag", + 34850: "ExposureProgram", + 34852: "SpectralSensitivity", + 34855: "ISOSpeedRatings", + 34856: "OECF", + 34864: "SensitivityType", + 34865: "StandardOutputSensitivity", + 34866: "RecommendedExposureIndex", + 34867: "ISOSpeed", + 34868: "ISOSpeedLatitudeyyy", + 34869: "ISOSpeedLatitudezzz", + 34908: "HylaFAX FaxRecvParams", + 34909: "HylaFAX FaxSubAddress", + 34910: "HylaFAX FaxRecvTime", + 36864: "ExifVersion", + 36867: "DateTimeOriginal", + 36868: "DateTimeDigitized", + 37121: "ComponentsConfiguration", + 37122: "CompressedBitsPerPixel", + 37724: "ImageSourceData", + 37377: "ShutterSpeedValue", + 37378: "ApertureValue", + 37379: "BrightnessValue", + 37380: "ExposureBiasValue", + 37381: "MaxApertureValue", + 37382: "SubjectDistance", + 37383: "MeteringMode", + 37384: "LightSource", + 37385: "Flash", + 37386: "FocalLength", + 37396: "SubjectArea", + 37500: "MakerNote", + 37510: "UserComment", + 37520: "SubSec", + 37521: "SubSecTimeOriginal", + 37522: "SubsecTimeDigitized", + 40960: "FlashPixVersion", + 40961: "ColorSpace", + 40962: "PixelXDimension", + 40963: "PixelYDimension", + 40964: "RelatedSoundFile", + 40965: "InteroperabilityIFD", + 41483: "FlashEnergy", + 41484: "SpatialFrequencyResponse", + 41486: "FocalPlaneXResolution", + 41487: "FocalPlaneYResolution", + 41488: "FocalPlaneResolutionUnit", + 41492: "SubjectLocation", + 41493: "ExposureIndex", + 41495: "SensingMethod", + 41728: "FileSource", + 41729: "SceneType", + 41730: "CFAPattern", + 41985: "CustomRendered", + 41986: "ExposureMode", + 41987: "WhiteBalance", + 41988: "DigitalZoomRatio", + 41989: "FocalLengthIn35mmFilm", + 41990: "SceneCaptureType", + 41991: "GainControl", + 41992: "Contrast", + 41993: "Saturation", + 41994: "Sharpness", + 41995: "DeviceSettingDescription", + 41996: "SubjectDistanceRange", + 42016: "ImageUniqueID", + 42032: "CameraOwnerName", + 42033: "BodySerialNumber", + 42034: "LensSpecification", + 42035: "LensMake", + 42036: "LensModel", + 42037: "LensSerialNumber", + 42112: "GDAL_METADATA", + 42113: "GDAL_NODATA", + 42240: "Gamma", + 50215: "Oce Scanjob Description", + 50216: "Oce Application Selector", + 50217: "Oce Identification Number", + 50218: "Oce ImageLogic Characteristics", + # Adobe DNG + 50706: "DNGVersion", + 50707: "DNGBackwardVersion", + 50708: "UniqueCameraModel", + 50709: "LocalizedCameraModel", + 50710: "CFAPlaneColor", + 50711: "CFALayout", + 50712: "LinearizationTable", + 50713: "BlackLevelRepeatDim", + 50714: "BlackLevel", + 50715: "BlackLevelDeltaH", + 50716: "BlackLevelDeltaV", + 50717: "WhiteLevel", + 50718: "DefaultScale", + 50719: "DefaultCropOrigin", + 50720: "DefaultCropSize", + 50721: "ColorMatrix1", + 50722: "ColorMatrix2", + 50723: "CameraCalibration1", + 50724: "CameraCalibration2", + 50725: "ReductionMatrix1", + 50726: "ReductionMatrix2", + 50727: "AnalogBalance", + 50728: "AsShotNeutral", + 50729: "AsShotWhiteXY", + 50730: "BaselineExposure", + 50731: "BaselineNoise", + 50732: "BaselineSharpness", + 50733: "BayerGreenSplit", + 50734: "LinearResponseLimit", + 50735: "CameraSerialNumber", + 50736: "LensInfo", + 50737: "ChromaBlurRadius", + 50738: "AntiAliasStrength", + 50740: "DNGPrivateData", + 50778: "CalibrationIlluminant1", + 50779: "CalibrationIlluminant2", + 50784: "Alias Layer Metadata", +} + +TAGS_V2: dict[int, TagInfo] = {} +TAGS_V2_GROUPS: dict[int, dict[int, TagInfo]] = {} + + +def _populate() -> None: + for k, v in _tags_v2.items(): + # Populate legacy structure. + TAGS[k] = v[0] + if len(v) == 4: + for sk, sv in v[3].items(): + TAGS[(k, sv)] = sk + + TAGS_V2[k] = TagInfo(k, *v) + + for group, tags in _tags_v2_groups.items(): + TAGS_V2_GROUPS[group] = {k: TagInfo(k, *v) for k, v in tags.items()} + + +_populate() +## +# Map type numbers to type names -- defined in ImageFileDirectory. + +TYPES: dict[int, str] = {} + +# +# These tags are handled by default in libtiff, without +# adding to the custom dictionary. From tif_dir.c, searching for +# case TIFFTAG in the _TIFFVSetField function: +# Line: item. +# 148: case TIFFTAG_SUBFILETYPE: +# 151: case TIFFTAG_IMAGEWIDTH: +# 154: case TIFFTAG_IMAGELENGTH: +# 157: case TIFFTAG_BITSPERSAMPLE: +# 181: case TIFFTAG_COMPRESSION: +# 202: case TIFFTAG_PHOTOMETRIC: +# 205: case TIFFTAG_THRESHHOLDING: +# 208: case TIFFTAG_FILLORDER: +# 214: case TIFFTAG_ORIENTATION: +# 221: case TIFFTAG_SAMPLESPERPIXEL: +# 228: case TIFFTAG_ROWSPERSTRIP: +# 238: case TIFFTAG_MINSAMPLEVALUE: +# 241: case TIFFTAG_MAXSAMPLEVALUE: +# 244: case TIFFTAG_SMINSAMPLEVALUE: +# 247: case TIFFTAG_SMAXSAMPLEVALUE: +# 250: case TIFFTAG_XRESOLUTION: +# 256: case TIFFTAG_YRESOLUTION: +# 262: case TIFFTAG_PLANARCONFIG: +# 268: case TIFFTAG_XPOSITION: +# 271: case TIFFTAG_YPOSITION: +# 274: case TIFFTAG_RESOLUTIONUNIT: +# 280: case TIFFTAG_PAGENUMBER: +# 284: case TIFFTAG_HALFTONEHINTS: +# 288: case TIFFTAG_COLORMAP: +# 294: case TIFFTAG_EXTRASAMPLES: +# 298: case TIFFTAG_MATTEING: +# 305: case TIFFTAG_TILEWIDTH: +# 316: case TIFFTAG_TILELENGTH: +# 327: case TIFFTAG_TILEDEPTH: +# 333: case TIFFTAG_DATATYPE: +# 344: case TIFFTAG_SAMPLEFORMAT: +# 361: case TIFFTAG_IMAGEDEPTH: +# 364: case TIFFTAG_SUBIFD: +# 376: case TIFFTAG_YCBCRPOSITIONING: +# 379: case TIFFTAG_YCBCRSUBSAMPLING: +# 383: case TIFFTAG_TRANSFERFUNCTION: +# 389: case TIFFTAG_REFERENCEBLACKWHITE: +# 393: case TIFFTAG_INKNAMES: + +# Following pseudo-tags are also handled by default in libtiff: +# TIFFTAG_JPEGQUALITY 65537 + +# some of these are not in our TAGS_V2 dict and were included from tiff.h + +# This list also exists in encode.c +LIBTIFF_CORE = { + 255, + 256, + 257, + 258, + 259, + 262, + 263, + 266, + 274, + 277, + 278, + 280, + 281, + 340, + 341, + 282, + 283, + 284, + 286, + 287, + 296, + 297, + 321, + 320, + 338, + 32995, + 322, + 323, + 32998, + 32996, + 339, + 32997, + 330, + 531, + 530, + 301, + 532, + 333, + # as above + 269, # this has been in our tests forever, and works + 65537, +} + +LIBTIFF_CORE.remove(255) # We don't have support for subfiletypes +LIBTIFF_CORE.remove(322) # We don't have support for writing tiled images with libtiff +LIBTIFF_CORE.remove(323) # Tiled images + +# Note to advanced users: There may be combinations of these +# parameters and values that when added properly, will work and +# produce valid tiff images that may work in your application. +# It is safe to add and remove tags from this set from Pillow's point +# of view so long as you test against libtiff. diff --git a/.venv/lib/python3.11/site-packages/PIL/WalImageFile.py b/.venv/lib/python3.11/site-packages/PIL/WalImageFile.py new file mode 100644 index 0000000000000000000000000000000000000000..07bbf747155607a3ada3f4b752f990099c1e711a --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/WalImageFile.py @@ -0,0 +1,129 @@ +# +# The Python Imaging Library. +# $Id$ +# +# WAL file handling +# +# History: +# 2003-04-23 fl created +# +# Copyright (c) 2003 by Fredrik Lundh. +# +# See the README file for information on usage and redistribution. +# + +""" +This reader is based on the specification available from: +https://www.flipcode.com/archives/Quake_2_BSP_File_Format.shtml +and has been tested with a few sample files found using google. + +.. note:: + This format cannot be automatically recognized, so the reader + is not registered for use with :py:func:`PIL.Image.open()`. + To open a WAL file, use the :py:func:`PIL.WalImageFile.open()` function instead. +""" + +from __future__ import annotations + +from typing import IO + +from . import Image, ImageFile +from ._binary import i32le as i32 +from ._typing import StrOrBytesPath + + +class WalImageFile(ImageFile.ImageFile): + format = "WAL" + format_description = "Quake2 Texture" + + def _open(self) -> None: + self._mode = "P" + + # read header fields + assert self.fp is not None + header = self.fp.read(32 + 24 + 32 + 12) + self._size = i32(header, 32), i32(header, 36) + Image._decompression_bomb_check(self.size) + + # load pixel data + offset = i32(header, 40) + self.fp.seek(offset) + + # strings are null-terminated + self.info["name"] = header[:32].split(b"\0", 1)[0] + if next_name := header[56 : 56 + 32].split(b"\0", 1)[0]: + self.info["next_name"] = next_name + + def load(self) -> Image.core.PixelAccess | None: + if self._im is None: + assert self.fp is not None + self.im = Image.core.new(self.mode, self.size) + self.frombytes(self.fp.read(self.size[0] * self.size[1])) + self.putpalette(quake2palette) + return Image.Image.load(self) + + +def open(filename: StrOrBytesPath | IO[bytes]) -> WalImageFile: + """ + Load texture from a Quake2 WAL texture file. + + By default, a Quake2 standard palette is attached to the texture. + To override the palette, use the :py:func:`PIL.Image.Image.putpalette()` method. + + :param filename: WAL file name, or an opened file handle. + :returns: An image instance. + """ + return WalImageFile(filename) + + +quake2palette = ( + # default palette taken from piffo 0.93 by Hans Häggström + b"\x01\x01\x01\x0b\x0b\x0b\x12\x12\x12\x17\x17\x17\x1b\x1b\x1b\x1e" + b"\x1e\x1e\x22\x22\x22\x26\x26\x26\x29\x29\x29\x2c\x2c\x2c\x2f\x2f" + b"\x2f\x32\x32\x32\x35\x35\x35\x37\x37\x37\x3a\x3a\x3a\x3c\x3c\x3c" + b"\x24\x1e\x13\x22\x1c\x12\x20\x1b\x12\x1f\x1a\x10\x1d\x19\x10\x1b" + b"\x17\x0f\x1a\x16\x0f\x18\x14\x0d\x17\x13\x0d\x16\x12\x0d\x14\x10" + b"\x0b\x13\x0f\x0b\x10\x0d\x0a\x0f\x0b\x0a\x0d\x0b\x07\x0b\x0a\x07" + b"\x23\x23\x26\x22\x22\x25\x22\x20\x23\x21\x1f\x22\x20\x1e\x20\x1f" + b"\x1d\x1e\x1d\x1b\x1c\x1b\x1a\x1a\x1a\x19\x19\x18\x17\x17\x17\x16" + b"\x16\x14\x14\x14\x13\x13\x13\x10\x10\x10\x0f\x0f\x0f\x0d\x0d\x0d" + b"\x2d\x28\x20\x29\x24\x1c\x27\x22\x1a\x25\x1f\x17\x38\x2e\x1e\x31" + b"\x29\x1a\x2c\x25\x17\x26\x20\x14\x3c\x30\x14\x37\x2c\x13\x33\x28" + b"\x12\x2d\x24\x10\x28\x1f\x0f\x22\x1a\x0b\x1b\x14\x0a\x13\x0f\x07" + b"\x31\x1a\x16\x30\x17\x13\x2e\x16\x10\x2c\x14\x0d\x2a\x12\x0b\x27" + b"\x0f\x0a\x25\x0f\x07\x21\x0d\x01\x1e\x0b\x01\x1c\x0b\x01\x1a\x0b" + b"\x01\x18\x0a\x01\x16\x0a\x01\x13\x0a\x01\x10\x07\x01\x0d\x07\x01" + b"\x29\x23\x1e\x27\x21\x1c\x26\x20\x1b\x25\x1f\x1a\x23\x1d\x19\x21" + b"\x1c\x18\x20\x1b\x17\x1e\x19\x16\x1c\x18\x14\x1b\x17\x13\x19\x14" + b"\x10\x17\x13\x0f\x14\x10\x0d\x12\x0f\x0b\x0f\x0b\x0a\x0b\x0a\x07" + b"\x26\x1a\x0f\x23\x19\x0f\x20\x17\x0f\x1c\x16\x0f\x19\x13\x0d\x14" + b"\x10\x0b\x10\x0d\x0a\x0b\x0a\x07\x33\x22\x1f\x35\x29\x26\x37\x2f" + b"\x2d\x39\x35\x34\x37\x39\x3a\x33\x37\x39\x30\x34\x36\x2b\x31\x34" + b"\x27\x2e\x31\x22\x2b\x2f\x1d\x28\x2c\x17\x25\x2a\x0f\x20\x26\x0d" + b"\x1e\x25\x0b\x1c\x22\x0a\x1b\x20\x07\x19\x1e\x07\x17\x1b\x07\x14" + b"\x18\x01\x12\x16\x01\x0f\x12\x01\x0b\x0d\x01\x07\x0a\x01\x01\x01" + b"\x2c\x21\x21\x2a\x1f\x1f\x29\x1d\x1d\x27\x1c\x1c\x26\x1a\x1a\x24" + b"\x18\x18\x22\x17\x17\x21\x16\x16\x1e\x13\x13\x1b\x12\x12\x18\x10" + b"\x10\x16\x0d\x0d\x12\x0b\x0b\x0d\x0a\x0a\x0a\x07\x07\x01\x01\x01" + b"\x2e\x30\x29\x2d\x2e\x27\x2b\x2c\x26\x2a\x2a\x24\x28\x29\x23\x27" + b"\x27\x21\x26\x26\x1f\x24\x24\x1d\x22\x22\x1c\x1f\x1f\x1a\x1c\x1c" + b"\x18\x19\x19\x16\x17\x17\x13\x13\x13\x10\x0f\x0f\x0d\x0b\x0b\x0a" + b"\x30\x1e\x1b\x2d\x1c\x19\x2c\x1a\x17\x2a\x19\x14\x28\x17\x13\x26" + b"\x16\x10\x24\x13\x0f\x21\x12\x0d\x1f\x10\x0b\x1c\x0f\x0a\x19\x0d" + b"\x0a\x16\x0b\x07\x12\x0a\x07\x0f\x07\x01\x0a\x01\x01\x01\x01\x01" + b"\x28\x29\x38\x26\x27\x36\x25\x26\x34\x24\x24\x31\x22\x22\x2f\x20" + b"\x21\x2d\x1e\x1f\x2a\x1d\x1d\x27\x1b\x1b\x25\x19\x19\x21\x17\x17" + b"\x1e\x14\x14\x1b\x13\x12\x17\x10\x0f\x13\x0d\x0b\x0f\x0a\x07\x07" + b"\x2f\x32\x29\x2d\x30\x26\x2b\x2e\x24\x29\x2c\x21\x27\x2a\x1e\x25" + b"\x28\x1c\x23\x26\x1a\x21\x25\x18\x1e\x22\x14\x1b\x1f\x10\x19\x1c" + b"\x0d\x17\x1a\x0a\x13\x17\x07\x10\x13\x01\x0d\x0f\x01\x0a\x0b\x01" + b"\x01\x3f\x01\x13\x3c\x0b\x1b\x39\x10\x20\x35\x14\x23\x31\x17\x23" + b"\x2d\x18\x23\x29\x18\x3f\x3f\x3f\x3f\x3f\x39\x3f\x3f\x31\x3f\x3f" + b"\x2a\x3f\x3f\x20\x3f\x3f\x14\x3f\x3c\x12\x3f\x39\x0f\x3f\x35\x0b" + b"\x3f\x32\x07\x3f\x2d\x01\x3d\x2a\x01\x3b\x26\x01\x39\x21\x01\x37" + b"\x1d\x01\x34\x1a\x01\x32\x16\x01\x2f\x12\x01\x2d\x0f\x01\x2a\x0b" + b"\x01\x27\x07\x01\x23\x01\x01\x1d\x01\x01\x17\x01\x01\x10\x01\x01" + b"\x3d\x01\x01\x19\x19\x3f\x3f\x01\x01\x01\x01\x3f\x16\x16\x13\x10" + b"\x10\x0f\x0d\x0d\x0b\x3c\x2e\x2a\x36\x27\x20\x30\x21\x18\x29\x1b" + b"\x10\x3c\x39\x37\x37\x32\x2f\x31\x2c\x28\x2b\x26\x21\x30\x22\x20" +) diff --git a/.venv/lib/python3.11/site-packages/PIL/WebPImagePlugin.py b/.venv/lib/python3.11/site-packages/PIL/WebPImagePlugin.py new file mode 100644 index 0000000000000000000000000000000000000000..63a48169182159ac0c64f58cc6ae4e3628b8372e --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/WebPImagePlugin.py @@ -0,0 +1,322 @@ +from __future__ import annotations + +from io import BytesIO + +from . import Image, ImageFile + +try: + from . import _webp + + SUPPORTED = True +except ImportError: + SUPPORTED = False + +TYPE_CHECKING = False +if TYPE_CHECKING: + from typing import IO, Any + +_VP8_MODES_BY_IDENTIFIER = { + b"VP8 ": "RGB", + b"VP8X": "RGBA", + b"VP8L": "RGBA", # lossless +} + + +def _accept(prefix: bytes) -> bool | str: + is_riff_file_format = prefix.startswith(b"RIFF") + is_webp_file = prefix[8:12] == b"WEBP" + is_valid_vp8_mode = prefix[12:16] in _VP8_MODES_BY_IDENTIFIER + + if is_riff_file_format and is_webp_file and is_valid_vp8_mode: + if not SUPPORTED: + return ( + "image file could not be identified because WEBP support not installed" + ) + return True + return False + + +class WebPImageFile(ImageFile.ImageFile): + format = "WEBP" + format_description = "WebP image" + __loaded = 0 + __logical_frame = 0 + + def _open(self) -> None: + assert self.fp is not None + s = self.fp.read() + if not _accept(s): + msg = "not a WEBP file" + raise SyntaxError(msg) + + # Use the newer AnimDecoder API to parse the (possibly) animated file, + # and access muxed chunks like ICC/EXIF/XMP. + self._decoder = _webp.WebPAnimDecoder(s) + + # Get info from decoder + self._size, self.info["loop"], bgcolor, self.n_frames, self.rawmode = ( + self._decoder.get_info() + ) + self.info["background"] = ( + (bgcolor >> 16) & 0xFF, # R + (bgcolor >> 8) & 0xFF, # G + bgcolor & 0xFF, # B + (bgcolor >> 24) & 0xFF, # A + ) + self.is_animated = self.n_frames > 1 + self._mode = "RGB" if self.rawmode == "RGBX" else self.rawmode + + # Attempt to read ICC / EXIF / XMP chunks from file + for key, chunk_name in { + "icc_profile": "ICCP", + "exif": "EXIF", + "xmp": "XMP ", + }.items(): + if value := self._decoder.get_chunk(chunk_name): + self.info[key] = value + + # Initialize seek state + self._reset(reset=False) + + def _getexif(self) -> dict[int, Any] | None: + if "exif" not in self.info: + return None + return self.getexif()._get_merged_dict() + + def seek(self, frame: int) -> None: + if not self._seek_check(frame): + return + + # Set logical frame to requested position + self.__logical_frame = frame + + def _reset(self, reset: bool = True) -> None: + if reset: + self._decoder.reset() + self.__physical_frame = 0 + self.__loaded = -1 + self.__timestamp = 0 + + def _get_next(self) -> tuple[bytes, int, int]: + # Get next frame + ret = self._decoder.get_next() + self.__physical_frame += 1 + + # Check if an error occurred + if ret is None: + self._reset() # Reset just to be safe + self.seek(0) + msg = "failed to decode next frame in WebP file" + raise EOFError(msg) + + # Compute duration + data, timestamp = ret + duration = timestamp - self.__timestamp + self.__timestamp = timestamp + + # libwebp gives frame end, adjust to start of frame + timestamp -= duration + return data, timestamp, duration + + def _seek(self, frame: int) -> None: + if self.__physical_frame == frame: + return # Nothing to do + if frame < self.__physical_frame: + self._reset() # Rewind to beginning + while self.__physical_frame < frame: + self._get_next() # Advance to the requested frame + + def load(self) -> Image.core.PixelAccess | None: + if self.__loaded != self.__logical_frame: + self._seek(self.__logical_frame) + + # We need to load the image data for this frame + data, self.info["timestamp"], self.info["duration"] = self._get_next() + self.__loaded = self.__logical_frame + + # Set tile + if self.fp and self._exclusive_fp: + self.fp.close() + self.fp = BytesIO(data) + self.tile = [ImageFile._Tile("raw", (0, 0) + self.size, 0, self.rawmode)] + + return super().load() + + def load_seek(self, pos: int) -> None: + pass + + def tell(self) -> int: + return self.__logical_frame + + +def _convert_frame(im: Image.Image) -> Image.Image: + # Make sure image mode is supported + if im.mode not in ("RGBX", "RGBA", "RGB"): + im = im.convert("RGBA" if im.has_transparency_data else "RGB") + return im + + +def _save_all(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + encoderinfo = im.encoderinfo.copy() + append_images = list(encoderinfo.get("append_images", [])) + + # If total frame count is 1, then save using the legacy API, which + # will preserve non-alpha modes + total = 0 + for ims in [im] + append_images: + total += getattr(ims, "n_frames", 1) + if total == 1: + _save(im, fp, filename) + return + + background: int | tuple[int, ...] = (0, 0, 0, 0) + if "background" in encoderinfo: + background = encoderinfo["background"] + elif "background" in im.info: + background = im.info["background"] + if isinstance(background, int): + # GifImagePlugin stores a global color table index in + # info["background"]. So it must be converted to an RGBA value + palette = im.getpalette() + if palette: + r, g, b = palette[background * 3 : (background + 1) * 3] + background = (r, g, b, 255) + else: + background = (background, background, background, 255) + + duration = im.encoderinfo.get("duration", im.info.get("duration", 0)) + loop = im.encoderinfo.get("loop", 0) + minimize_size = im.encoderinfo.get("minimize_size", False) + kmin = im.encoderinfo.get("kmin", None) + kmax = im.encoderinfo.get("kmax", None) + allow_mixed = im.encoderinfo.get("allow_mixed", False) + verbose = False + lossless = im.encoderinfo.get("lossless", False) + quality = im.encoderinfo.get("quality", 80) + alpha_quality = im.encoderinfo.get("alpha_quality", 100) + method = im.encoderinfo.get("method", 0) + icc_profile = im.encoderinfo.get("icc_profile") or "" + exif = im.encoderinfo.get("exif", "") + if isinstance(exif, Image.Exif): + exif = exif.tobytes() + xmp = im.encoderinfo.get("xmp", "") + if allow_mixed: + lossless = False + + # Sensible keyframe defaults are from gif2webp.c script + if kmin is None: + kmin = 9 if lossless else 3 + if kmax is None: + kmax = 17 if lossless else 5 + + # Validate background color + if ( + not isinstance(background, (list, tuple)) + or len(background) != 4 + or not all(0 <= v < 256 for v in background) + ): + msg = f"Background color is not an RGBA tuple clamped to (0-255): {background}" + raise OSError(msg) + + # Convert to packed uint + bg_r, bg_g, bg_b, bg_a = background + background = (bg_a << 24) | (bg_r << 16) | (bg_g << 8) | (bg_b << 0) + + # Setup the WebP animation encoder + enc = _webp.WebPAnimEncoder( + im.size, + background, + loop, + minimize_size, + kmin, + kmax, + allow_mixed, + verbose, + ) + + # Add each frame + frame_idx = 0 + timestamp = 0 + cur_idx = im.tell() + try: + for ims in [im] + append_images: + # Get number of frames in this image + nfr = getattr(ims, "n_frames", 1) + + for idx in range(nfr): + ims.seek(idx) + + frame = _convert_frame(ims) + + # Append the frame to the animation encoder + enc.add( + frame.getim(), + round(timestamp), + lossless, + quality, + alpha_quality, + method, + ) + + # Update timestamp and frame index + if isinstance(duration, (list, tuple)): + timestamp += duration[frame_idx] + else: + timestamp += duration + frame_idx += 1 + + finally: + im.seek(cur_idx) + + # Force encoder to flush frames + enc.add(None, round(timestamp), lossless, quality, alpha_quality, 0) + + # Get the final output from the encoder + data = enc.assemble(icc_profile, exif, xmp) + if data is None: + msg = "cannot write file as WebP (encoder returned None)" + raise OSError(msg) + + fp.write(data) + + +def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + lossless = im.encoderinfo.get("lossless", False) + quality = im.encoderinfo.get("quality", 80) + alpha_quality = im.encoderinfo.get("alpha_quality", 100) + icc_profile = im.encoderinfo.get("icc_profile") or "" + exif = im.encoderinfo.get("exif", b"") + if isinstance(exif, Image.Exif): + exif = exif.tobytes() + if exif.startswith(b"Exif\x00\x00"): + exif = exif[6:] + xmp = im.encoderinfo.get("xmp", "") + method = im.encoderinfo.get("method", 4) + exact = 1 if im.encoderinfo.get("exact") else 0 + + im = _convert_frame(im) + + data = _webp.WebPEncode( + im.getim(), + lossless, + float(quality), + float(alpha_quality), + icc_profile, + method, + exact, + exif, + xmp, + ) + if data is None: + msg = "cannot write file as WebP (encoder returned None)" + raise OSError(msg) + + fp.write(data) + + +Image.register_open(WebPImageFile.format, WebPImageFile, _accept) +if SUPPORTED: + Image.register_save(WebPImageFile.format, _save) + Image.register_save_all(WebPImageFile.format, _save_all) + Image.register_extension(WebPImageFile.format, ".webp") + Image.register_mime(WebPImageFile.format, "image/webp") diff --git a/.venv/lib/python3.11/site-packages/PIL/WmfImagePlugin.py b/.venv/lib/python3.11/site-packages/PIL/WmfImagePlugin.py new file mode 100644 index 0000000000000000000000000000000000000000..f5e244782fcc899194d3257bb89cd5bf66edc07c --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/WmfImagePlugin.py @@ -0,0 +1,183 @@ +# +# The Python Imaging Library +# $Id$ +# +# WMF stub codec +# +# history: +# 1996-12-14 fl Created +# 2004-02-22 fl Turned into a stub driver +# 2004-02-23 fl Added EMF support +# +# Copyright (c) Secret Labs AB 1997-2004. All rights reserved. +# Copyright (c) Fredrik Lundh 1996. +# +# See the README file for information on usage and redistribution. +# +# WMF/EMF reference documentation: +# https://winprotocoldoc.blob.core.windows.net/productionwindowsarchives/MS-WMF/[MS-WMF].pdf +# http://wvware.sourceforge.net/caolan/index.html +# http://wvware.sourceforge.net/caolan/ora-wmf.html +from __future__ import annotations + +from typing import IO + +from . import Image, ImageFile +from ._binary import i16le as word +from ._binary import si16le as short +from ._binary import si32le as _long + +_handler = None + + +def register_handler(handler: ImageFile.StubHandler | None) -> None: + """ + Install application-specific WMF image handler. + + :param handler: Handler object. + """ + global _handler + _handler = handler + + +if hasattr(Image.core, "drawwmf"): + # install default handler (windows only) + + class WmfHandler(ImageFile.StubHandler): + def open(self, im: ImageFile.StubImageFile) -> None: + self.bbox = im.info["wmf_bbox"] + + def load(self, im: ImageFile.StubImageFile) -> Image.Image: + assert im.fp is not None + im.fp.seek(0) # rewind + return Image.frombytes( + "RGB", + im.size, + Image.core.drawwmf(im.fp.read(), im.size, self.bbox), + "raw", + "BGR", + (im.size[0] * 3 + 3) & -4, + -1, + ) + + register_handler(WmfHandler()) + +# +# -------------------------------------------------------------------- +# Read WMF file + + +def _accept(prefix: bytes) -> bool: + return prefix.startswith((b"\xd7\xcd\xc6\x9a\x00\x00", b"\x01\x00\x00\x00")) + + +## +# Image plugin for Windows metafiles. + + +class WmfStubImageFile(ImageFile.StubImageFile): + format = "WMF" + format_description = "Windows Metafile" + + def _open(self) -> None: + # check placeable header + assert self.fp is not None + s = self.fp.read(44) + + if s.startswith(b"\xd7\xcd\xc6\x9a\x00\x00"): + # placeable windows metafile + + # get units per inch + inch = word(s, 14) + if inch == 0: + msg = "Invalid inch" + raise ValueError(msg) + self._inch: tuple[float, float] = inch, inch + + # get bounding box + x0 = short(s, 6) + y0 = short(s, 8) + x1 = short(s, 10) + y1 = short(s, 12) + + # normalize size to 72 dots per inch + self.info["dpi"] = 72 + size = ( + (x1 - x0) * self.info["dpi"] // inch, + (y1 - y0) * self.info["dpi"] // inch, + ) + + self.info["wmf_bbox"] = x0, y0, x1, y1 + + # sanity check (standard metafile header) + if s[22:26] != b"\x01\x00\t\x00": + msg = "Unsupported WMF file format" + raise SyntaxError(msg) + + elif s.startswith(b"\x01\x00\x00\x00") and s[40:44] == b" EMF": + # enhanced metafile + + # get bounding box + x0 = _long(s, 8) + y0 = _long(s, 12) + x1 = _long(s, 16) + y1 = _long(s, 20) + + # get frame (in 0.01 millimeter units) + frame = _long(s, 24), _long(s, 28), _long(s, 32), _long(s, 36) + + size = x1 - x0, y1 - y0 + + # calculate dots per inch from bbox and frame + xdpi = 2540.0 * (x1 - x0) / (frame[2] - frame[0]) + ydpi = 2540.0 * (y1 - y0) / (frame[3] - frame[1]) + + self.info["wmf_bbox"] = x0, y0, x1, y1 + + if xdpi == ydpi: + self.info["dpi"] = xdpi + else: + self.info["dpi"] = xdpi, ydpi + self._inch = xdpi, ydpi + + else: + msg = "Unsupported file format" + raise SyntaxError(msg) + + self._mode = "RGB" + self._size = size + + def _load(self) -> ImageFile.StubHandler | None: + return _handler + + def load( + self, dpi: float | tuple[float, float] | None = None + ) -> Image.core.PixelAccess | None: + if dpi is not None: + self.info["dpi"] = dpi + x0, y0, x1, y1 = self.info["wmf_bbox"] + if not isinstance(dpi, tuple): + dpi = dpi, dpi + self._size = ( + int((x1 - x0) * dpi[0] / self._inch[0]), + int((y1 - y0) * dpi[1] / self._inch[1]), + ) + return super().load() + + +def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + if _handler is None or not hasattr(_handler, "save"): + msg = "WMF save handler not installed" + raise OSError(msg) + _handler.save(im, fp, filename) + + +# +# -------------------------------------------------------------------- +# Registry stuff + + +Image.register_open(WmfStubImageFile.format, WmfStubImageFile, _accept) +Image.register_save(WmfStubImageFile.format, _save) + +Image.register_extensions(WmfStubImageFile.format, [".wmf", ".emf"]) diff --git a/.venv/lib/python3.11/site-packages/PIL/XVThumbImagePlugin.py b/.venv/lib/python3.11/site-packages/PIL/XVThumbImagePlugin.py new file mode 100644 index 0000000000000000000000000000000000000000..192c041d94edd900be6520be120df67d88eb7863 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/XVThumbImagePlugin.py @@ -0,0 +1,83 @@ +# +# The Python Imaging Library. +# $Id$ +# +# XV Thumbnail file handler by Charles E. "Gene" Cash +# (gcash@magicnet.net) +# +# see xvcolor.c and xvbrowse.c in the sources to John Bradley's XV, +# available from ftp://ftp.cis.upenn.edu/pub/xv/ +# +# history: +# 98-08-15 cec created (b/w only) +# 98-12-09 cec added color palette +# 98-12-28 fl added to PIL (with only a few very minor modifications) +# +# To do: +# FIXME: make save work (this requires quantization support) +# +from __future__ import annotations + +from . import Image, ImageFile, ImagePalette +from ._binary import o8 + +_MAGIC = b"P7 332" + +# standard color palette for thumbnails (RGB332) +PALETTE = b"" +for r in range(8): + for g in range(8): + for b in range(4): + PALETTE = PALETTE + ( + o8((r * 255) // 7) + o8((g * 255) // 7) + o8((b * 255) // 3) + ) + + +def _accept(prefix: bytes) -> bool: + return prefix.startswith(_MAGIC) + + +## +# Image plugin for XV thumbnail images. + + +class XVThumbImageFile(ImageFile.ImageFile): + format = "XVThumb" + format_description = "XV thumbnail image" + + def _open(self) -> None: + # check magic + assert self.fp is not None + + if not _accept(self.fp.read(6)): + msg = "not an XV thumbnail file" + raise SyntaxError(msg) + + # Skip to beginning of next line + self.fp.readline() + + # skip info comments + while True: + s = self.fp.readline() + if not s: + msg = "Unexpected EOF reading XV thumbnail file" + raise SyntaxError(msg) + if s[0] != 35: # ie. when not a comment: '#' + break + + # parse header line (already read) + w, h = s.strip().split(maxsplit=2)[:2] + + self._mode = "P" + self._size = int(w), int(h) + + self.palette = ImagePalette.raw("RGB", PALETTE) + + self.tile = [ + ImageFile._Tile("raw", (0, 0) + self.size, self.fp.tell(), self.mode) + ] + + +# -------------------------------------------------------------------- + +Image.register_open(XVThumbImageFile.format, XVThumbImageFile, _accept) diff --git a/.venv/lib/python3.11/site-packages/PIL/XbmImagePlugin.py b/.venv/lib/python3.11/site-packages/PIL/XbmImagePlugin.py new file mode 100644 index 0000000000000000000000000000000000000000..1e57aa162ea4f8618dac66cf042352f73d2199c8 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/XbmImagePlugin.py @@ -0,0 +1,98 @@ +# +# The Python Imaging Library. +# $Id$ +# +# XBM File handling +# +# History: +# 1995-09-08 fl Created +# 1996-11-01 fl Added save support +# 1997-07-07 fl Made header parser more tolerant +# 1997-07-22 fl Fixed yet another parser bug +# 2001-02-17 fl Use 're' instead of 'regex' (Python 2.1) (0.4) +# 2001-05-13 fl Added hotspot handling (based on code from Bernhard Herzog) +# 2004-02-24 fl Allow some whitespace before first #define +# +# Copyright (c) 1997-2004 by Secret Labs AB +# Copyright (c) 1996-1997 by Fredrik Lundh +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import re +from typing import IO + +from . import Image, ImageFile + +# XBM header +xbm_head = re.compile( + rb"\s*#define[ \t]+.*_width[ \t]+(?P[0-9]+)[\r\n]+" + b"#define[ \t]+.*_height[ \t]+(?P[0-9]+)[\r\n]+" + b"(?P" + b"#define[ \t]+[^_]*_x_hot[ \t]+(?P[0-9]+)[\r\n]+" + b"#define[ \t]+[^_]*_y_hot[ \t]+(?P[0-9]+)[\r\n]+" + b")?" + rb"[\000-\377]*_bits\[]" +) + + +def _accept(prefix: bytes) -> bool: + return prefix.lstrip().startswith(b"#define") + + +## +# Image plugin for X11 bitmaps. + + +class XbmImageFile(ImageFile.ImageFile): + format = "XBM" + format_description = "X11 Bitmap" + + def _open(self) -> None: + assert self.fp is not None + + m = xbm_head.match(self.fp.read(512)) + + if not m: + msg = "not a XBM file" + raise SyntaxError(msg) + + xsize = int(m.group("width")) + ysize = int(m.group("height")) + + if m.group("hotspot"): + self.info["hotspot"] = (int(m.group("xhot")), int(m.group("yhot"))) + + self._mode = "1" + self._size = xsize, ysize + + self.tile = [ImageFile._Tile("xbm", (0, 0) + self.size, m.end())] + + +def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: + if im.mode != "1": + msg = f"cannot write mode {im.mode} as XBM" + raise OSError(msg) + + fp.write(f"#define im_width {im.size[0]}\n".encode("ascii")) + fp.write(f"#define im_height {im.size[1]}\n".encode("ascii")) + + hotspot = im.encoderinfo.get("hotspot") + if hotspot: + fp.write(f"#define im_x_hot {hotspot[0]}\n".encode("ascii")) + fp.write(f"#define im_y_hot {hotspot[1]}\n".encode("ascii")) + + fp.write(b"static char im_bits[] = {\n") + + ImageFile._save(im, fp, [ImageFile._Tile("xbm", (0, 0) + im.size)]) + + fp.write(b"};\n") + + +Image.register_open(XbmImageFile.format, XbmImageFile, _accept) +Image.register_save(XbmImageFile.format, _save) + +Image.register_extension(XbmImageFile.format, ".xbm") + +Image.register_mime(XbmImageFile.format, "image/xbm") diff --git a/.venv/lib/python3.11/site-packages/PIL/XpmImagePlugin.py b/.venv/lib/python3.11/site-packages/PIL/XpmImagePlugin.py new file mode 100644 index 0000000000000000000000000000000000000000..80192f55e5345f2583bd9cdaaef131aa8fea0351 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/XpmImagePlugin.py @@ -0,0 +1,157 @@ +# +# The Python Imaging Library. +# $Id$ +# +# XPM File handling +# +# History: +# 1996-12-29 fl Created +# 2001-02-17 fl Use 're' instead of 'regex' (Python 2.1) (0.7) +# +# Copyright (c) Secret Labs AB 1997-2001. +# Copyright (c) Fredrik Lundh 1996-2001. +# +# See the README file for information on usage and redistribution. +# +from __future__ import annotations + +import re + +from . import Image, ImageFile, ImagePalette +from ._binary import o8 + +# XPM header +xpm_head = re.compile(b'"([0-9]*) ([0-9]*) ([0-9]*) ([0-9]*)') + + +def _accept(prefix: bytes) -> bool: + return prefix.startswith(b"/* XPM */") + + +## +# Image plugin for X11 pixel maps. + + +class XpmImageFile(ImageFile.ImageFile): + format = "XPM" + format_description = "X11 Pixel Map" + + def _open(self) -> None: + assert self.fp is not None + if not _accept(self.fp.read(9)): + msg = "not an XPM file" + raise SyntaxError(msg) + + # skip forward to next string + while True: + line = self.fp.readline() + if not line: + msg = "broken XPM file" + raise SyntaxError(msg) + m = xpm_head.match(line) + if m: + break + + self._size = int(m.group(1)), int(m.group(2)) + + palette_length = int(m.group(3)) + bpp = int(m.group(4)) + + # + # load palette description + + palette = {} + + for _ in range(palette_length): + line = self.fp.readline().rstrip() + + c = line[1 : bpp + 1] + s = line[bpp + 1 : -2].split() + + for i in range(0, len(s), 2): + if s[i] == b"c": + # process colour key + rgb = s[i + 1] + if rgb == b"None": + self.info["transparency"] = c + elif rgb.startswith(b"#"): + rgb_int = int(rgb[1:], 16) + palette[c] = ( + o8((rgb_int >> 16) & 255) + + o8((rgb_int >> 8) & 255) + + o8(rgb_int & 255) + ) + else: + # unknown colour + msg = "cannot read this XPM file" + raise ValueError(msg) + break + + else: + # missing colour key + msg = "cannot read this XPM file" + raise ValueError(msg) + + args: tuple[int, dict[bytes, bytes] | tuple[bytes, ...]] + if palette_length > 256: + self._mode = "RGB" + args = (bpp, palette) + else: + self._mode = "P" + self.palette = ImagePalette.raw("RGB", b"".join(palette.values())) + args = (bpp, tuple(palette.keys())) + + self.tile = [ImageFile._Tile("xpm", (0, 0) + self.size, self.fp.tell(), args)] + + def load_read(self, read_bytes: int) -> bytes: + # + # load all image data in one chunk + + xsize, ysize = self.size + + assert self.fp is not None + s = [self.fp.readline()[1 : xsize + 1].ljust(xsize) for i in range(ysize)] + + return b"".join(s) + + +class XpmDecoder(ImageFile.PyDecoder): + _pulls_fd = True + + def decode(self, buffer: Image.DecoderInput) -> tuple[int, int]: + assert self.fd is not None + + data = bytearray() + bpp, palette = self.args + dest_length = self.state.xsize * self.state.ysize + if self.mode == "RGB": + dest_length *= 3 + pixel_header = False + while len(data) < dest_length: + line = self.fd.readline() + if not line: + break + if line.rstrip() == b"/* pixels */" and not pixel_header: + pixel_header = True + continue + line = b'"'.join(line.split(b'"')[1:-1]) + for i in range(0, len(line), bpp): + key = line[i : i + bpp] + if self.mode == "RGB": + data += palette[key] + else: + data += o8(palette.index(key)) + self.set_as_raw(bytes(data)) + return -1, 0 + + +# +# Registry + + +Image.register_open(XpmImageFile.format, XpmImageFile, _accept) +Image.register_decoder("xpm", XpmDecoder) + +Image.register_extension(XpmImageFile.format, ".xpm") + +Image.register_mime(XpmImageFile.format, "image/xpm") diff --git a/.venv/lib/python3.11/site-packages/PIL/__init__.py b/.venv/lib/python3.11/site-packages/PIL/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..faf3e76e0ae13198dafe41bca9d2543abcbe92ae --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/__init__.py @@ -0,0 +1,87 @@ +"""Pillow (Fork of the Python Imaging Library) + +Pillow is the friendly PIL fork by Jeffrey 'Alex' Clark and contributors. + https://github.com/python-pillow/Pillow/ + +Pillow is forked from PIL 1.1.7. + +PIL is the Python Imaging Library by Fredrik Lundh and contributors. +Copyright (c) 1999 by Secret Labs AB. + +Use PIL.__version__ for this Pillow version. + +;-) +""" + +from __future__ import annotations + +from . import _version + +# VERSION was removed in Pillow 6.0.0. +# PILLOW_VERSION was removed in Pillow 9.0.0. +# Use __version__ instead. +__version__ = _version.__version__ +del _version + + +_plugins = [ + "AvifImagePlugin", + "BlpImagePlugin", + "BmpImagePlugin", + "BufrStubImagePlugin", + "CurImagePlugin", + "DcxImagePlugin", + "DdsImagePlugin", + "EpsImagePlugin", + "FitsImagePlugin", + "FliImagePlugin", + "FpxImagePlugin", + "FtexImagePlugin", + "GbrImagePlugin", + "GifImagePlugin", + "GribStubImagePlugin", + "Hdf5StubImagePlugin", + "IcnsImagePlugin", + "IcoImagePlugin", + "ImImagePlugin", + "ImtImagePlugin", + "IptcImagePlugin", + "JpegImagePlugin", + "Jpeg2KImagePlugin", + "McIdasImagePlugin", + "MicImagePlugin", + "MpegImagePlugin", + "MpoImagePlugin", + "MspImagePlugin", + "PalmImagePlugin", + "PcdImagePlugin", + "PcxImagePlugin", + "PdfImagePlugin", + "PixarImagePlugin", + "PngImagePlugin", + "PpmImagePlugin", + "PsdImagePlugin", + "QoiImagePlugin", + "SgiImagePlugin", + "SpiderImagePlugin", + "SunImagePlugin", + "TgaImagePlugin", + "TiffImagePlugin", + "WebPImagePlugin", + "WmfImagePlugin", + "XbmImagePlugin", + "XpmImagePlugin", + "XVThumbImagePlugin", +] + + +class UnidentifiedImageError(OSError): + """ + Raised in :py:meth:`PIL.Image.open` if an image cannot be opened and identified. + + If a PNG image raises this error, setting :data:`.ImageFile.LOAD_TRUNCATED_IMAGES` + to true may allow the image to be opened after all. The setting will ignore missing + data and checksum failures. + """ + + pass diff --git a/.venv/lib/python3.11/site-packages/PIL/__main__.py b/.venv/lib/python3.11/site-packages/PIL/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..043156e892dadc4fb1222b33f5eda33251cd15aa --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/__main__.py @@ -0,0 +1,7 @@ +from __future__ import annotations + +import sys + +from .features import pilinfo + +pilinfo(supported_formats="--report" not in sys.argv) diff --git a/.venv/lib/python3.11/site-packages/PIL/_avif.cpython-311-x86_64-linux-gnu.so b/.venv/lib/python3.11/site-packages/PIL/_avif.cpython-311-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..7c04429d5f30a23ed3524d48fdaeddf82231a6c5 Binary files /dev/null and b/.venv/lib/python3.11/site-packages/PIL/_avif.cpython-311-x86_64-linux-gnu.so differ diff --git a/.venv/lib/python3.11/site-packages/PIL/_avif.pyi b/.venv/lib/python3.11/site-packages/PIL/_avif.pyi new file mode 100644 index 0000000000000000000000000000000000000000..e27843e5338213713e26973127c738c14313ff98 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/_avif.pyi @@ -0,0 +1,3 @@ +from typing import Any + +def __getattr__(name: str) -> Any: ... diff --git a/.venv/lib/python3.11/site-packages/PIL/_binary.py b/.venv/lib/python3.11/site-packages/PIL/_binary.py new file mode 100644 index 0000000000000000000000000000000000000000..d3236c17abbe00ef3062675306fdd44f6ba3cecf --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/_binary.py @@ -0,0 +1,113 @@ +# +# The Python Imaging Library. +# $Id$ +# +# Binary input/output support routines. +# +# Copyright (c) 1997-2003 by Secret Labs AB +# Copyright (c) 1995-2003 by Fredrik Lundh +# Copyright (c) 2012 by Brian Crowell +# +# See the README file for information on usage and redistribution. +# + + +"""Binary input/output support routines.""" + +from __future__ import annotations + +from struct import pack, unpack_from + + +def i8(c: bytes) -> int: + return c[0] + + +def o8(i: int) -> bytes: + return bytes((i & 255,)) + + +# Input, le = little endian, be = big endian +def i16le(c: bytes, o: int = 0) -> int: + """ + Converts a 2-bytes (16 bits) string to an unsigned integer. + + :param c: string containing bytes to convert + :param o: offset of bytes to convert in string + """ + return unpack_from(" int: + """ + Converts a 2-bytes (16 bits) string to a signed integer. + + :param c: string containing bytes to convert + :param o: offset of bytes to convert in string + """ + return unpack_from(" int: + """ + Converts a 2-bytes (16 bits) string to a signed integer, big endian. + + :param c: string containing bytes to convert + :param o: offset of bytes to convert in string + """ + return unpack_from(">h", c, o)[0] + + +def i32le(c: bytes, o: int = 0) -> int: + """ + Converts a 4-bytes (32 bits) string to an unsigned integer. + + :param c: string containing bytes to convert + :param o: offset of bytes to convert in string + """ + return unpack_from(" int: + """ + Converts a 4-bytes (32 bits) string to a signed integer. + + :param c: string containing bytes to convert + :param o: offset of bytes to convert in string + """ + return unpack_from(" int: + """ + Converts a 4-bytes (32 bits) string to a signed integer, big endian. + + :param c: string containing bytes to convert + :param o: offset of bytes to convert in string + """ + return unpack_from(">i", c, o)[0] + + +def i16be(c: bytes, o: int = 0) -> int: + return unpack_from(">H", c, o)[0] + + +def i32be(c: bytes, o: int = 0) -> int: + return unpack_from(">I", c, o)[0] + + +# Output, le = little endian, be = big endian +def o16le(i: int) -> bytes: + return pack(" bytes: + return pack(" bytes: + return pack(">H", i) + + +def o32be(i: int) -> bytes: + return pack(">I", i) diff --git a/.venv/lib/python3.11/site-packages/PIL/_deprecate.py b/.venv/lib/python3.11/site-packages/PIL/_deprecate.py new file mode 100644 index 0000000000000000000000000000000000000000..711c62ab2b1e15fcae8ecc2529d74a66df74bac6 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/_deprecate.py @@ -0,0 +1,72 @@ +from __future__ import annotations + +import warnings + +from . import __version__ + + +def deprecate( + deprecated: str, + when: int | None, + replacement: str | None = None, + *, + action: str | None = None, + plural: bool = False, + stacklevel: int = 3, +) -> None: + """ + Deprecations helper. + + :param deprecated: Name of thing to be deprecated. + :param when: Pillow major version to be removed in. + :param replacement: Name of replacement. + :param action: Instead of "replacement", give a custom call to action + e.g. "Upgrade to new thing". + :param plural: if the deprecated thing is plural, needing "are" instead of "is". + + Usually of the form: + + "[deprecated] is deprecated and will be removed in Pillow [when] (yyyy-mm-dd). + Use [replacement] instead." + + You can leave out the replacement sentence: + + "[deprecated] is deprecated and will be removed in Pillow [when] (yyyy-mm-dd)" + + Or with another call to action: + + "[deprecated] is deprecated and will be removed in Pillow [when] (yyyy-mm-dd). + [action]." + """ + + is_ = "are" if plural else "is" + + if when is None: + removed = "a future version" + elif when <= int(__version__.split(".")[0]): + msg = f"{deprecated} {is_} deprecated and should be removed." + raise RuntimeError(msg) + elif when == 13: + removed = "Pillow 13 (2026-10-15)" + elif when == 14: + removed = "Pillow 14 (2027-10-15)" + else: + msg = f"Unknown removal version: {when}. Update {__name__}?" + raise ValueError(msg) + + if replacement and action: + msg = "Use only one of 'replacement' and 'action'" + raise ValueError(msg) + + if replacement: + action = f". Use {replacement} instead." + elif action: + action = f". {action.rstrip('.')}." + else: + action = "" + + warnings.warn( + f"{deprecated} {is_} deprecated and will be removed in {removed}{action}", + DeprecationWarning, + stacklevel=stacklevel, + ) diff --git a/.venv/lib/python3.11/site-packages/PIL/_imaging.cpython-311-x86_64-linux-gnu.so b/.venv/lib/python3.11/site-packages/PIL/_imaging.cpython-311-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..a57479667152f83828d84a67b5f01b28c01bdad9 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/_imaging.cpython-311-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b55dc49c50e6bad027caa57e6d0f7d7e793993e4693cd8d80cec38dc102790ff +size 3385961 diff --git a/.venv/lib/python3.11/site-packages/PIL/_imaging.pyi b/.venv/lib/python3.11/site-packages/PIL/_imaging.pyi new file mode 100644 index 0000000000000000000000000000000000000000..81028a5960ae34ec74285c456d9b691dc6a67a93 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/_imaging.pyi @@ -0,0 +1,31 @@ +from typing import Any + +class ImagingCore: + def __getitem__(self, index: int) -> float | tuple[int, ...] | None: ... + def __getattr__(self, name: str) -> Any: ... + +class ImagingFont: + def __getattr__(self, name: str) -> Any: ... + +class ImagingDraw: + def __getattr__(self, name: str) -> Any: ... + +class PixelAccess: + def __getitem__(self, xy: tuple[int, int]) -> float | tuple[int, ...]: ... + def __setitem__( + self, xy: tuple[int, int], color: float | tuple[int, ...] + ) -> None: ... + +class ImagingDecoder: + def __getattr__(self, name: str) -> Any: ... + +class ImagingEncoder: + def __getattr__(self, name: str) -> Any: ... + +class _Outline: + def close(self) -> None: ... + def __getattr__(self, name: str) -> Any: ... + +def font(image: ImagingCore, glyphdata: bytes) -> ImagingFont: ... +def outline() -> _Outline: ... +def __getattr__(name: str) -> Any: ... diff --git a/.venv/lib/python3.11/site-packages/PIL/_imagingcms.cpython-311-x86_64-linux-gnu.so b/.venv/lib/python3.11/site-packages/PIL/_imagingcms.cpython-311-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..9c2d51bfa0efd0629d8e3ca630d0740cbd9c9e7d --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/_imagingcms.cpython-311-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c06d0f4e91a6d0f0b162a6798849c8692dae1a222bf4b4b67f546a4696af21ff +size 157841 diff --git a/.venv/lib/python3.11/site-packages/PIL/_imagingcms.pyi b/.venv/lib/python3.11/site-packages/PIL/_imagingcms.pyi new file mode 100644 index 0000000000000000000000000000000000000000..4fc0d60ab79375281abb6d53d9d707cf18f09815 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/_imagingcms.pyi @@ -0,0 +1,143 @@ +import datetime +import sys +from typing import Literal, SupportsFloat, TypeAlias, TypedDict + +from ._typing import CapsuleType + +littlecms_version: str | None + +_Tuple3f: TypeAlias = tuple[float, float, float] +_Tuple2x3f: TypeAlias = tuple[_Tuple3f, _Tuple3f] +_Tuple3x3f: TypeAlias = tuple[_Tuple3f, _Tuple3f, _Tuple3f] + +class _IccMeasurementCondition(TypedDict): + observer: int + backing: _Tuple3f + geo: str + flare: float + illuminant_type: str + +class _IccViewingCondition(TypedDict): + illuminant: _Tuple3f + surround: _Tuple3f + illuminant_type: str + +class CmsProfile: + @property + def rendering_intent(self) -> int: ... + @property + def creation_date(self) -> datetime.datetime | None: ... + @property + def copyright(self) -> str | None: ... + @property + def target(self) -> str | None: ... + @property + def manufacturer(self) -> str | None: ... + @property + def model(self) -> str | None: ... + @property + def profile_description(self) -> str | None: ... + @property + def screening_description(self) -> str | None: ... + @property + def viewing_condition(self) -> str | None: ... + @property + def version(self) -> float: ... + @property + def icc_version(self) -> int: ... + @property + def attributes(self) -> int: ... + @property + def header_flags(self) -> int: ... + @property + def header_manufacturer(self) -> str: ... + @property + def header_model(self) -> str: ... + @property + def device_class(self) -> str: ... + @property + def connection_space(self) -> str: ... + @property + def xcolor_space(self) -> str: ... + @property + def profile_id(self) -> bytes: ... + @property + def is_matrix_shaper(self) -> bool: ... + @property + def technology(self) -> str | None: ... + @property + def colorimetric_intent(self) -> str | None: ... + @property + def perceptual_rendering_intent_gamut(self) -> str | None: ... + @property + def saturation_rendering_intent_gamut(self) -> str | None: ... + @property + def red_colorant(self) -> _Tuple2x3f | None: ... + @property + def green_colorant(self) -> _Tuple2x3f | None: ... + @property + def blue_colorant(self) -> _Tuple2x3f | None: ... + @property + def red_primary(self) -> _Tuple2x3f | None: ... + @property + def green_primary(self) -> _Tuple2x3f | None: ... + @property + def blue_primary(self) -> _Tuple2x3f | None: ... + @property + def media_white_point_temperature(self) -> float | None: ... + @property + def media_white_point(self) -> _Tuple2x3f | None: ... + @property + def media_black_point(self) -> _Tuple2x3f | None: ... + @property + def luminance(self) -> _Tuple2x3f | None: ... + @property + def chromatic_adaptation(self) -> tuple[_Tuple3x3f, _Tuple3x3f] | None: ... + @property + def chromaticity(self) -> _Tuple3x3f | None: ... + @property + def colorant_table(self) -> list[str] | None: ... + @property + def colorant_table_out(self) -> list[str] | None: ... + @property + def intent_supported(self) -> dict[int, tuple[bool, bool, bool]] | None: ... + @property + def clut(self) -> dict[int, tuple[bool, bool, bool]] | None: ... + @property + def icc_measurement_condition(self) -> _IccMeasurementCondition | None: ... + @property + def icc_viewing_condition(self) -> _IccViewingCondition | None: ... + def is_intent_supported(self, intent: int, direction: int, /) -> int: ... + +class CmsTransform: + def apply(self, id_in: CapsuleType, id_out: CapsuleType) -> int: ... + +def profile_open(profile: str, /) -> CmsProfile: ... +def profile_frombytes(profile: bytes, /) -> CmsProfile: ... +def profile_tobytes(profile: CmsProfile, /) -> bytes: ... +def buildTransform( + input_profile: CmsProfile, + output_profile: CmsProfile, + in_mode: str, + out_mode: str, + rendering_intent: int = 0, + cms_flags: int = 0, + /, +) -> CmsTransform: ... +def buildProofTransform( + input_profile: CmsProfile, + output_profile: CmsProfile, + proof_profile: CmsProfile, + in_mode: str, + out_mode: str, + rendering_intent: int = 0, + proof_intent: int = 0, + cms_flags: int = 0, + /, +) -> CmsTransform: ... +def createProfile( + color_space: Literal["LAB", "XYZ", "sRGB"], color_temp: SupportsFloat = 0.0, / +) -> CmsProfile: ... + +if sys.platform == "win32": + def get_display_profile_win32(handle: int = 0, is_dc: int = 0, /) -> str | None: ... diff --git a/.venv/lib/python3.11/site-packages/PIL/_imagingft.cpython-311-x86_64-linux-gnu.so b/.venv/lib/python3.11/site-packages/PIL/_imagingft.cpython-311-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..68ad7d6314ca11ccbb112e6ceede6d9704396b26 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/_imagingft.cpython-311-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8f7f03397dd21518ed13f4322b7461be44c867459f539e6f0759f8c282995cbb +size 322969 diff --git a/.venv/lib/python3.11/site-packages/PIL/_imagingft.pyi b/.venv/lib/python3.11/site-packages/PIL/_imagingft.pyi new file mode 100644 index 0000000000000000000000000000000000000000..2136810ba6a95e0c025a71cf7fbbc5b60490fed7 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/_imagingft.pyi @@ -0,0 +1,70 @@ +from collections.abc import Callable +from typing import Any + +from . import ImageFont, _imaging + +class Font: + @property + def family(self) -> str | None: ... + @property + def style(self) -> str | None: ... + @property + def ascent(self) -> int: ... + @property + def descent(self) -> int: ... + @property + def height(self) -> int: ... + @property + def x_ppem(self) -> int: ... + @property + def y_ppem(self) -> int: ... + @property + def glyphs(self) -> int: ... + def render( + self, + string: str | bytes, + fill: Callable[[int, int], _imaging.ImagingCore], + mode: str, + dir: str | None, + features: list[str] | None, + lang: str | None, + stroke_width: float, + stroke_filled: bool, + anchor: str | None, + foreground_ink_long: int, + start: tuple[float, float], + /, + ) -> tuple[_imaging.ImagingCore, tuple[int, int]]: ... + def getsize( + self, + string: str | bytes | bytearray, + mode: str, + dir: str | None, + features: list[str] | None, + lang: str | None, + anchor: str | None, + /, + ) -> tuple[tuple[int, int], tuple[int, int]]: ... + def getlength( + self, + string: str | bytes, + mode: str, + dir: str | None, + features: list[str] | None, + lang: str | None, + /, + ) -> float: ... + def getvarnames(self) -> list[bytes]: ... + def getvaraxes(self) -> list[ImageFont.Axis]: ... + def setvarname(self, instance_index: int, /) -> None: ... + def setvaraxes(self, axes: list[float], /) -> None: ... + +def getfont( + filename: str | bytes, + size: float, + index: int, + encoding: str, + font_bytes: bytes, + layout_engine: int, +) -> Font: ... +def __getattr__(name: str) -> Any: ... diff --git a/.venv/lib/python3.11/site-packages/PIL/_imagingmath.cpython-311-x86_64-linux-gnu.so b/.venv/lib/python3.11/site-packages/PIL/_imagingmath.cpython-311-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..b7e25f8f0794f397ef17d0ef21976c81b466ce4d --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/_imagingmath.cpython-311-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e0d3cf5254e69defb13ac124a48e580aa8e746388a6a59b8f0cb78215ecba099 +size 137496 diff --git a/.venv/lib/python3.11/site-packages/PIL/_imagingmath.pyi b/.venv/lib/python3.11/site-packages/PIL/_imagingmath.pyi new file mode 100644 index 0000000000000000000000000000000000000000..e27843e5338213713e26973127c738c14313ff98 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/_imagingmath.pyi @@ -0,0 +1,3 @@ +from typing import Any + +def __getattr__(name: str) -> Any: ... diff --git a/.venv/lib/python3.11/site-packages/PIL/_imagingmorph.cpython-311-x86_64-linux-gnu.so b/.venv/lib/python3.11/site-packages/PIL/_imagingmorph.cpython-311-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..5a540fb85ce3efa48210d52a0111281f3ac6a5b4 Binary files /dev/null and b/.venv/lib/python3.11/site-packages/PIL/_imagingmorph.cpython-311-x86_64-linux-gnu.so differ diff --git a/.venv/lib/python3.11/site-packages/PIL/_imagingmorph.pyi b/.venv/lib/python3.11/site-packages/PIL/_imagingmorph.pyi new file mode 100644 index 0000000000000000000000000000000000000000..e27843e5338213713e26973127c738c14313ff98 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/_imagingmorph.pyi @@ -0,0 +1,3 @@ +from typing import Any + +def __getattr__(name: str) -> Any: ... diff --git a/.venv/lib/python3.11/site-packages/PIL/_imagingtk.cpython-311-x86_64-linux-gnu.so b/.venv/lib/python3.11/site-packages/PIL/_imagingtk.cpython-311-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..8bd49eb5ead92a1c9689353fc0c1c257511329a6 Binary files /dev/null and b/.venv/lib/python3.11/site-packages/PIL/_imagingtk.cpython-311-x86_64-linux-gnu.so differ diff --git a/.venv/lib/python3.11/site-packages/PIL/_imagingtk.pyi b/.venv/lib/python3.11/site-packages/PIL/_imagingtk.pyi new file mode 100644 index 0000000000000000000000000000000000000000..e27843e5338213713e26973127c738c14313ff98 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/_imagingtk.pyi @@ -0,0 +1,3 @@ +from typing import Any + +def __getattr__(name: str) -> Any: ... diff --git a/.venv/lib/python3.11/site-packages/PIL/_tkinter_finder.py b/.venv/lib/python3.11/site-packages/PIL/_tkinter_finder.py new file mode 100644 index 0000000000000000000000000000000000000000..9c0143003a7320dd475cfcd168168b82e4f64964 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/_tkinter_finder.py @@ -0,0 +1,20 @@ +"""Find compiled module linking to Tcl / Tk libraries""" + +from __future__ import annotations + +import sys +import tkinter + +tk = getattr(tkinter, "_tkinter") + +try: + if hasattr(sys, "pypy_find_executable"): + TKINTER_LIB = tk.tklib_cffi.__file__ + else: + TKINTER_LIB = tk.__file__ +except AttributeError: + # _tkinter may be compiled directly into Python, in which case __file__ is + # not available. load_tkinter_funcs will check the binary first in any case. + TKINTER_LIB = None + +tk_version = str(tkinter.TkVersion) diff --git a/.venv/lib/python3.11/site-packages/PIL/_typing.py b/.venv/lib/python3.11/site-packages/PIL/_typing.py new file mode 100644 index 0000000000000000000000000000000000000000..a941f89806faabe61486fc164d8bd3f60fb48626 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/_typing.py @@ -0,0 +1,45 @@ +from __future__ import annotations + +import os +import sys +from collections.abc import Sequence +from typing import Any, Protocol, TypeVar + +TYPE_CHECKING = False +if TYPE_CHECKING: + from numbers import _IntegralLike as IntegralLike + + try: + import numpy.typing as npt + + NumpyArray = npt.NDArray[Any] + except ImportError: + pass + +if sys.version_info >= (3, 13): + from types import CapsuleType +else: + CapsuleType = object + +if sys.version_info >= (3, 12): + from collections.abc import Buffer +else: + Buffer = Any + + +_Ink = float | tuple[int, ...] | str + +Coords = Sequence[float] | Sequence[Sequence[float]] + + +_T_co = TypeVar("_T_co", covariant=True) + + +class SupportsRead(Protocol[_T_co]): + def read(self, length: int = ..., /) -> _T_co: ... + + +StrOrBytesPath = str | bytes | os.PathLike[str] | os.PathLike[bytes] + + +__all__ = ["Buffer", "IntegralLike", "StrOrBytesPath", "SupportsRead"] diff --git a/.venv/lib/python3.11/site-packages/PIL/_util.py b/.venv/lib/python3.11/site-packages/PIL/_util.py new file mode 100644 index 0000000000000000000000000000000000000000..b1fa6a0f39ed2847723f20fc81462adc9245d970 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/_util.py @@ -0,0 +1,29 @@ +from __future__ import annotations + +import os + +TYPE_CHECKING = False +if TYPE_CHECKING: + from typing import Any, NoReturn, TypeGuard + + from ._typing import StrOrBytesPath + + +def is_path(f: Any) -> TypeGuard[StrOrBytesPath]: + return isinstance(f, (bytes, str, os.PathLike)) + + +class DeferredError: + def __init__(self, ex: BaseException): + self.ex = ex + + def __getattr__(self, elt: str) -> NoReturn: + raise self.ex + + @staticmethod + def new(ex: BaseException) -> Any: + """ + Creates an object that raises the wrapped exception ``ex`` when used, + and casts it to :py:obj:`~typing.Any` type. + """ + return DeferredError(ex) diff --git a/.venv/lib/python3.11/site-packages/PIL/_version.py b/.venv/lib/python3.11/site-packages/PIL/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..6a8a6f65edfc11a017786b6611d56e8a5cddcd48 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/_version.py @@ -0,0 +1,4 @@ +# Master version for Pillow +from __future__ import annotations + +__version__ = "12.3.0" diff --git a/.venv/lib/python3.11/site-packages/PIL/_webp.cpython-311-x86_64-linux-gnu.so b/.venv/lib/python3.11/site-packages/PIL/_webp.cpython-311-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..f88130763e268c673724608c7e18fcde618fc2e1 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/_webp.cpython-311-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:aff629f5b1a9143958126b163c21854fc3ae76faea2793fe562a2a975f75cb16 +size 108849 diff --git a/.venv/lib/python3.11/site-packages/PIL/_webp.pyi b/.venv/lib/python3.11/site-packages/PIL/_webp.pyi new file mode 100644 index 0000000000000000000000000000000000000000..e27843e5338213713e26973127c738c14313ff98 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/_webp.pyi @@ -0,0 +1,3 @@ +from typing import Any + +def __getattr__(name: str) -> Any: ... diff --git a/.venv/lib/python3.11/site-packages/PIL/features.py b/.venv/lib/python3.11/site-packages/PIL/features.py new file mode 100644 index 0000000000000000000000000000000000000000..ff32c2510453aebb44a0b60d52db29d4718acee6 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/features.py @@ -0,0 +1,343 @@ +from __future__ import annotations + +import collections +import os +import sys +import warnings +from typing import IO + +import PIL + +from . import Image + +modules = { + "pil": ("PIL._imaging", "PILLOW_VERSION"), + "tkinter": ("PIL._tkinter_finder", "tk_version"), + "freetype2": ("PIL._imagingft", "freetype2_version"), + "littlecms2": ("PIL._imagingcms", "littlecms_version"), + "webp": ("PIL._webp", "webpdecoder_version"), + "avif": ("PIL._avif", "libavif_version"), +} + + +def check_module(feature: str) -> bool: + """ + Checks if a module is available. + + :param feature: The module to check for. + :returns: ``True`` if available, ``False`` otherwise. + :raises ValueError: If the module is not defined in this version of Pillow. + """ + if feature not in modules: + msg = f"Unknown module {feature}" + raise ValueError(msg) + + module, ver = modules[feature] + + try: + __import__(module) + return True + except ModuleNotFoundError: + return False + except ImportError as ex: + warnings.warn(str(ex)) + return False + + +def version_module(feature: str) -> str | None: + """ + :param feature: The module to check for. + :returns: + The loaded version number as a string, or ``None`` if unknown or not available. + :raises ValueError: If the module is not defined in this version of Pillow. + """ + if not check_module(feature): + return None + + module, ver = modules[feature] + + return getattr(__import__(module, fromlist=[ver]), ver) + + +def get_supported_modules() -> list[str]: + """ + :returns: A list of all supported modules. + """ + return [f for f in modules if check_module(f)] + + +codecs = { + "jpg": ("jpeg", "jpeglib"), + "jpg_2000": ("jpeg2k", "jp2klib"), + "zlib": ("zip", "zlib"), + "libtiff": ("libtiff", "libtiff"), +} + + +def check_codec(feature: str) -> bool: + """ + Checks if a codec is available. + + :param feature: The codec to check for. + :returns: ``True`` if available, ``False`` otherwise. + :raises ValueError: If the codec is not defined in this version of Pillow. + """ + if feature not in codecs: + msg = f"Unknown codec {feature}" + raise ValueError(msg) + + codec, lib = codecs[feature] + + return f"{codec}_encoder" in dir(Image.core) + + +def version_codec(feature: str) -> str | None: + """ + :param feature: The codec to check for. + :returns: + The version number as a string, or ``None`` if not available. + Checked at compile time for ``jpg``, run-time otherwise. + :raises ValueError: If the codec is not defined in this version of Pillow. + """ + if not check_codec(feature): + return None + + codec, lib = codecs[feature] + + version = getattr(Image.core, f"{lib}_version") + + if feature == "libtiff": + return version.split("\n")[0].split("Version ")[1] + + return version + + +def get_supported_codecs() -> list[str]: + """ + :returns: A list of all supported codecs. + """ + return [f for f in codecs if check_codec(f)] + + +features: dict[str, tuple[str, str, str | None]] = { + "raqm": ("PIL._imagingft", "HAVE_RAQM", "raqm_version"), + "fribidi": ("PIL._imagingft", "HAVE_FRIBIDI", "fribidi_version"), + "harfbuzz": ("PIL._imagingft", "HAVE_HARFBUZZ", "harfbuzz_version"), + "libjpeg_turbo": ("PIL._imaging", "HAVE_LIBJPEGTURBO", "libjpeg_turbo_version"), + "mozjpeg": ("PIL._imaging", "HAVE_MOZJPEG", "libjpeg_turbo_version"), + "zlib_ng": ("PIL._imaging", "HAVE_ZLIBNG", "zlib_ng_version"), + "libimagequant": ("PIL._imaging", "HAVE_LIBIMAGEQUANT", "imagequant_version"), + "xcb": ("PIL._imaging", "HAVE_XCB", None), +} + + +def check_feature(feature: str) -> bool | None: + """ + Checks if a feature is available. + + :param feature: The feature to check for. + :returns: ``True`` if available, ``False`` if unavailable, ``None`` if unknown. + :raises ValueError: If the feature is not defined in this version of Pillow. + """ + if feature not in features: + msg = f"Unknown feature {feature}" + raise ValueError(msg) + + module, flag, ver = features[feature] + + try: + imported_module = __import__(module, fromlist=["PIL"]) + return getattr(imported_module, flag) + except ModuleNotFoundError: + return None + except ImportError as ex: + warnings.warn(str(ex)) + return None + + +def version_feature(feature: str) -> str | None: + """ + :param feature: The feature to check for. + :returns: The version number as a string, or ``None`` if not available. + :raises ValueError: If the feature is not defined in this version of Pillow. + """ + if not check_feature(feature): + return None + + module, flag, ver = features[feature] + + if ver is None: + return None + + return getattr(__import__(module, fromlist=[ver]), ver) + + +def get_supported_features() -> list[str]: + """ + :returns: A list of all supported features. + """ + return [f for f in features if check_feature(f)] + + +def check(feature: str) -> bool | None: + """ + :param feature: A module, codec, or feature name. + :returns: + ``True`` if the module, codec, or feature is available, + ``False`` or ``None`` otherwise. + """ + + if feature in modules: + return check_module(feature) + if feature in codecs: + return check_codec(feature) + if feature in features: + return check_feature(feature) + warnings.warn(f"Unknown feature '{feature}'.", stacklevel=2) + return False + + +def version(feature: str) -> str | None: + """ + :param feature: + The module, codec, or feature to check for. + :returns: + The version number as a string, or ``None`` if unknown or not available. + """ + if feature in modules: + return version_module(feature) + if feature in codecs: + return version_codec(feature) + if feature in features: + return version_feature(feature) + return None + + +def get_supported() -> list[str]: + """ + :returns: A list of all supported modules, features, and codecs. + """ + + ret = get_supported_modules() + ret.extend(get_supported_features()) + ret.extend(get_supported_codecs()) + return ret + + +def pilinfo(out: IO[str] | None = None, supported_formats: bool = True) -> None: + """ + Prints information about this installation of Pillow. + This function can be called with ``python3 -m PIL``. + It can also be called with ``python3 -m PIL.report`` or ``python3 -m PIL --report`` + to have "supported_formats" set to ``False``, omitting the list of all supported + image file formats. + + :param out: + The output stream to print to. Defaults to ``sys.stdout`` if ``None``. + :param supported_formats: + If ``True``, a list of all supported image file formats will be printed. + """ + + if out is None: + out = sys.stdout + + Image.init() + + print("-" * 68, file=out) + print(f"Pillow {PIL.__version__}", file=out) + py_version_lines = sys.version.splitlines() + print(f"Python {py_version_lines[0].strip()}", file=out) + for py_version in py_version_lines[1:]: + print(f" {py_version.strip()}", file=out) + print("-" * 68, file=out) + print(f"Python executable is {sys.executable or 'unknown'}", file=out) + if sys.prefix != sys.base_prefix: + print(f"Environment Python files loaded from {sys.prefix}", file=out) + print(f"System Python files loaded from {sys.base_prefix}", file=out) + print("-" * 68, file=out) + print( + f"Python Pillow modules loaded from {os.path.dirname(Image.__file__)}", + file=out, + ) + print( + f"Binary Pillow modules loaded from {os.path.dirname(Image.core.__file__)}", + file=out, + ) + print("-" * 68, file=out) + + for name, feature in [ + ("pil", "PIL CORE"), + ("tkinter", "TKINTER"), + ("freetype2", "FREETYPE2"), + ("littlecms2", "LITTLECMS2"), + ("webp", "WEBP"), + ("avif", "AVIF"), + ("jpg", "JPEG"), + ("jpg_2000", "OPENJPEG (JPEG2000)"), + ("zlib", "ZLIB (PNG/ZIP)"), + ("libtiff", "LIBTIFF"), + ("raqm", "RAQM (Bidirectional Text)"), + ("libimagequant", "LIBIMAGEQUANT (Quantization method)"), + ("xcb", "XCB (X protocol)"), + ]: + if check(name): + v: str | None = None + if name == "jpg": + libjpeg_turbo_version = version_feature("libjpeg_turbo") + if libjpeg_turbo_version is not None: + v = "mozjpeg" if check_feature("mozjpeg") else "libjpeg-turbo" + v += " " + libjpeg_turbo_version + if v is None: + v = version(name) + if v is not None: + version_static = name in ("pil", "jpg") + if name == "littlecms2": + # this check is also in src/_imagingcms.c:setup_module() + version_static = tuple(int(x) for x in v.split(".")) < (2, 7) + t = "compiled for" if version_static else "loaded" + if name == "zlib": + zlib_ng_version = version_feature("zlib_ng") + if zlib_ng_version is not None: + v += ", compiled for zlib-ng " + zlib_ng_version + elif name == "raqm": + for f in ("fribidi", "harfbuzz"): + v2 = version_feature(f) + if v2 is not None: + v += f", {f} {v2}" + print("---", feature, "support ok,", t, v, file=out) + else: + print("---", feature, "support ok", file=out) + else: + print("***", feature, "support not installed", file=out) + print("-" * 68, file=out) + + if supported_formats: + extensions = collections.defaultdict(list) + for ext, i in Image.EXTENSION.items(): + extensions[i].append(ext) + + for i in sorted(Image.ID): + line = f"{i}" + if i in Image.MIME: + line = f"{line} {Image.MIME[i]}" + print(line, file=out) + + if i in extensions: + print( + "Extensions: {}".format(", ".join(sorted(extensions[i]))), file=out + ) + + features = [] + if i in Image.OPEN: + features.append("open") + if i in Image.SAVE: + features.append("save") + if i in Image.SAVE_ALL: + features.append("save_all") + if i in Image.DECODERS: + features.append("decode") + if i in Image.ENCODERS: + features.append("encode") + + print("Features: {}".format(", ".join(features)), file=out) + print("-" * 68, file=out) diff --git a/.venv/lib/python3.11/site-packages/PIL/py.typed b/.venv/lib/python3.11/site-packages/PIL/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.11/site-packages/PIL/report.py b/.venv/lib/python3.11/site-packages/PIL/report.py new file mode 100644 index 0000000000000000000000000000000000000000..d2815e8455e2ead803de4417314987ce7e9b7598 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/PIL/report.py @@ -0,0 +1,5 @@ +from __future__ import annotations + +from .features import pilinfo + +pilinfo(supported_formats=False) diff --git a/.venv/lib/python3.11/site-packages/__pycache__/_virtualenv.cpython-311.pyc b/.venv/lib/python3.11/site-packages/__pycache__/_virtualenv.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..44e802327d095adc553a96db0cf6f4d3c6e1c1c4 Binary files /dev/null and b/.venv/lib/python3.11/site-packages/__pycache__/_virtualenv.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/__pycache__/six.cpython-311.pyc b/.venv/lib/python3.11/site-packages/__pycache__/six.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ecdf5f0c222a81687e063fcfe4d6f9b7e40e8fc Binary files /dev/null and b/.venv/lib/python3.11/site-packages/__pycache__/six.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/__pycache__/typing_extensions.cpython-311.pyc b/.venv/lib/python3.11/site-packages/__pycache__/typing_extensions.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b8c17782d80757485a2975350fd73e695d2b272c --- /dev/null +++ b/.venv/lib/python3.11/site-packages/__pycache__/typing_extensions.cpython-311.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3c70169ae3dc88df890d7c9351a8bf5cdb5f4580e9168a116679e6534eec57d8 +size 182701 diff --git a/.venv/lib/python3.11/site-packages/_virtualenv.pth b/.venv/lib/python3.11/site-packages/_virtualenv.pth new file mode 100644 index 0000000000000000000000000000000000000000..74d2eb6578fd774c6d8e324cd2fad5efb8beb747 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/_virtualenv.pth @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:69ac3d8f27e679c81b94ab30b3b56e9cd138219b1ba94a1fa3606d5a76a1433d +size 18 diff --git a/.venv/lib/python3.11/site-packages/_virtualenv.py b/.venv/lib/python3.11/site-packages/_virtualenv.py new file mode 100644 index 0000000000000000000000000000000000000000..6c1f22640d567f04c9880b90566436ee5ba14400 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/_virtualenv.py @@ -0,0 +1,101 @@ +"""Patches that are applied at runtime to the virtual environment.""" + +import os +import sys + +VIRTUALENV_PATCH_FILE = os.path.join(__file__) + + +def patch_dist(dist): + """ + Distutils allows user to configure some arguments via a configuration file: + https://docs.python.org/3.11/install/index.html#distutils-configuration-files. + + Some of this arguments though don't make sense in context of the virtual environment files, let's fix them up. + """ # noqa: D205 + # we cannot allow some install config as that would get packages installed outside of the virtual environment + old_parse_config_files = dist.Distribution.parse_config_files + + def parse_config_files(self, *args, **kwargs): + result = old_parse_config_files(self, *args, **kwargs) + install = self.get_option_dict("install") + + if "prefix" in install: # the prefix governs where to install the libraries + install["prefix"] = VIRTUALENV_PATCH_FILE, os.path.abspath(sys.prefix) + for base in ("purelib", "platlib", "headers", "scripts", "data"): + key = f"install_{base}" + if key in install: # do not allow global configs to hijack venv paths + install.pop(key, None) + return result + + dist.Distribution.parse_config_files = parse_config_files + + +# Import hook that patches some modules to ignore configuration values that break package installation in case +# of virtual environments. +_DISTUTILS_PATCH = "distutils.dist", "setuptools.dist" +# https://docs.python.org/3/library/importlib.html#setting-up-an-importer + + +class _Finder: + """A meta path finder that allows patching the imported distutils modules.""" + + fullname = None + + # lock[0] is threading.Lock(), but initialized lazily to avoid importing threading very early at startup, + # because there are gevent-based applications that need to be first to import threading by themselves. + # See https://github.com/pypa/virtualenv/issues/1895 for details. + lock = [] # noqa: RUF012 + + def find_spec(self, fullname, path, target=None): # noqa: ARG002 + if fullname in _DISTUTILS_PATCH and self.fullname is None: + # initialize lock[0] lazily + if len(self.lock) == 0: + import threading + + lock = threading.Lock() + # there is possibility that two threads T1 and T2 are simultaneously running into find_spec, + # observing .lock as empty, and further going into hereby initialization. However due to the GIL, + # list.append() operation is atomic and this way only one of the threads will "win" to put the lock + # - that every thread will use - into .lock[0]. + # https://docs.python.org/3/faq/library.html#what-kinds-of-global-value-mutation-are-thread-safe + self.lock.append(lock) + + from functools import partial + from importlib.util import find_spec + + with self.lock[0]: + self.fullname = fullname + try: + spec = find_spec(fullname, path) + if spec is not None: + # https://www.python.org/dev/peps/pep-0451/#how-loading-will-work + is_new_api = hasattr(spec.loader, "exec_module") + func_name = "exec_module" if is_new_api else "load_module" + old = getattr(spec.loader, func_name) + func = self.exec_module if is_new_api else self.load_module + if old is not func: + try: # noqa: SIM105 + setattr(spec.loader, func_name, partial(func, old)) + except AttributeError: + pass # C-Extension loaders are r/o such as zipimporter with <3.7 + return spec + finally: + self.fullname = None + return None + + @staticmethod + def exec_module(old, module): + old(module) + if module.__name__ in _DISTUTILS_PATCH: + patch_dist(module) + + @staticmethod + def load_module(old, name): + module = old(name) + if module.__name__ in _DISTUTILS_PATCH: + patch_dist(module) + return module + + +sys.meta_path.insert(0, _Finder()) diff --git a/.venv/lib/python3.11/site-packages/_yaml/__init__.py b/.venv/lib/python3.11/site-packages/_yaml/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7baa8c4b68127d5cdf0be9a799429e61347c2694 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/_yaml/__init__.py @@ -0,0 +1,33 @@ +# This is a stub package designed to roughly emulate the _yaml +# extension module, which previously existed as a standalone module +# and has been moved into the `yaml` package namespace. +# It does not perfectly mimic its old counterpart, but should get +# close enough for anyone who's relying on it even when they shouldn't. +import yaml + +# in some circumstances, the yaml module we imoprted may be from a different version, so we need +# to tread carefully when poking at it here (it may not have the attributes we expect) +if not getattr(yaml, '__with_libyaml__', False): + from sys import version_info + + exc = ModuleNotFoundError if version_info >= (3, 6) else ImportError + raise exc("No module named '_yaml'") +else: + from yaml._yaml import * + import warnings + warnings.warn( + 'The _yaml extension module is now located at yaml._yaml' + ' and its location is subject to change. To use the' + ' LibYAML-based parser and emitter, import from `yaml`:' + ' `from yaml import CLoader as Loader, CDumper as Dumper`.', + DeprecationWarning + ) + del warnings + # Don't `del yaml` here because yaml is actually an existing + # namespace member of _yaml. + +__name__ = '_yaml' +# If the module is top-level (i.e. not a part of any specific package) +# then the attribute should be set to ''. +# https://docs.python.org/3.8/library/types.html +__package__ = '' diff --git a/.venv/lib/python3.11/site-packages/anndata-0.12.19.dist-info/INSTALLER b/.venv/lib/python3.11/site-packages/anndata-0.12.19.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..5c69047b2eb8235994febeeae1da4a82365a240a --- /dev/null +++ b/.venv/lib/python3.11/site-packages/anndata-0.12.19.dist-info/INSTALLER @@ -0,0 +1 @@ +uv \ No newline at end of file diff --git a/.venv/lib/python3.11/site-packages/anndata/__init__.py b/.venv/lib/python3.11/site-packages/anndata/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b3857356c17316ffbb8c75b73310b2220bb97134 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/anndata/__init__.py @@ -0,0 +1,70 @@ +"""Annotated multivariate observation data.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from typing import Any + +from ._core.anndata import AnnData +from ._core.extensions import register_anndata_namespace +from ._core.merge import concat +from ._core.raw import Raw +from ._settings import settings +from ._warnings import ( + ExperimentalFeatureWarning, + ImplicitModificationWarning, + OldFormatWarning, + WriteWarning, +) +from .io import read_h5ad, read_zarr +from .utils import module_get_attr_redirect + +# Submodules need to be imported last +from . import abc, experimental, typing, io, types # isort: skip + +# We use these in tests by attribute access +from . import logging # noqa: F401 # isort: skip + +__all__ = [ + "AnnData", + "ExperimentalFeatureWarning", + "ImplicitModificationWarning", + "OldFormatWarning", + "Raw", + "WriteWarning", + "abc", + "concat", + "experimental", + "io", + "read_h5ad", + "read_zarr", + "register_anndata_namespace", + "settings", + "types", + "typing", +] + +_DEPRECATED_IO = ( + "read_loom", + "read_hdf", + "read_excel", + "read_umi_tools", + "read_csv", + "read_text", + "read_mtx", +) +_DEPRECATED = {method: f"io.{method}" for method in _DEPRECATED_IO} + + +def __getattr__(attr_name: str) -> Any: + if attr_name == "__version__": + import warnings + from importlib.metadata import version + + msg = "`__version__` is deprecated, use `importlib.metadata.version('anndata')` instead." + warnings.warn(msg, FutureWarning, stacklevel=2) + return version("anndata") + + return module_get_attr_redirect(attr_name, deprecated_mapping=_DEPRECATED) diff --git a/.venv/lib/python3.11/site-packages/anndata/__pycache__/__init__.cpython-311.pyc b/.venv/lib/python3.11/site-packages/anndata/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d80fe1194bc33135d2a36a652f9c765381e70f4e Binary files /dev/null and b/.venv/lib/python3.11/site-packages/anndata/__pycache__/__init__.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/anndata/__pycache__/_settings.cpython-311.pyc b/.venv/lib/python3.11/site-packages/anndata/__pycache__/_settings.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0ed68da258ad33b9f7df1734274f3944704b9fc7 Binary files /dev/null and b/.venv/lib/python3.11/site-packages/anndata/__pycache__/_settings.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/anndata/__pycache__/_types.cpython-311.pyc b/.venv/lib/python3.11/site-packages/anndata/__pycache__/_types.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f98c0ffe012b1dbdee4c60b0129953195ddb6a83 Binary files /dev/null and b/.venv/lib/python3.11/site-packages/anndata/__pycache__/_types.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/anndata/__pycache__/_warnings.cpython-311.pyc b/.venv/lib/python3.11/site-packages/anndata/__pycache__/_warnings.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..43ed73313e9145a23632a33458b729efa6697e3a Binary files /dev/null and b/.venv/lib/python3.11/site-packages/anndata/__pycache__/_warnings.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/anndata/__pycache__/abc.cpython-311.pyc b/.venv/lib/python3.11/site-packages/anndata/__pycache__/abc.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6d4d50ee82ee88b7f0258c58b094e489a1901c73 Binary files /dev/null and b/.venv/lib/python3.11/site-packages/anndata/__pycache__/abc.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/anndata/__pycache__/io.cpython-311.pyc b/.venv/lib/python3.11/site-packages/anndata/__pycache__/io.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae23d3e6c38e46e4239301289493105487c073c7 Binary files /dev/null and b/.venv/lib/python3.11/site-packages/anndata/__pycache__/io.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/anndata/__pycache__/logging.cpython-311.pyc b/.venv/lib/python3.11/site-packages/anndata/__pycache__/logging.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4bce6bd79106ab6c6da27d88cd7dea7980df59f4 Binary files /dev/null and b/.venv/lib/python3.11/site-packages/anndata/__pycache__/logging.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/anndata/__pycache__/types.cpython-311.pyc b/.venv/lib/python3.11/site-packages/anndata/__pycache__/types.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2c5d5f82882c455017ab215731bbde0f60e50ce5 Binary files /dev/null and b/.venv/lib/python3.11/site-packages/anndata/__pycache__/types.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/anndata/__pycache__/typing.cpython-311.pyc b/.venv/lib/python3.11/site-packages/anndata/__pycache__/typing.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..075c097934d4bf8cd44b267332279c00c76fe495 Binary files /dev/null and b/.venv/lib/python3.11/site-packages/anndata/__pycache__/typing.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/anndata/__pycache__/utils.cpython-311.pyc b/.venv/lib/python3.11/site-packages/anndata/__pycache__/utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b909baac7921e4a3b3ad6800eedcd65bcc45f01a Binary files /dev/null and b/.venv/lib/python3.11/site-packages/anndata/__pycache__/utils.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/anndata/_core/__init__.py b/.venv/lib/python3.11/site-packages/anndata/_core/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.11/site-packages/anndata/_core/__pycache__/__init__.cpython-311.pyc b/.venv/lib/python3.11/site-packages/anndata/_core/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2a2c3d7736d57b02b59f33c2e8b98338044b6689 Binary files /dev/null and b/.venv/lib/python3.11/site-packages/anndata/_core/__pycache__/__init__.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/anndata/_core/__pycache__/access.cpython-311.pyc b/.venv/lib/python3.11/site-packages/anndata/_core/__pycache__/access.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..24badbe2d9bb369cb3203252d7a63c761138e44d Binary files /dev/null and b/.venv/lib/python3.11/site-packages/anndata/_core/__pycache__/access.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/anndata/_core/__pycache__/aligned_df.cpython-311.pyc b/.venv/lib/python3.11/site-packages/anndata/_core/__pycache__/aligned_df.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6fb897c6ab1e8723cf321244230eea97e81024c8 Binary files /dev/null and b/.venv/lib/python3.11/site-packages/anndata/_core/__pycache__/aligned_df.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/anndata/_core/__pycache__/aligned_mapping.cpython-311.pyc b/.venv/lib/python3.11/site-packages/anndata/_core/__pycache__/aligned_mapping.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f76570acce00877c7cadcaf3280b1c28985cee93 Binary files /dev/null and b/.venv/lib/python3.11/site-packages/anndata/_core/__pycache__/aligned_mapping.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/anndata/_core/__pycache__/anndata.cpython-311.pyc b/.venv/lib/python3.11/site-packages/anndata/_core/__pycache__/anndata.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..619ba3fbfd3c3417aba31c4e6afb9f0ff878e12b Binary files /dev/null and b/.venv/lib/python3.11/site-packages/anndata/_core/__pycache__/anndata.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/anndata/_core/__pycache__/extensions.cpython-311.pyc b/.venv/lib/python3.11/site-packages/anndata/_core/__pycache__/extensions.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d15d817d4111c9d907f6f8b04adadc59bc71cbcd Binary files /dev/null and b/.venv/lib/python3.11/site-packages/anndata/_core/__pycache__/extensions.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/anndata/_core/__pycache__/file_backing.cpython-311.pyc b/.venv/lib/python3.11/site-packages/anndata/_core/__pycache__/file_backing.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..035865412dd00c271f5d6bd308e8da64187a02d6 Binary files /dev/null and b/.venv/lib/python3.11/site-packages/anndata/_core/__pycache__/file_backing.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/anndata/_core/__pycache__/index.cpython-311.pyc b/.venv/lib/python3.11/site-packages/anndata/_core/__pycache__/index.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..03f00cc20d60eae7e38fe5df96b00c2ed3cd9d8d Binary files /dev/null and b/.venv/lib/python3.11/site-packages/anndata/_core/__pycache__/index.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/anndata/_core/__pycache__/merge.cpython-311.pyc b/.venv/lib/python3.11/site-packages/anndata/_core/__pycache__/merge.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f6ad1ef1169d07328200893217e45f34037ea4f2 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/anndata/_core/__pycache__/merge.cpython-311.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5bba4a279512fcaf3959cd23dd945bf75ace74ed1b618f34f18d46f1f174dc5b +size 101151 diff --git a/.venv/lib/python3.11/site-packages/anndata/_core/__pycache__/raw.cpython-311.pyc b/.venv/lib/python3.11/site-packages/anndata/_core/__pycache__/raw.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c973c2f39fd039462ab06bfd6249acb57458c68 Binary files /dev/null and b/.venv/lib/python3.11/site-packages/anndata/_core/__pycache__/raw.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/anndata/_core/__pycache__/sparse_dataset.cpython-311.pyc b/.venv/lib/python3.11/site-packages/anndata/_core/__pycache__/sparse_dataset.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d2306b90a3ca4211d1a6b0e9dc7cbfe93b8f36c6 Binary files /dev/null and b/.venv/lib/python3.11/site-packages/anndata/_core/__pycache__/sparse_dataset.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/anndata/_core/__pycache__/storage.cpython-311.pyc b/.venv/lib/python3.11/site-packages/anndata/_core/__pycache__/storage.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8863ac4f7f4abb5b736086839679da21ed8ce1a7 Binary files /dev/null and b/.venv/lib/python3.11/site-packages/anndata/_core/__pycache__/storage.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/anndata/_core/__pycache__/views.cpython-311.pyc b/.venv/lib/python3.11/site-packages/anndata/_core/__pycache__/views.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac898bde040e6cde64928b622017a13c802ebc2f Binary files /dev/null and b/.venv/lib/python3.11/site-packages/anndata/_core/__pycache__/views.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/anndata/_core/__pycache__/xarray.cpython-311.pyc b/.venv/lib/python3.11/site-packages/anndata/_core/__pycache__/xarray.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..63b5ac9793ff82b11210b378f75fe621df9be0c8 Binary files /dev/null and b/.venv/lib/python3.11/site-packages/anndata/_core/__pycache__/xarray.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/anndata/_core/access.py b/.venv/lib/python3.11/site-packages/anndata/_core/access.py new file mode 100644 index 0000000000000000000000000000000000000000..9a2ffbbda397fee5b64e1dc38ff249cff3149655 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/anndata/_core/access.py @@ -0,0 +1,33 @@ +from __future__ import annotations + +from functools import reduce +from typing import TYPE_CHECKING, NamedTuple + +if TYPE_CHECKING: + from anndata import AnnData + + +class ElementRef(NamedTuple): + parent: AnnData + attrname: str + keys: tuple[str, ...] = () + + def __str__(self) -> str: + return f".{self.attrname}" + "".join(f"[{x!r}]" for x in self.keys) + + @property + def _parent_el(self): + return reduce( + lambda d, k: d[k], self.keys[:-1], getattr(self.parent, self.attrname) + ) + + def get(self): + """Get referenced value in self.parent.""" + return reduce(lambda d, k: d[k], self.keys, getattr(self.parent, self.attrname)) + + def set(self, val): + """Set referenced value in self.parent.""" + self._parent_el[self.keys[-1]] = val + + def delete(self): + del self._parent_el[self.keys[-1]] diff --git a/.venv/lib/python3.11/site-packages/anndata/_core/aligned_df.py b/.venv/lib/python3.11/site-packages/anndata/_core/aligned_df.py new file mode 100644 index 0000000000000000000000000000000000000000..a78bf9ccb9f682338654ef1e019c6802f1e9a5b6 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/anndata/_core/aligned_df.py @@ -0,0 +1,155 @@ +from __future__ import annotations + +import warnings +from collections.abc import Mapping +from functools import singledispatch +from typing import TYPE_CHECKING + +import pandas as pd +from pandas.api.types import is_string_dtype + +from .._warnings import ImplicitModificationWarning +from ..compat import XDataset, pandas_as_str +from .xarray import Dataset2D + +if TYPE_CHECKING: + from collections.abc import Iterable + from typing import Any, Literal + + +@singledispatch +def _gen_dataframe( + anno: Any, + index_names: Iterable[str], + *, + source: Literal["X", "shape"], + attr: Literal["obs", "var"], + length: int | None = None, +) -> pd.DataFrame: # pragma: no cover + msg = f"Cannot convert {type(anno)} to {attr} DataFrame" + raise ValueError(msg) + + +@_gen_dataframe.register(Mapping) +@_gen_dataframe.register(type(None)) +def _gen_dataframe_mapping( + anno: Mapping[str, Any] | None, + index_names: Iterable[str], + *, + source: Literal["X", "shape"], + attr: Literal["obs", "var"], + length: int | None = None, +) -> pd.DataFrame: + if anno is None or len(anno) == 0: + anno = {} + + def mk_index(l: int) -> pd.Index: + return pd.RangeIndex(0, l, name=None).astype(str) + + for index_name in index_names: + if index_name not in anno: + continue + df = pd.DataFrame( + anno, + index=anno[index_name], + columns=[k for k in anno if k != index_name], + ) + break + else: + df = pd.DataFrame( + anno, + index=None if length is None else mk_index(length), + columns=None if anno else pd.array([], dtype="str"), + ) + + if length is None: + df.index = mk_index(len(df)) + elif length != len(df): + raise _mk_df_error(source, attr, length, len(df)) + return df + + +@_gen_dataframe.register(pd.DataFrame) +def _gen_dataframe_df( + anno: pd.DataFrame, + index_names: Iterable[str], + *, + source: Literal["X", "shape"], + attr: Literal["obs", "var"], + length: int | None = None, +): + if isinstance(anno.index, pd.MultiIndex): + msg = ( + "pandas.MultiIndex not supported as index for obs or var on declaration.\n\ + You can set `obs_names` manually although most operations after will error or convert to str.\n\ + This behavior will likely be clarified in a future breaking release." + ) + raise ValueError(msg) + if length is not None and length != len(anno): + raise _mk_df_error(source, attr, length, len(anno)) + anno = anno.copy(deep=False) + if not is_string_dtype(anno.index[~anno.index.isna()]): + msg = "Transforming to str index." + warnings.warn(msg, ImplicitModificationWarning, stacklevel=2) + anno.index = pandas_as_str(anno.index) + if not len(anno.columns): + anno.columns = pandas_as_str(anno.columns) + return anno + + +@_gen_dataframe.register(pd.Series) +@_gen_dataframe.register(pd.Index) +def _gen_dataframe_1d( + anno: pd.Series | pd.Index, + index_names: Iterable[str], + *, + source: Literal["X", "shape"], + attr: Literal["obs", "var"], + length: int | None = None, +): + msg = f"Cannot convert {type(anno)} to {attr} DataFrame" + raise ValueError(msg) + + +def _mk_df_error( + source: Literal["X", "shape"], + attr: Literal["obs", "var"], + expected: int, + actual: int, +): + what = "row" if attr == "obs" else "column" + if source == "X": + msg = ( + f"Observations annot. `{attr}` must have as many rows as `X` has {what}s " + f"({expected}), but has {actual} rows." + ) + else: + msg = ( + f"`shape` is inconsistent with `{attr}` " + f"({actual} {what}s instead of {expected})" + ) + return ValueError(msg) + + +@_gen_dataframe.register(Dataset2D) +def _gen_dataframe_xr( + anno: Dataset2D, + index_names: Iterable[str], + *, + source: Literal["X", "shape"], + attr: Literal["obs", "var"], + length: int | None = None, +): + return anno + + +@_gen_dataframe.register(XDataset) +def _gen_dataframe_xdataset( + anno: XDataset, + index_names: Iterable[str], + *, + source: Literal["X", "shape"], + attr: Literal["obs", "var"], + length: int | None = None, +): + return Dataset2D(anno) diff --git a/.venv/lib/python3.11/site-packages/anndata/_core/aligned_mapping.py b/.venv/lib/python3.11/site-packages/anndata/_core/aligned_mapping.py new file mode 100644 index 0000000000000000000000000000000000000000..6a7f8e243466ac6497ac4c66ab9f1f570f02ea90 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/anndata/_core/aligned_mapping.py @@ -0,0 +1,450 @@ +from __future__ import annotations + +import warnings +from abc import ABC, abstractmethod +from collections.abc import MutableMapping, Sequence +from copy import copy +from dataclasses import dataclass +from typing import TYPE_CHECKING, Generic, TypeVar + +import numpy as np +import pandas as pd +from scverse_misc import Deprecation, deprecated + +from .._warnings import ExperimentalFeatureWarning, ImplicitModificationWarning +from ..compat import AwkArray, CSArray, CSMatrix, CupyArray, XDataset +from ..utils import ( + axis_len, + convert_to_dict, + deprecation_msg, + raise_value_error_if_multiindex_columns, + warn_once, +) +from .access import ElementRef +from .index import _subset +from .storage import coerce_array +from .views import as_view, view_update +from .xarray import Dataset2D + +if TYPE_CHECKING: + from collections.abc import Callable, Iterable, Iterator, Mapping + from typing import ClassVar, Literal, Self + + from .anndata import AnnData + from .raw import Raw + + +OneDIdx = Sequence[int] | Sequence[bool] | slice +TwoDIdx = tuple[OneDIdx, OneDIdx] +# TODO: pd.DataFrame only allowed in AxisArrays? +Value = pd.DataFrame | CSMatrix | CSArray | np.ndarray + +P = TypeVar("P", bound="AlignedMappingBase") +"""Parent mapping an AlignedView is based on.""" +I = TypeVar("I", OneDIdx, TwoDIdx) + + +class AlignedMappingBase(MutableMapping[str, Value], ABC): + """\ + An abstract base class for Mappings containing array-like values aligned + to either one or both AnnData axes. + """ + + _allow_df: ClassVar[bool] + """If this mapping supports heterogeneous DataFrames""" + + _view_class: ClassVar[type[AlignedView]] + """The view class for this aligned mapping.""" + + _actual_class: ClassVar[type[AlignedActual]] + """The actual class (which has it’s own data) for this aligned mapping.""" + + _parent: AnnData | Raw + """The parent object that this mapping is aligned to.""" + + def __repr__(self): + return f"{type(self).__name__} with keys: {', '.join(self.keys())}" + + def _ipython_key_completions_(self) -> list[str]: + return list(self.keys()) + + def _validate_value(self, val: Value, key: str) -> Value: + """Raises an error if value is invalid""" + if isinstance(val, AwkArray): + warn_once( + "Support for Awkward Arrays is currently experimental. " + "Behavior may change in the future. Please report any issues you may encounter!", + ExperimentalFeatureWarning, + # stacklevel=3, + ) + elif isinstance(val, np.ndarray | CupyArray) and len(val.shape) == 1: + val = val.reshape((val.shape[0], 1)) + elif isinstance(val, XDataset): + val = Dataset2D(val) + for i, axis in enumerate(self.axes): + if self.parent.shape[axis] == axis_len(val, i): + continue + right_shape = tuple(self.parent.shape[a] for a in self.axes) + actual_shape = tuple(axis_len(val, a) for a, _ in enumerate(self.axes)) + if actual_shape[i] is None and isinstance(val, AwkArray): + dim = ("obs", "var")[i] + msg = ( + f"The AwkwardArray is of variable length in dimension {dim}.", + f"Try ak.to_regular(array, {i}) before including the array in AnnData", + ) + else: + dims = tuple(("obs", "var")[ax] for ax in self.axes) + msg = ( + f"Value passed for key {key!r} is of incorrect shape. " + f"Values of {self.attrname} must match dimensions {dims} of parent. " + f"Value had shape {actual_shape} while it should have had {right_shape}." + ) + raise ValueError(msg) + name = f"{self.attrname.title().rstrip('s')} {key!r}" + return coerce_array(val, name=name, allow_df=self._allow_df) + + @property + @abstractmethod + def attrname(self) -> str: + """What attr for the AnnData is this?""" + + @property + @abstractmethod + def axes(self) -> tuple[Literal[0, 1], ...]: + """Which axes of the parent is this aligned to?""" + + @property + @abstractmethod + def is_view(self) -> bool: ... + + @property + def parent(self) -> AnnData | Raw: + return self._parent + + def copy(self) -> dict[str, Value]: + # Shallow copy for awkward array since their buffers are immutable + return { + k: copy(v) if isinstance(v, AwkArray) else v.copy() for k, v in self.items() + } + + def _view(self, parent: AnnData, subset_idx: I) -> AlignedView[Self, I]: + """Returns a subset copy-on-write view of the object.""" + return self._view_class(self, parent, subset_idx) + + @deprecated(Deprecation("0.10.2", deprecation_msg("as_dict", "dict(obj)"))) + def as_dict(self) -> dict: + return dict(self) + + +class AlignedView(AlignedMappingBase, Generic[P, I]): + is_view: ClassVar[Literal[True]] = True + + # override docstring + parent: AnnData + """Reference to parent AnnData view""" + + attrname: str + """What attribute in the parent is this?""" + + parent_mapping: P + """The object this is a view of.""" + + subset_idx: I + """The subset of the parent to view.""" + + def __init__(self, parent_mapping: P, parent_view: AnnData, subset_idx: I): + self.parent_mapping = parent_mapping + self._parent = parent_view + self.subset_idx = subset_idx + if hasattr(parent_mapping, "_axis"): + # LayersBase has no _axis, the rest does + self._axis = parent_mapping._axis # type: ignore + + def __getitem__(self, key: str) -> Value: + return as_view( + _subset(self.parent_mapping[key], self.subset_idx), + ElementRef(self.parent, self.attrname, (key,)), + ) + + def __setitem__(self, key: str, value: Value) -> None: + value = self._validate_value(value, key) # Validate before mutating + warnings.warn( + f"Setting element `.{self.attrname}['{key}']` of view, " + "initializing view as actual.", + ImplicitModificationWarning, + stacklevel=2, + ) + with view_update(self.parent, self.attrname, ()) as new_mapping: + new_mapping[key] = value + + def __delitem__(self, key: str) -> None: + if key not in self: + msg = f"{key!r} not found in view of {self.attrname}" + raise KeyError(msg) # Make sure it exists before bothering with a copy + warnings.warn( + f"Removing element `.{self.attrname}['{key}']` of view, " + "initializing view as actual.", + ImplicitModificationWarning, + stacklevel=2, + ) + with view_update(self.parent, self.attrname, ()) as new_mapping: + del new_mapping[key] + + def __contains__(self, key: str) -> bool: + return key in self.parent_mapping + + def __iter__(self) -> Iterator[str]: + return iter(self.parent_mapping) + + def __len__(self) -> int: + return len(self.parent_mapping) + + +class AlignedActual(AlignedMappingBase): + is_view: ClassVar[Literal[False]] = False + + _data: MutableMapping[str, Value] + """Underlying mapping to the data""" + + def __init__(self, parent: AnnData | Raw, *, store: MutableMapping[str, Value]): + self._parent = parent + self._data = store + for k, v in self._data.items(): + self._data[k] = self._validate_value(v, k) + + def __getitem__(self, key: str) -> Value: + return self._data[key] + + def __setitem__(self, key: str, value: Value): + value = self._validate_value(value, key) + self._data[key] = value + + def __contains__(self, key: str) -> bool: + return key in self._data + + def __delitem__(self, key: str): + del self._data[key] + + def __iter__(self) -> Iterator[str]: + return iter(self._data) + + def __len__(self) -> int: + return len(self._data) + + +class AxisArraysBase(AlignedMappingBase): + """\ + Mapping of key→array-like, + where array-like is aligned to an axis of parent AnnData. + """ + + _allow_df: ClassVar = True + _dimnames: ClassVar = ("obs", "var") + + _axis: Literal[0, 1] + + @property + def attrname(self) -> str: + return f"{self.dim}m" + + @property + def axes(self) -> tuple[Literal[0, 1]]: + """Axes of the parent this is aligned to""" + return (self._axis,) + + @property + def dim(self) -> str: + """Name of the dimension this aligned to.""" + return self._dimnames[self._axis] + + def to_df(self) -> pd.DataFrame: + """Convert to pandas dataframe.""" + df = pd.DataFrame(index=self.dim_names) + for key in self.keys(): + value = self[key] + for icolumn, column in enumerate(value.T): + df[f"{key}{icolumn + 1}"] = column + return df + + def _validate_value(self, val: Value, key: str) -> Value: + if isinstance(val, pd.DataFrame): + raise_value_error_if_multiindex_columns(val, f"{self.attrname}[{key!r}]") + if not val.index.equals(self.dim_names): + # Could probably also re-order index if it’s contained + try: + pd.testing.assert_index_equal(val.index, self.dim_names) + except AssertionError as e: + msg = f"value.index does not match parent’s {self.dim} names:\n{e}" + raise ValueError(msg) from None + else: + msg = "Index.equals and pd.testing.assert_index_equal disagree" + raise AssertionError(msg) + val.index.name = ( + self.dim_names.name + ) # this is consistent with AnnData.obsm.setter and AnnData.varm.setter + return super()._validate_value(val, key) + + @property + def dim_names(self) -> pd.Index: + return (self.parent.obs_names, self.parent.var_names)[self._axis] + + +class AxisArrays(AlignedActual, AxisArraysBase): + def __init__( + self, + parent: AnnData | Raw, + *, + axis: Literal[0, 1], + store: MutableMapping[str, Value] | AxisArraysBase, + ): + if axis not in {0, 1}: + raise ValueError() + self._axis = axis + super().__init__(parent, store=store) + + +class AxisArraysView(AlignedView[AxisArraysBase, OneDIdx], AxisArraysBase): + pass + + +AxisArraysBase._view_class = AxisArraysView +AxisArraysBase._actual_class = AxisArrays + + +class LayersBase(AlignedMappingBase): + """\ + Mapping of key: array-like, where array-like is aligned to both axes of the + parent anndata. + """ + + _allow_df: ClassVar = False + attrname: ClassVar[Literal["layers"]] = "layers" + axes: ClassVar[tuple[Literal[0], Literal[1]]] = (0, 1) + + +class Layers(AlignedActual, LayersBase): + pass + + +class LayersView(AlignedView[LayersBase, TwoDIdx], LayersBase): + pass + + +LayersBase._view_class = LayersView +LayersBase._actual_class = Layers + + +class PairwiseArraysBase(AlignedMappingBase): + """\ + Mapping of key: array-like, where both axes of array-like are aligned to + one axis of the parent anndata. + """ + + _allow_df: ClassVar = False + _dimnames: ClassVar = ("obs", "var") + + _axis: Literal[0, 1] + + @property + def attrname(self) -> str: + return f"{self.dim}p" + + @property + def axes(self) -> tuple[Literal[0], Literal[0]] | tuple[Literal[1], Literal[1]]: + """Axes of the parent this is aligned to""" + return self._axis, self._axis # type: ignore + + @property + def dim(self) -> str: + """Name of the dimension this aligned to.""" + return self._dimnames[self._axis] + + +class PairwiseArrays(AlignedActual, PairwiseArraysBase): + def __init__( + self, + parent: AnnData, + *, + axis: Literal[0, 1], + store: MutableMapping[str, Value], + ): + if axis not in {0, 1}: + raise ValueError() + self._axis = axis + super().__init__(parent, store=store) + + +class PairwiseArraysView(AlignedView[PairwiseArraysBase, OneDIdx], PairwiseArraysBase): + pass + + +PairwiseArraysBase._view_class = PairwiseArraysView +PairwiseArraysBase._actual_class = PairwiseArrays + + +AlignedMapping = ( + AxisArrays + | AxisArraysView + | Layers + | LayersView + | PairwiseArrays + | PairwiseArraysView +) +T = TypeVar("T", bound=AlignedMapping) +"""Pair of types to be aligned.""" + + +@dataclass +class AlignedMappingProperty(property, Generic[T]): + """A :class:`property` that creates an ephemeral AlignedMapping. + + The actual data is stored as `f'_{self.name}'` in the parent object. + """ + + cls: type[T] + """Concrete type that will be constructed.""" + axis: Literal[0, 1] | None = None + """Axis of the parent to align to.""" + name: str | None = None + """Name of the attribute in the parent object.""" + + def construct(self, obj: AnnData, *, store: MutableMapping[str, Value]) -> T: + if self.axis is None: + return self.cls(obj, store=store) + return self.cls(obj, axis=self.axis, store=store) + + @property + def fget(self) -> Callable[[], None]: + """Fake fget for sphinx-autodoc-typehints.""" + + def fake(): ... + + fake.__annotations__ = {"return": self.cls._actual_class | self.cls._view_class} + return fake + + def __set_name__(self, owner: AnnData, name: str): + self.name = name + + def __get__(self, obj: None | AnnData, objtype: type | None = None) -> T: + if obj is None: + # When accessed from the class, e.g. via `AnnData.obs`, + # this needs to return a `property` instance, e.g. for Sphinx + return self # type: ignore + if not obj.is_view: + return self.construct(obj, store=getattr(obj, f"_{self.name}")) + parent_anndata = obj._adata_ref + idxs = (obj._oidx, obj._vidx) + parent: AlignedMapping = getattr(parent_anndata, self.name) + return parent._view(obj, tuple(idxs[ax] for ax in parent.axes)) + + def __set__( + self, obj: AnnData, value: Mapping[str, Value] | Iterable[tuple[str, Value]] + ) -> None: + value = convert_to_dict(value) + _ = self.construct(obj, store=value) # Validate + if obj.is_view: + obj._init_as_actual(obj.copy()) + setattr(obj, f"_{self.name}", value) + + def __delete__(self, obj) -> None: + setattr(obj, self.name, dict()) diff --git a/.venv/lib/python3.11/site-packages/anndata/_core/anndata.py b/.venv/lib/python3.11/site-packages/anndata/_core/anndata.py new file mode 100644 index 0000000000000000000000000000000000000000..7b5c42fb51f8279bba8e9c4ef104b87688f6d33f --- /dev/null +++ b/.venv/lib/python3.11/site-packages/anndata/_core/anndata.py @@ -0,0 +1,2248 @@ +"""\ +Main class and helper functions. +""" + +from __future__ import annotations + +import warnings +from collections import OrderedDict +from collections.abc import Mapping, MutableMapping, Sequence +from copy import copy, deepcopy +from functools import partial, singledispatchmethod +from pathlib import Path +from textwrap import dedent +from typing import TYPE_CHECKING, cast + +import h5py +import numpy as np +import pandas as pd +from natsort import natsorted +from numpy import ma +from pandas.api.types import infer_dtype +from scipy import sparse +from scipy.sparse import issparse +from scverse_misc import Deprecation, deprecated + +from anndata._warnings import ImplicitModificationWarning +from testing.anndata._doctest import doctest_filterwarnings + +from .. import utils +from .._settings import settings +from ..compat import ( + CSArray, + DaskArray, + ZarrArray, + _move_adj_mtx, + old_positionals, + pandas_as_str, +) +from ..logging import anndata_logger as logger +from ..utils import ( + axis_len, + deprecation_msg, + ensure_df_homogeneous, + raise_value_error_if_multiindex_columns, +) +from .access import ElementRef +from .aligned_df import _gen_dataframe +from .aligned_mapping import AlignedMappingProperty, AxisArrays, Layers, PairwiseArrays +from .file_backing import AnnDataFileManager, to_memory +from .index import _normalize_indices, _subset, get_vector +from .raw import Raw +from .sparse_dataset import BaseCompressedSparseDataset, sparse_dataset +from .storage import coerce_array +from .views import DictView, _resolve_idxs, as_view +from .xarray import Dataset2D + +if TYPE_CHECKING: + from collections.abc import Iterable + from os import PathLike + from typing import Any, ClassVar, Literal, NoReturn + + from zarr.storage import StoreLike + + from ..compat import Index1D, Index1DNorm, XDataset + from ..typing import XDataType + from .aligned_mapping import AxisArraysView, LayersView, PairwiseArraysView + from .index import Index + + +class AnnData: # noqa: PLW1641 + """\ + An annotated data matrix. + + .. figure:: ../_static/img/anndata_schema.svg + :width: 260px + :align: right + :class: dark-light + + :class:`~anndata.AnnData` stores a data matrix :attr:`X` together with annotations + of observations :attr:`obs` (:attr:`obsm`, :attr:`obsp`), + variables :attr:`var` (:attr:`varm`, :attr:`varp`), + and unstructured annotations :attr:`uns`. + + An :class:`~anndata.AnnData` object `adata` can be sliced like a + :class:`~pandas.DataFrame`, + for instance `adata_subset = adata[:, list_of_variable_names]`. + :class:`~anndata.AnnData`’s basic structure is similar to R’s ExpressionSet + [Huber15]_. If setting an `.h5ad`-formatted HDF5 backing file `.filename`, + data remains on the disk but is automatically loaded into memory if needed. + + Parameters + ---------- + X + A #observations × #variables data matrix. A view of the data is used if the + data type matches, otherwise, a copy is made. + obs + Key-indexed one-dimensional observations annotation of length #observations. + var + Key-indexed one-dimensional variables annotation of length #variables. + uns + Key-indexed unstructured annotation. + obsm + Key-indexed multi-dimensional observations annotation of length #observations. + If passing a :class:`~numpy.ndarray`, it needs to have a structured datatype. + varm + Key-indexed multi-dimensional variables annotation of length #variables. + If passing a :class:`~numpy.ndarray`, it needs to have a structured datatype. + layers + Key-indexed multi-dimensional arrays aligned to dimensions of `X`. + shape + Shape tuple (#observations, #variables). Can only be provided if `X` is `None`. + filename + Name of backing file. See :class:`h5py.File`. + filemode + Open mode of backing file. See :class:`h5py.File`. + + See Also + -------- + io.read_h5ad + io.read_csv + io.read_excel + io.read_hdf + io.read_loom + io.read_zarr + io.read_mtx + io.read_text + io.read_umi_tools + + Notes + ----- + :class:`~anndata.AnnData` stores observations (samples) of variables/features + in the rows of a matrix. + This is the convention of the modern classics of statistics [Hastie09]_ + and machine learning [Murphy12]_, + the convention of dataframes both in R and Python and the established statistics + and machine learning packages in Python (statsmodels_, scikit-learn_). + + Single dimensional annotations of the observation and variables are stored + in the :attr:`obs` and :attr:`var` attributes as :class:`~pandas.DataFrame`\\ s. + This is intended for metrics calculated over their axes. + Multi-dimensional annotations are stored in :attr:`obsm` and :attr:`varm`, + which are aligned to the objects observation and variable dimensions respectively. + Square matrices representing graphs are stored in :attr:`obsp` and :attr:`varp`, + with both of their own dimensions aligned to their associated axis. + Additional measurements across both observations and variables are stored in + :attr:`layers`. + + Indexing into an AnnData object can be performed by relative position + with numeric indices (like pandas’ :meth:`~pandas.DataFrame.iloc`), + or by labels (like :meth:`~pandas.DataFrame.loc`). + To avoid ambiguity with numeric indexing into observations or variables, + indexes of the AnnData object are converted to strings by the constructor. + + Subsetting an AnnData object by indexing into it will also subset its elements + according to the dimensions they were aligned to. + This means an operation like `adata[list_of_obs, :]` will also subset :attr:`obs`, + :attr:`obsm`, and :attr:`layers`. + + Subsetting an AnnData object returns a view into the original object, + meaning very little additional memory is used upon subsetting. + This is achieved lazily, meaning that the constituent arrays are subset on access. + Copying a view causes an equivalent “real” AnnData object to be generated. + Attempting to modify a view (at any attribute except X) is handled + in a copy-on-modify manner, meaning the object is initialized in place. + Here’s an example:: + + batch1 = adata[adata.obs["batch"] == "batch1", :] + batch1.obs["value"] = 0 # This makes batch1 a “real” AnnData object + + At the end of this snippet: `adata` was not modified, + and `batch1` is its own AnnData object with its own data. + + Similar to Bioconductor’s `ExpressionSet` and :mod:`scipy.sparse` matrices, + subsetting an AnnData object retains the dimensionality of its constituent arrays. + Therefore, unlike with the classes exposed by :mod:`pandas`, :mod:`numpy`, + and `xarray`, there is no concept of a one dimensional AnnData object. + AnnDatas always have two inherent dimensions, :attr:`obs` and :attr:`var`. + Additionally, maintaining the dimensionality of the AnnData object allows for + consistent handling of :mod:`scipy.sparse` matrices and :mod:`numpy` arrays. + + .. _statsmodels: http://www.statsmodels.org/stable/index.html + .. _scikit-learn: http://scikit-learn.org/ + """ + + _BACKED_ATTRS: ClassVar[list[str]] = ["X", "raw.X"] + + # backwards compat + _H5_ALIASES: ClassVar[dict[str, set[str]]] = dict( + X={"X", "_X", "data", "_data"}, + obs={"obs", "_obs", "smp", "_smp"}, + var={"var", "_var"}, + uns={"uns"}, + obsm={"obsm", "_obsm", "smpm", "_smpm"}, + varm={"varm", "_varm"}, + layers={"layers", "_layers"}, + ) + + _H5_ALIASES_NAMES: ClassVar[dict[str, set[str]]] = dict( + obs={"obs_names", "smp_names", "row_names", "index"}, + var={"var_names", "col_names", "index"}, + ) + + _accessors: ClassVar[set[str]] = set() + + # view attributes + _adata_ref: AnnData | None + _oidx: Index1DNorm | None + _vidx: Index1DNorm | None + + @old_positionals( + "obsm", + "varm", + "layers", + "raw", + "dtype", + "shape", + "filename", + "filemode", + "asview", + ) + def __init__( # noqa: PLR0913 + self, + X: XDataType | pd.DataFrame | None = None, + obs: pd.DataFrame | Mapping[str, Iterable[Any]] | None = None, + var: pd.DataFrame | Mapping[str, Iterable[Any]] | None = None, + uns: Mapping[str, Any] | None = None, + *, + obsm: np.ndarray | Mapping[str, Sequence[Any]] | None = None, + varm: np.ndarray | Mapping[str, Sequence[Any]] | None = None, + layers: Mapping[str, XDataType] | None = None, + raw: Mapping[str, Any] | None = None, + dtype: np.dtype | type | str | None = None, + shape: tuple[int, int] | None = None, + filename: PathLike[str] | str | None = None, + filemode: Literal["r", "r+"] | None = None, + asview: bool = False, + obsp: np.ndarray | Mapping[str, Sequence[Any]] | None = None, + varp: np.ndarray | Mapping[str, Sequence[Any]] | None = None, + oidx: Index1DNorm | int | np.integer | None = None, + vidx: Index1DNorm | int | np.integer | None = None, + ): + # check for any multi-indices that aren’t later checked in coerce_array + for attr, key in [(obs, "obs"), (var, "var"), (X, "X")]: + if isinstance(attr, pd.DataFrame): + raise_value_error_if_multiindex_columns(attr, key) + if asview: + if not isinstance(X, AnnData): + msg = "`X` has to be an AnnData object." + raise ValueError(msg) + assert oidx is not None + assert vidx is not None + self._init_as_view(X, oidx, vidx) + else: + self._init_as_actual( + X=X, + obs=obs, + var=var, + uns=uns, + obsm=obsm, + varm=varm, + raw=raw, + layers=layers, + dtype=dtype, + shape=shape, + obsp=obsp, + varp=varp, + filename=filename, + filemode=filemode, + ) + + def _init_as_view( + self, + adata_ref: AnnData, + oidx: Index1DNorm | int | np.integer, + vidx: Index1DNorm | int | np.integer, + ): + if adata_ref.isbacked and adata_ref.is_view: + msg = ( + "Currently, you cannot index repeatedly into a backed AnnData, " + "that is, you cannot make a view of a view." + ) + raise ValueError(msg) + self._is_view = True + if isinstance(oidx, int | np.integer): + if not (-adata_ref.n_obs <= oidx < adata_ref.n_obs): + msg = f"Observation index `{oidx}` is out of range." + raise IndexError(msg) + oidx += adata_ref.n_obs * (oidx < 0) + oidx = slice(oidx, oidx + 1, 1) + if isinstance(vidx, int | np.integer): + if not (-adata_ref.n_vars <= vidx < adata_ref.n_vars): + msg = f"Variable index `{vidx}` is out of range." + raise IndexError(msg) + vidx += adata_ref.n_vars * (vidx < 0) + vidx = slice(vidx, vidx + 1, 1) + if adata_ref.is_view: + assert adata_ref._adata_ref is not None + assert adata_ref._oidx is not None + assert adata_ref._vidx is not None + prev_oidx, prev_vidx = adata_ref._oidx, adata_ref._vidx + adata_ref = adata_ref._adata_ref + oidx, vidx = _resolve_idxs((prev_oidx, prev_vidx), (oidx, vidx), adata_ref) + # self._adata_ref is never a view + self._adata_ref = adata_ref + self._oidx = oidx + self._vidx = vidx + # the file is the same as of the reference object + self.file = adata_ref.file + # views on attributes of adata_ref + obs_sub = adata_ref.obs.iloc[oidx] + var_sub = adata_ref.var.iloc[vidx] + # fix categories + uns = copy(adata_ref._uns) + if settings.remove_unused_categories: + self._remove_unused_categories(adata_ref.obs, obs_sub, uns) + self._remove_unused_categories(adata_ref.var, var_sub, uns) + # set attributes + self._obs = as_view(obs_sub, view_args=(self, "obs")) + self._var = as_view(var_sub, view_args=(self, "var")) + self._uns = uns + + # set data + if self.isbacked: + self._X = None + + # set raw, easy, as it’s immutable anyways... + if adata_ref._raw is not None: + # slicing along variables axis is ignored + self._raw = adata_ref.raw[self, oidx] + else: + self._raw = None + + def _init_as_actual( # noqa: PLR0912, PLR0913, PLR0915 + self, + X=None, + *, + obs=None, + var=None, + uns=None, + obsm=None, + varm=None, + varp=None, + obsp=None, + raw=None, + layers=None, + dtype=None, + shape=None, + filename=None, + filemode=None, + ): + # view attributes + self._is_view = False + self._adata_ref = None + self._oidx = None + self._vidx = None + + # ---------------------------------------------------------------------- + # various ways of initializing the data + # ---------------------------------------------------------------------- + + # If X is a data frame, we store its indices for verification + x_indices = [] + + # init from file + if filename is not None: + fileobj, filename = ( + (filename, None) + if isinstance(filename, h5py.File) + else (None, filename) + ) + self.file = AnnDataFileManager(self, filename, filemode, fileobj) + else: + self.file = AnnDataFileManager(self, None) + + # init from AnnData + if isinstance(X, AnnData): + if any((obs, var, uns, obsm, varm, obsp, varp)): + msg = "If `X` is a dict no further arguments must be provided." + raise ValueError(msg) + X, obs, var, uns, obsm, varm, obsp, varp, layers, raw = ( + X._X, + X.obs, + X.var, + X.uns, + X.obsm, + X.varm, + X.obsp, + X.varp, + X.layers, + X.raw, + ) + + # init from DataFrame + elif isinstance(X, pd.DataFrame): + # to verify index matching, we wait until obs and var are DataFrames + if obs is None: + obs = pd.DataFrame(index=X.index) + elif not isinstance(X.index, pd.RangeIndex): + x_indices.append(("obs", "index", pandas_as_str(X.index))) + if var is None: + var = pd.DataFrame(index=X.columns) + elif not isinstance(X.columns, pd.RangeIndex): + x_indices.append(("var", "columns", pandas_as_str(X.columns))) + X = ensure_df_homogeneous(X, "X") + + # ---------------------------------------------------------------------- + # actually process the data + # ---------------------------------------------------------------------- + + # check data type of X + if X is not None: + X = coerce_array(X, name="X") + if shape is not None: + msg = "`shape` needs to be `None` if `X` is not `None`." + raise ValueError(msg) + _check_2d_shape(X) + # if type doesn’t match, a copy is made, otherwise, use a view + if dtype is not None: + msg = ( + "The dtype argument is deprecated and will be removed in late 2024." + ) + warnings.warn(msg, FutureWarning, stacklevel=3) + if issparse(X) or isinstance(X, ma.MaskedArray): + # TODO: maybe use view on data attribute of sparse matrix + # as in readwrite.read_10x_h5 + if X.dtype != np.dtype(dtype): + X = X.astype(dtype) + elif isinstance(X, ZarrArray | DaskArray): + X = X.astype(dtype) + else: # is np.ndarray or a subclass, convert to true np.ndarray + X = np.asarray(X, dtype) + # data matrix and shape + self._X = X + n_obs, n_vars = X.shape + source = "X" + else: + self._X = None + n_obs, n_vars = ( + shape + if shape is not None + else _infer_shape( + obs, var, obsm=obsm, varm=varm, layers=layers, obsp=obsp, varp=varp + ) + ) + source = "shape" + + # annotations + self._obs = _gen_dataframe( + obs, ["obs_names", "row_names"], source=source, attr="obs", length=n_obs + ) + self._var = _gen_dataframe( + var, ["var_names", "col_names"], source=source, attr="var", length=n_vars + ) + + # now we can verify if indices match! + for attr_name, x_name, idx in x_indices: + attr = getattr(self, attr_name) + if isinstance(attr.index, pd.RangeIndex): + attr.index = idx + elif not idx.equals(attr.index): + msg = f"Index of {attr_name} must match {x_name} of X." + raise ValueError(msg) + + # unstructured annotations + self.uns = uns or OrderedDict() + + self.obsm = obsm + self.varm = varm + + self.obsp = obsp + self.varp = varp + + # Backwards compat for connectivities matrices in uns["neighbors"] + _move_adj_mtx({"uns": self._uns, "obsp": self._obsp}) + self._check_dimensions() + if settings.check_uniqueness: + self._check_uniqueness() + + if self.filename: + assert not isinstance(raw, Raw), ( + "got raw from other adata but also filename?" + ) + if {"raw", "raw.X"} & set(self.file): + raw = dict(X=None, **raw) + if not raw: + self._raw = None + elif isinstance(raw, Mapping): + self._raw = Raw(self, **raw) + else: # is a Raw from another AnnData + self._raw = Raw(self, raw._X, raw.var, raw.varm) + + # clean up old formats + self._clean_up_old_format(uns) + + # layers + self.layers = layers + + @old_positionals("show_stratified", "with_disk") + def __sizeof__( + self, *, show_stratified: bool = False, with_disk: bool = False + ) -> int: + def get_size(X) -> int: + def cs_to_bytes(X) -> int: + return int(X.data.nbytes + X.indptr.nbytes + X.indices.nbytes) + + if isinstance(X, h5py.Dataset) and with_disk: + return int(np.array(X.shape).prod() * X.dtype.itemsize) + elif isinstance(X, BaseCompressedSparseDataset) and with_disk: + return cs_to_bytes(X._to_backed()) + elif issparse(X): + return cs_to_bytes(X) + else: + return X.__sizeof__() + + sizes = {} + attrs = ["X", "_obs", "_var"] + attrs_multi = ["_uns", "_obsm", "_varm", "varp", "_obsp", "_layers"] + for attr in attrs + attrs_multi: + if attr in attrs_multi: + keys = getattr(self, attr).keys() + s = sum(get_size(getattr(self, attr)[k]) for k in keys) + else: + s = get_size(getattr(self, attr)) + if s > 0 and show_stratified: + from tqdm import tqdm + + print( + f"Size of {attr.replace('_', '.'):<7}: {tqdm.format_sizeof(s, 'B')}" + ) + sizes[attr] = s + return sum(sizes.values()) + + def _gen_repr(self, n_obs, n_vars) -> str: + backed_at = f" backed at {str(self.filename)!r}" if self.isbacked else "" + descr = f"AnnData object with n_obs × n_vars = {n_obs} × {n_vars}{backed_at}" + for attr in [ + "obs", + "var", + "uns", + "obsm", + "varm", + "layers", + "obsp", + "varp", + ]: + keys = getattr(self, attr).keys() + if len(keys) > 0: + descr += f"\n {attr}: {str(list(keys))[1:-1]}" + return descr + + def __repr__(self) -> str: + if self.is_view: + return "View of " + self._gen_repr(self.n_obs, self.n_vars) + else: + return self._gen_repr(self.n_obs, self.n_vars) + + def __eq__(self, other): + """Equality testing""" + msg = ( + "Equality comparisons are not supported for AnnData objects, " + "instead compare the desired attributes." + ) + raise NotImplementedError(msg) + + @property + def shape(self) -> tuple[int, int]: + """Shape of data matrix (:attr:`n_obs`, :attr:`n_vars`).""" + return self.n_obs, self.n_vars + + @property + def X(self) -> XDataType | None: + """Data matrix of shape :attr:`n_obs` × :attr:`n_vars`.""" + if self.isbacked: + if not self.file.is_open: + self.file.open() + X = self.file["X"] + if isinstance(X, h5py.Group): + X = sparse_dataset(X) + # This is so that we can index into a backed dense dataset with + # indices that aren’t strictly increasing + if self.is_view: + X = _subset(X, (self._oidx, self._vidx)) + elif self.is_view and self._adata_ref.X is None: + X = None + elif self.is_view: + X = as_view( + _subset(self._adata_ref.X, (self._oidx, self._vidx)), + ElementRef(self, "X"), + ) + else: + X = self._X + return X + # if self.n_obs == 1 and self.n_vars == 1: + # return X[0, 0] + # elif self.n_obs == 1 or self.n_vars == 1: + # if issparse(X): X = X.toarray() + # return X.flatten() + # else: + # return X + + def _handle_view_X_cow(self, value: XDataType | None): + if self._is_view: + if settings.copy_on_write_X: + if np.isscalar(value) and value is not None: + msg = "The ability to set X with a scalar value will be removed in the future. Initializing as an `np.array` with the shape of the current view." + warnings.warn(msg, FutureWarning, stacklevel=2) + value = np.full(self.shape, fill_value=value) + if hasattr(value, "shape") and value.shape != self.shape: + msg = "Automatic reshaping when setting X will be removed in the future." + warnings.warn(msg, FutureWarning, stacklevel=2) + value = value.reshape(self.shape) + msg = "Setting element `.X` of view, initializing view as actual." + warnings.warn(msg, ImplicitModificationWarning, stacklevel=2) + new = self._mutated_copy(X=value) + self._init_as_actual(new) + return True + msg = "Setting element `.X` of view of `AnnData` object will obey copy-on-write semantics in the next minor release. " + "In other words, this subset of your original `AnnData` will be copied-in-place and initialized with the value passed into this setter. " + "Set `anndata.settings.copy_on_write_X = True` to begin opting in to this behavior." + warnings.warn(msg, FutureWarning, stacklevel=2) + return False + + @X.setter + def X(self, value: XDataType | None): # noqa: PLR0912 + value = ( + coerce_array(value, name="X", allow_array_like=True) + if value is not None + else None + ) + can_set_direct_if_not_none = value is None or ( + np.isscalar(value) + or (hasattr(value, "shape") and (self.shape == value.shape)) + or (self.n_vars == 1 and self.n_obs == len(value)) + or (self.n_obs == 1 and self.n_vars == len(value)) + ) + if not can_set_direct_if_not_none: + msg = f"Data matrix has wrong shape {value.shape}, need to be {self.shape}." + raise ValueError(msg) + if self._handle_view_X_cow(value): + return None + if value is None: + if self.isbacked: + msg = "Cannot currently remove data matrix from backed object." + raise NotImplementedError(msg) + if self.is_view: + self._init_as_actual(self.copy()) + self._X = None + return + + # If indices are both arrays, we need to modify them + # so we don’t set values like coordinates + # This can occur if there are successive views + if ( + self.is_view + and isinstance(self._oidx, np.ndarray) + and isinstance(self._vidx, np.ndarray) + ): + oidx, vidx = np.ix_(self._oidx, self._vidx) + else: + oidx, vidx = self._oidx, self._vidx + if not np.isscalar(value): + if self.is_view and any( + isinstance(idx, np.ndarray) and len(np.unique(idx)) != len(idx.ravel()) + for idx in [oidx, vidx] + ): + msg = ( + "You are attempting to set `X` to a matrix on a view which has non-unique indices. " + "The resulting `adata.X` will likely not equal the value to which you set it. " + "To avoid this potential issue, please make a copy of the data first. " + "In the future, this operation will throw an error." + ) + warnings.warn(msg, FutureWarning, stacklevel=2) + if self.shape != value.shape: + # For assigning vector of values to 2d array or matrix + # Not necessary for row of 2d array + value = value.reshape(self.shape) + if self.isbacked: + if self.is_view: + X = self.file["X"] + if isinstance(X, h5py.Group): + msg = "Cannot write to views of sparse backed files" + raise NotImplementedError(msg) + X[oidx, vidx] = value + else: + self._set_backed("X", value) + elif self.is_view: + if sparse.issparse(self._adata_ref._X) and isinstance(value, np.ndarray): + if isinstance(self._adata_ref.X, CSArray): + memory_class = sparse.coo_array + else: + memory_class = sparse.coo_matrix + value = memory_class(value) + elif sparse.issparse(value) and isinstance(self._adata_ref._X, np.ndarray): + msg = ( + "Trying to set a dense array with a sparse array on a view. " + "Densifying the sparse array. " + "This may incur excessive memory usage" + ) + warnings.warn(msg, UserWarning, stacklevel=2) + value = value.toarray() + msg = "Modifying `X` on a view results in data being overridden" + warnings.warn(msg, ImplicitModificationWarning, stacklevel=2) + self._adata_ref._X[oidx, vidx] = value + else: + self._X = value + + @X.deleter + def X(self): + self.X = None + + layers: AlignedMappingProperty[Layers | LayersView] = AlignedMappingProperty(Layers) + """\ + Dictionary-like object with values of the same dimensions as :attr:`X`. + + Layers in AnnData are inspired by loompy’s :ref:`loomlayers`. + + Return the layer named `"unspliced"`:: + + adata.layers["unspliced"] + + Create or replace the `"spliced"` layer:: + + adata.layers["spliced"] = ... + + Assign the 10th column of layer `"spliced"` to the variable a:: + + a = adata.layers["spliced"][:, 10] + + Delete the `"spliced"` layer:: + + del adata.layers["spliced"] + + Return layers’ names:: + + adata.layers.keys() + """ + + @property + def raw(self) -> Raw: + """\ + Store raw version of :attr:`X` and :attr:`var` as `.raw.X` and `.raw.var`. + + The :attr:`raw` attribute is initialized with the current content + of an object by setting:: + + adata.raw = adata.copy() + + Its content can be deleted:: + + adata.raw = None + # or + del adata.raw + + Upon slicing an AnnData object along the obs (row) axis, :attr:`raw` + is also sliced. Slicing an AnnData object along the vars (columns) axis + leaves :attr:`raw` unaffected. Note that you can call:: + + adata.raw[:, 'orig_variable_name'].X + + to retrieve the data associated with a variable that might have been + filtered out or "compressed away" in :attr:`X`. + """ + return self._raw + + @raw.setter + def raw(self, value: AnnData) -> None: + if value is None: + del self.raw + return + if not isinstance(value, AnnData): + msg = "Can only init raw attribute with an AnnData object." + raise ValueError(msg) + raw = Raw(self, X=value.X, var=value.var, varm=value.varm) + if self.is_view: + self._init_as_actual(self.copy()) + self._raw = raw + + @raw.deleter + def raw(self) -> None: + if self.is_view: + self._init_as_actual(self.copy()) + self._raw = None + + @property + def n_obs(self) -> int: + """Number of observations.""" + return len(self.obs_names) + + @property + def n_vars(self) -> int: + """Number of variables/features.""" + return len(self.var_names) + + def _set_dim_df(self, value: pd.DataFrame | XDataset, attr: Literal["obs", "var"]): + value = _gen_dataframe( + value, + [f"{attr}_names", f"{'row' if attr == 'obs' else 'col'}_names"], + source="shape", + attr=attr, + length=self.n_obs if attr == "obs" else self.n_vars, + ) + raise_value_error_if_multiindex_columns(value, attr) + value_idx = self._prep_dim_index(value.index, attr) + if self.is_view: + self._init_as_actual(self.copy()) + setattr(self, f"_{attr}", value) + self._set_dim_index(value_idx, attr) + if not len(value.columns): + value.columns = value.columns.astype(str) + + def _prep_dim_index(self, value, attr: str) -> pd.Index: + """Prepares index to be uses as obs_names or var_names for AnnData object.AssertionError + + If a pd.Index is passed, this will use a reference, otherwise a new index object is created. + """ + if self.shape[attr == "var"] != len(value): + msg = f"Length of passed value for {attr}_names is {len(value)}, but this AnnData has shape: {self.shape}" + raise ValueError(msg) + if isinstance(value, pd.Index) and not isinstance(value.name, str | type(None)): + msg = ( + f"AnnData expects .{attr}.index.name to be a string or None, " + f"but you passed a name of type {type(value.name).__name__!r}" + ) + raise ValueError(msg) + else: + value = ( + value if isinstance(value, pd.Index) else pandas_as_str(pd.Index(value)) + ) + if not isinstance(value.name, str | type(None)): + value.name = None + if ( + len(value) > 0 + and not isinstance(value, pd.RangeIndex) + and infer_dtype(value) not in {"string", "bytes"} + ): + sample = list(value[: min(len(value), 5)]) + msg = dedent( + f""" + AnnData expects .{attr}.index to contain strings, but got values like: + {sample} + + Inferred to be: {infer_dtype(value)} + """ + ) + warnings.warn(msg, stacklevel=2) + return value + + def _set_dim_index(self, value: pd.Index, attr: str): + # Assumes _prep_dim_index has been run + if self.is_view: + self._init_as_actual(self.copy()) + getattr(self, attr).index = value + for v in getattr(self, f"_{attr}m").values(): + if isinstance(v, pd.DataFrame): + v.index = value + + @property + def obs(self) -> pd.DataFrame | Dataset2D: + """One-dimensional annotation of observations (`pd.DataFrame`).""" + return self._obs + + @obs.setter + def obs(self, value: pd.DataFrame | XDataset): + self._set_dim_df(value, "obs") + + @obs.deleter + def obs(self): + self.obs = pd.DataFrame({}, index=self.obs_names) + + @property + def obs_names(self) -> pd.Index: + """Names of observations (alias for `.obs.index`).""" + return self.obs.index + + @obs_names.setter + def obs_names(self, names: Sequence[str]): + names = self._prep_dim_index(names, "obs") + self._set_dim_index(names, "obs") + + @property + def var(self) -> pd.DataFrame | Dataset2D: + """One-dimensional annotation of variables/ features (`pd.DataFrame`).""" + return self._var + + @var.setter + def var(self, value: pd.DataFrame | XDataset): + self._set_dim_df(value, "var") + + @var.deleter + def var(self): + self.var = pd.DataFrame({}, index=self.var_names) + + @property + def var_names(self) -> pd.Index: + """Names of variables (alias for `.var.index`).""" + return self.var.index + + @var_names.setter + def var_names(self, names: Sequence[str]): + names = self._prep_dim_index(names, "var") + self._set_dim_index(names, "var") + + @property + def uns(self) -> MutableMapping: + """Unstructured annotation (ordered dictionary).""" + uns = self._uns + if self.is_view: + uns = DictView(uns, view_args=(self, "_uns")) + return uns + + @uns.setter + def uns(self, value: MutableMapping): + if not isinstance(value, MutableMapping): + msg = "Only mutable mapping types (e.g. dict) are allowed for `.uns`." + raise ValueError(msg) + if isinstance(value, DictView): + value = value.copy() + if self.is_view: + self._init_as_actual(self.copy()) + self._uns = value + + @uns.deleter + def uns(self): + self.uns = OrderedDict() + + obsm: AlignedMappingProperty[AxisArrays | AxisArraysView] = AlignedMappingProperty( + AxisArrays, 0 + ) + """\ + Multi-dimensional annotation of observations + (mutable structured :class:`~numpy.ndarray`). + + Stores for each key a two or higher-dimensional :class:`~numpy.ndarray` + of length `n_obs`. + Is sliced with `data` and `obs` but behaves otherwise like a :term:`mapping`. + """ + + varm: AlignedMappingProperty[AxisArrays | AxisArraysView] = AlignedMappingProperty( + AxisArrays, 1 + ) + """\ + Multi-dimensional annotation of variables/features + (mutable structured :class:`~numpy.ndarray`). + + Stores for each key a two or higher-dimensional :class:`~numpy.ndarray` + of length `n_vars`. + Is sliced with `data` and `var` but behaves otherwise like a :term:`mapping`. + """ + + obsp: AlignedMappingProperty[PairwiseArrays | PairwiseArraysView] = ( + AlignedMappingProperty(PairwiseArrays, 0) + ) + """\ + Pairwise annotation of observations, + a mutable mapping with array-like values. + + Stores for each key a two or higher-dimensional :class:`~numpy.ndarray` + whose first two dimensions are of length `n_obs`. + Is sliced with `data` and `obs` but behaves otherwise like a :term:`mapping`. + """ + + varp: AlignedMappingProperty[PairwiseArrays | PairwiseArraysView] = ( + AlignedMappingProperty(PairwiseArrays, 1) + ) + """\ + Pairwise annotation of variables/features, + a mutable mapping with array-like values. + + Stores for each key a two or higher-dimensional :class:`~numpy.ndarray` + whose first two dimensions are of length `n_var`. + Is sliced with `data` and `var` but behaves otherwise like a :term:`mapping`. + """ + + @deprecated( + Deprecation( + "0.12.3", + deprecation_msg( + *("obs_keys", "obs"), + "(e.g. `k in adata.obs` or `str(adata.obs.columns.tolist())`)", + ), + ) + ) + def obs_keys(self) -> list[str]: + """List keys of observation annotation :attr:`obs`.""" + return self._obs.keys().tolist() + + @deprecated( + Deprecation( + "0.12.3", + deprecation_msg( + *("var_keys", "var"), + "(e.g. `k in adata.var` or `str(adata.var.columns.tolist())`)", + ), + ) + ) + def var_keys(self) -> list[str]: + """List keys of variable annotation :attr:`var`.""" + return self._var.keys().tolist() + + @deprecated( + Deprecation( + "0.12.3", + deprecation_msg( + *("obsm_keys", "obsm"), + "(e.g. `k in adata.obsm` or `adata.obsm.keys() | {'u'}`)", + ), + ) + ) + def obsm_keys(self) -> list[str]: + """List keys of observation annotation :attr:`obsm`.""" + return list(self.obsm.keys()) + + @deprecated( + Deprecation( + "0.12.3", + deprecation_msg( + *("varm_keys", "varm"), + "(e.g. `k in adata.varm` or `adata.varm.keys() | {'u'}`)", + ), + ) + ) + def varm_keys(self) -> list[str]: + """List keys of variable annotation :attr:`varm`.""" + return list(self.varm.keys()) + + @deprecated( + Deprecation( + "0.13", + deprecation_msg( + "uns_keys", "uns", "(e.g. `k in adata.uns` or `sorted(adata.uns)`)" + ), + ) + ) + def uns_keys(self) -> list[str]: + """List keys of unstructured annotation.""" + return sorted(self._uns.keys()) + + @property + def isbacked(self) -> bool: + """`True` if object is backed on disk, `False` otherwise.""" + is_filename_none = self.filename is not None + is_x_none = ( + getattr(self._adata_ref if self._is_view else self, "_X", None) is None + ) + return is_filename_none and is_x_none + + @property + def is_view(self) -> bool: + """`True` if object is view of another AnnData object, `False` otherwise.""" + return self._is_view + + @property + def filename(self) -> Path | None: + """\ + Change to backing mode by setting the filename of a `.h5ad` file. + + - Setting the filename writes the stored data to disk. + - Setting the filename when the filename was previously another name + moves the backing file from the previous file to the new file. + If you want to copy the previous file, use `copy(filename='new_filename')`. + """ + return self.file.filename + + @filename.setter + def filename(self, filename: PathLike[str] | str | None): + # convert early for later comparison + filename = None if filename is None else Path(filename) + # change from backing-mode back to full loading into memory + if filename is None: + if self.filename is not None: + self.file._to_memory_mode() + else: + # both filename and self.filename are None + # do nothing + return + else: + if self.filename is not None: + if self.filename != filename: + # write the content of self to the old file + # and close the file + self.write() + self.filename.rename(filename) + else: + # do nothing + return + else: + # change from memory to backing-mode + # write the content of self to disk + as_dense = ("X", "raw/X") if self.raw is not None else ("X",) + self.write(filename, as_dense=as_dense) + # open new file for accessing + self.file.open(filename, "r+") + # as the data is stored on disk, we can safely set self._X to None + self._X = None + + def _set_backed(self, attr, value): + from .._io.utils import write_attribute + + write_attribute(self.file._file, attr, value) + + def _normalize_indices( + self, index: Index | None + ) -> tuple[Index1DNorm | int | np.integer, Index1DNorm | int | np.integer]: + return _normalize_indices(index, self.obs_names, self.var_names) + + # TODO: this is not quite complete... + def __delitem__(self, index: Index): + obs, var = self._normalize_indices(index) + # TODO: does this really work? + if not self.isbacked: + del self._X[obs, var] + else: + X = self.file["X"] + del X[obs, var] + self._set_backed("X", X) + if var == slice(None): + del self._obs.iloc[obs, :] + if obs == slice(None): + del self._var.iloc[var, :] + + def __getitem__(self, index: Index) -> AnnData: + """Returns a sliced view of the object.""" + oidx, vidx = self._normalize_indices(index) + return AnnData(self, oidx=oidx, vidx=vidx, asview=True) + + @singledispatchmethod + @staticmethod + def _remove_unused_categories( + df_full: pd.DataFrame, df_sub: pd.DataFrame, uns: dict[str, Any] + ): + for k in df_full: + if not isinstance(df_full[k].dtype, pd.CategoricalDtype): + continue + all_categories = df_full[k].cat.categories + # TODO: this mode is going away + with pd.option_context("mode.chained_assignment", None): + df_sub[k] = df_sub[k].cat.remove_unused_categories() + # also correct the colors... + color_key = f"{k}_colors" + if color_key not in uns: + continue + color_vec = uns[color_key] + if np.array(color_vec).ndim == 0: + # Make 0D arrays into 1D ones + uns[color_key] = np.array(color_vec)[(None,)] + elif len(color_vec) != len(all_categories): + # Reset colors + del uns[color_key] + else: + idx = np.where(np.isin(all_categories, df_sub[k].cat.categories))[0] + uns[color_key] = np.array(color_vec)[(idx,)] + + def rename_categories(self, key: str, categories: Sequence[Any]): + """\ + Rename categories of annotation `key` in :attr:`obs`, :attr:`var`, + and :attr:`uns`. + + Only supports passing a list/array-like `categories` argument. + + Besides calling `self.obs[key].cat.categories = categories` – + similar for :attr:`var` - this also renames categories in unstructured + annotation that uses the categorical annotation `key`. + + Parameters + ---------- + key + Key for observations or variables annotation. + categories + New categories, the same number as the old categories. + """ + if isinstance(categories, Mapping): + msg = "Only list-like `categories` is supported." + raise ValueError(msg) + if key in self.obs: + old_categories = self.obs[key].cat.categories.tolist() + self.obs[key] = self.obs[key].cat.rename_categories(categories) + elif key in self.var: + old_categories = self.var[key].cat.categories.tolist() + self.var[key] = self.var[key].cat.rename_categories(categories) + else: + msg = f"{key} is neither in `.obs` nor in `.var`." + raise ValueError(msg) + # this is not a good solution + # but depends on the scanpy conventions for storing the categorical key + # as `groupby` in the `params` slot + for k1, v1 in self.uns.items(): + if not ( + isinstance(v1, Mapping) + and "params" in v1 + and "groupby" in v1["params"] + and v1["params"]["groupby"] == key + ): + continue + for k2, v2 in v1.items(): + # picks out the recarrays that are named according to the old + # categories + if isinstance(v2, np.ndarray) and v2.dtype.names is not None: + if list(v2.dtype.names) == old_categories: + self.uns[k1][k2].dtype.names = categories + else: + logger.warning( + f"Omitting {k1}/{k2} as old categories do not match." + ) + + def strings_to_categoricals(self, df: pd.DataFrame | None = None): + """\ + Transform string annotations to categoricals. + + Only affects string annotations that lead to less categories than the + total number of observations. + + Params + ------ + df + If `df` is `None`, modifies both :attr:`obs` and :attr:`var`, + otherwise modifies `df` inplace. + + Notes + ----- + Turns the view of an :class:`~anndata.AnnData` into an actual + :class:`~anndata.AnnData`. + """ + dont_modify = False # only necessary for backed views + if df is None: + dfs = [self.obs, self.var] + if self.is_view and self.isbacked: + dont_modify = True + else: + dfs = [df] + del df + + for df in dfs: + string_cols = [ + key for key in df.columns if infer_dtype(df[key]) == "string" + ] + for key in string_cols: + c = pd.Categorical(df[key]) + # TODO: We should only check if non-null values are unique, but + # this would break cases where string columns with nulls could + # be written as categorical, but not as string. + # Possible solution: https://github.com/scverse/anndata/issues/504 + if len(c.categories) >= len(c): + continue + # Ideally this could be done inplace + sorted_categories = natsorted(c.categories) + if not np.array_equal(c.categories, sorted_categories): + c = c.reorder_categories(sorted_categories) + if dont_modify: + msg = ( + "Please call `.strings_to_categoricals()` on full " + "AnnData, not on this view. You might encounter this" + "error message while copying or writing to disk." + ) + raise RuntimeError(msg) + df[key] = c + logger.info(f"... storing {key!r} as categorical") + + _sanitize = strings_to_categoricals # backwards compat + + def _inplace_subset_var(self, index: Index1D): + """\ + Inplace subsetting along variables dimension. + + Same as `adata = adata[:, index]`, but inplace. + """ + adata_subset = self[:, index].copy() + + self._init_as_actual(adata_subset) + + def _inplace_subset_obs(self, index: Index1D): + """\ + Inplace subsetting along variables dimension. + + Same as `adata = adata[index, :]`, but inplace. + """ + adata_subset = self[index].copy() + + self._init_as_actual(adata_subset) + + # TODO: Update, possibly remove + def __setitem__(self, index: Index, val: float | XDataType): + if self.is_view: + msg = "Object is view and cannot be accessed with `[]`." + raise ValueError(msg) + obs, var = self._normalize_indices(index) + if not self.isbacked: + self._X[obs, var] = val + else: + X = self.file["X"] + X[obs, var] = val + self._set_backed("X", X) + + def __len__(self) -> int: + return self.shape[0] + + def transpose(self) -> AnnData: + """\ + Transpose whole object. + + Data matrix is transposed, observations and variables are interchanged. + Ignores `.raw`. + """ + from anndata.compat import _safe_transpose + + X = self.X if not self.isbacked else self.file["X"] + if self.is_view: + msg = ( + "You’re trying to transpose a view of an `AnnData`, " + "which is currently not implemented. Call `.copy()` before transposing." + ) + raise ValueError(msg) + if any( + isinstance(elem, ZarrArray | BaseCompressedSparseDataset | h5py.Dataset) + for elem in (self.X, *self.layers.values()) + ): + msg = "Cannot transpose anndata object that has raw zarr arrays or h5py arrays backing X or layers" + raise ValueError(msg) + + return AnnData( + X=_safe_transpose(X) if X is not None else None, + layers={k: _safe_transpose(v) for k, v in self.layers.items()}, + obs=self.var, + var=self.obs, + uns=self._uns, + obsm=self.varm, + varm=self.obsm, + obsp=self.varp, + varp=self.obsp, + filename=self.filename, + ) + + T = property(transpose) + + def to_df(self, layer: str | None = None) -> pd.DataFrame: + """\ + Generate shallow :class:`~pandas.DataFrame`. + + The data matrix :attr:`X` is returned as + :class:`~pandas.DataFrame`, where :attr:`obs_names` initializes the + index, and :attr:`var_names` the columns. + + * No annotations are maintained in the returned object. + * The data matrix is densified in case it is sparse. + + Params + ------ + layer + Key for `.layers`. + + Returns + ------- + Pandas DataFrame of specified data matrix. + """ + if layer is not None: + X = self.layers[layer] + elif not self._has_X(): + msg = "X is None, cannot convert to dataframe." + raise ValueError(msg) + else: + X = self.X + if issparse(X): + X = X.toarray() + return pd.DataFrame(X, index=self.obs_names, columns=self.var_names) + + def _get_X(self, *, use_raw: bool = False, layer: str | None = None): + """\ + Convenience method for getting expression values + with common arguments and error handling. + """ + is_layer = layer is not None + if use_raw and is_layer: + msg = ( + "Cannot use expression from both layer and raw. You provided:" + f"`use_raw={use_raw}` and `layer={layer}`" + ) + raise ValueError(msg) + if is_layer: + return self.layers[layer] + elif use_raw: + if self.raw is None: + msg = "This AnnData doesn’t have a value in `.raw`." + raise ValueError(msg) + return self.raw.X + else: + return self.X + + def obs_vector(self, k: str, *, layer: str | None = None) -> np.ndarray: + """\ + Convenience function for returning a 1 dimensional ndarray of values + from :attr:`X`, :attr:`layers`\\ `[k]`, or :attr:`obs`. + + Made for convenience, not performance. + Intentionally permissive about arguments, for easy iterative use. + + Params + ------ + k + Key to use. Should be in :attr:`var_names` or :attr:`obs`\\ `.columns`. + layer + What layer values should be returned from. If `None`, :attr:`X` is used. + + Returns + ------- + A one dimensional ndarray, with values for each obs in the same order + as :attr:`obs_names`. + """ + if layer == "X": + if "X" in self.layers: + pass + else: + msg = ( + "In a future version of AnnData, access to `.X` by passing" + " `layer='X'` will be removed. Instead pass `layer=None`." + ) + warnings.warn(msg, FutureWarning, stacklevel=2) + layer = None + return get_vector(self, k, "obs", "var", layer=layer) + + def var_vector(self, k, *, layer: str | None = None) -> np.ndarray: + """\ + Convenience function for returning a 1 dimensional ndarray of values + from :attr:`X`, :attr:`layers`\\ `[k]`, or :attr:`obs`. + + Made for convenience, not performance. Intentionally permissive about + arguments, for easy iterative use. + + Params + ------ + k + Key to use. Should be in :attr:`obs_names` or :attr:`var`\\ `.columns`. + layer + What layer values should be returned from. If `None`, :attr:`X` is used. + + Returns + ------- + A one dimensional ndarray, with values for each var in the same order + as :attr:`var_names`. + """ + if layer == "X": + if "X" in self.layers: + pass + else: + msg = ( + "In a future version of AnnData, access to `.X` by passing " + "`layer='X'` will be removed. Instead pass `layer=None`." + ) + warnings.warn(msg, FutureWarning, stacklevel=2) + layer = None + return get_vector(self, k, "var", "obs", layer=layer) + + @deprecated(Deprecation("0.6.21", "obs_vector is deprecated.")) + def _get_obs_array(self, k, use_raw=False, layer=None): # noqa: FBT002 + """\ + Get an array from the layer (default layer='X') along the :attr:`obs` + dimension by first looking up `obs.keys` and then :attr:`obs_names`. + """ + if not use_raw or k in self.obs.columns: + return self.obs_vector(k=k, layer=layer) + else: + return self.raw.obs_vector(k) + + @deprecated(Deprecation("0.6.21", "var_vector is deprecated.")) + def _get_var_array(self, k, use_raw=False, layer=None): # noqa: FBT002 + """\ + Get an array from the layer (default layer='X') along the :attr:`var` + dimension by first looking up `var.keys` and then :attr:`var_names`. + """ + if not use_raw or k in self.var.columns: + return self.var_vector(k=k, layer=layer) + else: + return self.raw.var_vector(k) + + def _mutated_copy(self, **kwargs): + """Creating AnnData with attributes optionally specified via kwargs.""" + if self.isbacked and ( + "X" not in kwargs or (self.raw is not None and "raw" not in kwargs) + ): + msg = ( + "This function does not currently handle backed objects " + "internally, this should be dealt with before." + ) + raise NotImplementedError(msg) + new = {} + + for key in ["obs", "var", "obsm", "varm", "obsp", "varp", "layers"]: + if key in kwargs: + new[key] = kwargs[key] + else: + new[key] = getattr(self, key).copy() + if "X" in kwargs: + new["X"] = kwargs["X"] + elif self._has_X(): + new["X"] = self.X.copy() + if "uns" in kwargs: + new["uns"] = kwargs["uns"] + else: + new["uns"] = deepcopy(self._uns) + if "raw" in kwargs: + new["raw"] = kwargs["raw"] + elif self.raw is not None: + new["raw"] = self.raw.copy() + return AnnData(**new) + + @old_positionals("copy") + def to_memory(self, *, copy: bool = False) -> AnnData: + """Return a new AnnData object with all non-in-memory arrays loaded into memory. + + Params + ------ + copy + Whether the arrays that are already in-memory should be copied. + + Example + ------- + + .. code:: python + + import anndata + backed = anndata.io.read_h5ad("file.h5ad", backed="r") + mem = backed[backed.obs["cluster"] == "a", :].to_memory() + """ + new = {} + for attr_name in [ + "X", + "obs", + "var", + "obsm", + "varm", + "obsp", + "varp", + "layers", + "uns", + ]: + attr = getattr(self, attr_name, None) + if attr is not None: + new[attr_name] = to_memory(attr, copy=copy) + + if self.raw is not None: + new["raw"] = { + "X": to_memory(self.raw.X, copy=copy), + "var": to_memory(self.raw.var, copy=copy), + "varm": to_memory(self.raw.varm, copy=copy), + } + + if self.isbacked: + self.file.close() + + return AnnData(**new) + + def copy(self, filename: PathLike[str] | str | None = None) -> AnnData: + """Full copy, optionally on disk.""" + if not self.isbacked: + if self.is_view and self._has_X(): + # TODO: How do I unambiguously check if this is a copy? + # Subsetting this way means we don’t have to have a view type + # defined for the matrix, which is needed for some of the + # current distributed backend. Specifically Dask. + return self._mutated_copy( + X=_subset(self._adata_ref.X, (self._oidx, self._vidx)).copy() + ) + return self._mutated_copy() + else: + from ..io import read_h5ad, write_h5ad + + if filename is None: + msg = ( + "To copy an AnnData object in backed mode, " + "pass a filename: `.copy(filename='myfilename.h5ad')`. " + "To load the object into memory, use `.to_memory()`." + ) + raise ValueError(msg) + mode = self.file._filemode + write_h5ad(filename, self) + return read_h5ad(filename, backed=mode) + + @deprecated( + Deprecation( + "0.10.3", + deprecation_msg( + "AnnData.concatenate", + "anndata.concat", + "See the tutorial for concat at: " + "https://anndata.readthedocs.io/en/latest/concatenation.html", + ), + ) + ) + @doctest_filterwarnings("ignore", r"The method concatenate.*", FutureWarning) + def concatenate( + self, + *adatas: AnnData, + join: str = "inner", + batch_key: str = "batch", + batch_categories: Sequence[Any] | None = None, + uns_merge: str | None = None, + index_unique: str | None = "-", + fill_value=None, + ) -> AnnData: + """\ + Concatenate along the observations axis. + + The :attr:`uns`, :attr:`varm` and :attr:`obsm` attributes are ignored. + + Currently, this works only in `'memory'` mode. + + .. note:: + + For more flexible and efficient concatenation, see: :func:`~anndata.concat`. + + Parameters + ---------- + adatas + AnnData matrices to concatenate with. Each matrix is referred to as + a “batch”. + join + Use intersection (`'inner'`) or union (`'outer'`) of variables. + batch_key + Add the batch annotation to :attr:`obs` using this key. + batch_categories + Use these as categories for the batch annotation. By default, use increasing numbers. + uns_merge + Strategy to use for merging entries of uns. These strategies are applied recusivley. + Currently implemented strategies include: + + * `None`: The default. The concatenated object will just have an empty dict for `uns`. + * `"same"`: Only entries which have the same value in all AnnData objects are kept. + * `"unique"`: Only entries which have one unique value in all AnnData objects are kept. + * `"first"`: The first non-missing value is used. + * `"only"`: A value is included if only one of the AnnData objects has a value at this + path. + index_unique + Make the index unique by joining the existing index names with the + batch category, using `index_unique='-'`, for instance. Provide + `None` to keep existing indices. + fill_value + Scalar value to fill newly missing values in arrays with. Note: only applies to arrays + and sparse matrices (not dataframes) and will only be used if `join="outer"`. + + .. note:: + If not provided, the default value is `0` for sparse matrices and `np.nan` + for numpy arrays. See the examples below for more information. + + Returns + ------- + :class:`~anndata.AnnData` + The concatenated :class:`~anndata.AnnData`, where `adata.obs[batch_key]` + stores a categorical variable labeling the batch. + + Notes + ----- + + .. warning:: + + If you use `join='outer'` this fills 0s for sparse data when + variables are absent in a batch. Use this with care. Dense data is + filled with `NaN`. See the examples. + + Examples + -------- + Joining on intersection of variables. + + >>> adata1 = AnnData( + ... np.array([[1, 2, 3], [4, 5, 6]]), + ... dict(obs_names=['s1', 's2'], anno1=['c1', 'c2']), + ... dict(var_names=['a', 'b', 'c'], annoA=[0, 1, 2]), + ... ) + >>> adata2 = AnnData( + ... np.array([[1, 2, 3], [4, 5, 6]]), + ... dict(obs_names=['s3', 's4'], anno1=['c3', 'c4']), + ... dict(var_names=['d', 'c', 'b'], annoA=[0, 1, 2]), + ... ) + >>> adata3 = AnnData( + ... np.array([[1, 2, 3], [4, 5, 6]]), + ... dict(obs_names=['s1', 's2'], anno2=['d3', 'd4']), + ... dict(var_names=['d', 'c', 'b'], annoA=[0, 2, 3], annoB=[0, 1, 2]), + ... ) + >>> adata = adata1.concatenate(adata2, adata3) + >>> adata + AnnData object with n_obs × n_vars = 6 × 2 + obs: 'anno1', 'anno2', 'batch' + var: 'annoA-0', 'annoA-1', 'annoA-2', 'annoB-2' + >>> adata.X + array([[2, 3], + [5, 6], + [3, 2], + [6, 5], + [3, 2], + [6, 5]]) + >>> adata.obs + anno1 anno2 batch + s1-0 c1 NaN 0 + s2-0 c2 NaN 0 + s3-1 c3 NaN 1 + s4-1 c4 NaN 1 + s1-2 NaN d3 2 + s2-2 NaN d4 2 + >>> adata.var.T + b c + annoA-0 1 2 + annoA-1 2 1 + annoA-2 3 2 + annoB-2 2 1 + + Joining on the union of variables. + + >>> outer = adata1.concatenate(adata2, adata3, join='outer') + >>> outer + AnnData object with n_obs × n_vars = 6 × 4 + obs: 'anno1', 'anno2', 'batch' + var: 'annoA-0', 'annoA-1', 'annoA-2', 'annoB-2' + >>> outer.var.T + a b c d + annoA-0 0.0 1.0 2.0 NaN + annoA-1 NaN 2.0 1.0 0.0 + annoA-2 NaN 3.0 2.0 0.0 + annoB-2 NaN 2.0 1.0 0.0 + >>> outer.var_names.astype("string") + Index(['a', 'b', 'c', 'd'], dtype='string') + >>> outer.X + array([[ 1., 2., 3., nan], + [ 4., 5., 6., nan], + [nan, 3., 2., 1.], + [nan, 6., 5., 4.], + [nan, 3., 2., 1.], + [nan, 6., 5., 4.]]) + >>> outer.X.sum(axis=0) + array([nan, 25., 23., nan]) + >>> import pandas as pd + >>> Xdf = pd.DataFrame(outer.X, columns=outer.var_names) + >>> Xdf + a b c d + 0 1.0 2.0 3.0 NaN + 1 4.0 5.0 6.0 NaN + 2 NaN 3.0 2.0 1.0 + 3 NaN 6.0 5.0 4.0 + 4 NaN 3.0 2.0 1.0 + 5 NaN 6.0 5.0 4.0 + >>> Xdf.sum() + a 5.0 + b 25.0 + c 23.0 + d 10.0 + dtype: float64 + + One way to deal with missing values is to use masked arrays: + + >>> from numpy import ma + >>> outer.X = ma.masked_invalid(outer.X) + >>> outer.X + masked_array( + data=[[1.0, 2.0, 3.0, --], + [4.0, 5.0, 6.0, --], + [--, 3.0, 2.0, 1.0], + [--, 6.0, 5.0, 4.0], + [--, 3.0, 2.0, 1.0], + [--, 6.0, 5.0, 4.0]], + mask=[[False, False, False, True], + [False, False, False, True], + [ True, False, False, False], + [ True, False, False, False], + [ True, False, False, False], + [ True, False, False, False]], + fill_value=1e+20) + >>> outer.X.sum(axis=0).data + array([ 5., 25., 23., 10.]) + + The masked array is not saved but has to be reinstantiated after saving. + + >>> outer.write('./test.h5ad') + >>> from anndata import read_h5ad + >>> outer = read_h5ad('./test.h5ad') + >>> outer.X + array([[ 1., 2., 3., nan], + [ 4., 5., 6., nan], + [nan, 3., 2., 1.], + [nan, 6., 5., 4.], + [nan, 3., 2., 1.], + [nan, 6., 5., 4.]]) + + For sparse data, everything behaves similarly, + except that for `join='outer'`, zeros are added. + + >>> from scipy.sparse import csr_matrix + >>> adata1 = AnnData( + ... csr_matrix([[0, 2, 3], [0, 5, 6]], dtype=np.float32), + ... dict(obs_names=['s1', 's2'], anno1=['c1', 'c2']), + ... dict(var_names=['a', 'b', 'c']), + ... ) + >>> adata2 = AnnData( + ... csr_matrix([[0, 2, 3], [0, 5, 6]], dtype=np.float32), + ... dict(obs_names=['s3', 's4'], anno1=['c3', 'c4']), + ... dict(var_names=['d', 'c', 'b']), + ... ) + >>> adata3 = AnnData( + ... csr_matrix([[1, 2, 0], [0, 5, 6]], dtype=np.float32), + ... dict(obs_names=['s5', 's6'], anno2=['d3', 'd4']), + ... dict(var_names=['d', 'c', 'b']), + ... ) + >>> adata = adata1.concatenate(adata2, adata3, join='outer') + >>> adata.var_names.astype("string") + Index(['a', 'b', 'c', 'd'], dtype='string') + >>> adata.X.toarray() + array([[0., 2., 3., 0.], + [0., 5., 6., 0.], + [0., 3., 2., 0.], + [0., 6., 5., 0.], + [0., 0., 2., 1.], + [0., 6., 5., 0.]], dtype=float32) + """ + from .merge import concat, merge_dataframes, merge_outer, merge_same + + if self.isbacked: + msg = "Currently, concatenate only works in memory mode." + raise ValueError(msg) + + if len(adatas) == 0: + return self.copy() + elif len(adatas) == 1 and not isinstance(adatas[0], AnnData): + adatas = adatas[0] # backwards compatibility + all_adatas = (self, *adatas) + + out = concat( + all_adatas, + axis=0, + join=join, + label=batch_key, + keys=batch_categories, + uns_merge=uns_merge, + fill_value=fill_value, + index_unique=index_unique, + pairwise=False, + ) + + # Backwards compat (some of this could be more efficient) + # obs used to always be an outer join + sparse_class = sparse.csr_matrix + if any(isinstance(a.X, CSArray) for a in all_adatas): + sparse_class = sparse.csr_array + out.obs = concat( + [AnnData(sparse_class(a.shape), obs=a.obs) for a in all_adatas], + axis=0, + join="outer", + label=batch_key, + keys=batch_categories, + index_unique=index_unique, + ).obs + # Removing varm + del out.varm + # Implementing old-style merging of var + if batch_categories is None: + batch_categories = np.arange(len(all_adatas)).astype(str) + pat = rf"-({'|'.join(batch_categories)})$" + out.var = merge_dataframes( + [a.var for a in all_adatas], + out.var_names, + partial(merge_outer, batch_keys=batch_categories, merge=merge_same), + ) + out.var = out.var.iloc[ + :, + ( + out.var.columns.str.extract(pat, expand=False) + .fillna("") + .argsort(kind="stable") + ), + ] + + return out + + def var_names_make_unique(self, join: str = "-") -> None: + # Important to go through the setter so obsm dataframes are updated too + self.var_names = utils.make_index_unique(self.var.index, join) + + var_names_make_unique.__doc__ = utils.make_index_unique.__doc__ + + def obs_names_make_unique(self, join: str = "-") -> None: + # Important to go through the setter so obsm dataframes are updated too + self.obs_names = utils.make_index_unique(self.obs.index, join) + + obs_names_make_unique.__doc__ = utils.make_index_unique.__doc__ + + def _check_uniqueness(self) -> None: + if self.obs.index[~self.obs.index.isna()].has_duplicates: + utils.warn_names_duplicates("obs") + if self.var.index[~self.var.index.isna()].has_duplicates: + utils.warn_names_duplicates("var") + + def __contains__(self, key: Any) -> NoReturn: + msg = "AnnData has no attribute __contains__, don’t check `in adata`." + raise AttributeError(msg) + + def _check_dimensions(self, key=None): + key = {"obsm", "varm"} if key is None else {key} + if "obsm" in key and ( + not all(axis_len(o, 0) == self.n_obs for o in self.obsm.values()) + and len(self.obsm.dim_names) != self.n_obs + ): + msg = ( + "Observations annot. `obsm` must have number of rows of `X`" + f" ({self.n_obs}), but has {len(self.obsm)} rows." + ) + raise ValueError(msg) + if "varm" in key and ( + not all(axis_len(v, 0) == self.n_vars for v in self.varm.values()) + and len(self.varm.dim_names) != self.n_vars + ): + msg = ( + "Variables annot. `varm` must have number of columns of `X`" + f" ({self.n_vars}), but has {len(self.varm)} rows." + ) + raise ValueError(msg) + + @old_positionals("compression", "compression_opts", "as_dense") + def write_h5ad( + self, + filename: PathLike[str] | str | None = None, + *, + convert_strings_to_categoricals: bool = True, + compression: Literal["gzip", "lzf"] | None = None, + compression_opts: int | Any = None, + as_dense: Sequence[str] = (), + ): + """\ + Write `.h5ad`-formatted hdf5 file. + + .. note:: + Setting compression to `'gzip'` can save disk space + but will slow down writing and subsequent reading. + Prior to v0.6.16, this was the default for parameter `compression`. + + Generally, if you have sparse data that are stored as a dense matrix, + you can dramatically improve performance and reduce disk space + by converting to a :class:`~scipy.sparse.csr_matrix`:: + + from scipy.sparse import csr_matrix + adata.X = csr_matrix(adata.X) + + Parameters + ---------- + filename + Filename of data file. Defaults to backing file. + convert_strings_to_categoricals + Convert string columns to categorical. + compression + For [`lzf`, `gzip`], see the h5py :ref:`dataset_compression`. + + Alternative compression filters such as `zstd` can be passed + from the :doc:`hdf5plugin ` library. + Experimental. + + Usage example:: + + import hdf5plugin + adata.write_h5ad( + filename, + compression=hdf5plugin.FILTERS["zstd"] + ) + + .. note:: + Datasets written with hdf5plugin-provided compressors + cannot be opened without first loading the hdf5plugin + library using `import hdf5plugin`. When using alternative + compression filters such as `zstd`, consider writing to + `zarr` format instead of `h5ad`, as the `zarr` library + provides a more transparent compression pipeline. + + compression_opts + For [`lzf`, `gzip`], see the h5py :ref:`dataset_compression`. + + Alternative compression filters such as `zstd` can be configured + using helpers from the :doc:`hdf5plugin ` + library. Experimental. + + Usage example (setting `zstd` compression level to 5):: + + import hdf5plugin + adata.write_h5ad( + filename, + compression=hdf5plugin.FILTERS["zstd"], + compression_opts=hdf5plugin.Zstd(clevel=5).filter_options + ) + + as_dense + Sparse arrays in AnnData object to write as dense. Currently only + supports `X` and `raw/X`. + """ + from ..io import write_h5ad + + if filename is None and not self.isbacked: + msg = "Provide a filename!" + raise ValueError(msg) + if filename is None: + filename = self.filename + + write_h5ad( + Path(filename), + self, + convert_strings_to_categoricals=convert_strings_to_categoricals, + compression=compression, + compression_opts=compression_opts, + as_dense=as_dense, + ) + # Only reset the filename if the AnnData object now points to a complete new copy + if self.isbacked and not self.is_view: + self.file.filename = filename + + write = write_h5ad # a shortcut and backwards compat + + @old_positionals("skip_data", "sep") + def write_csvs( + self, dirname: PathLike[str] | str, *, skip_data: bool = True, sep: str = "," + ): + """\ + Write annotation to `.csv` files. + + It is not possible to recover the full :class:`~anndata.AnnData` from + these files. Use :meth:`write` for this. + + Parameters + ---------- + dirname + Name of directory to which to export. + skip_data + Skip the data matrix :attr:`X`. + sep + Separator for the data. + """ + from ..io import write_csvs + + write_csvs(dirname, self, skip_data=skip_data, sep=sep) + + @old_positionals("write_obsm_varm") + def write_loom( + self, filename: PathLike[str] | str, *, write_obsm_varm: bool = False + ): + """\ + Write `.loom`-formatted hdf5 file. + + Parameters + ---------- + filename + The filename. + """ + from ..io import write_loom + + write_loom(filename, self, write_obsm_varm=write_obsm_varm) + + @old_positionals("chunks") + def write_zarr( + self, + store: StoreLike, + *, + chunks: tuple[int, ...] | None = None, + convert_strings_to_categoricals: bool = True, + ): + """\ + Write a hierarchical Zarr array store. + + Parameters + ---------- + store + The filename, a :class:`~typing.MutableMapping`, or a Zarr storage class. + chunks + Chunk shape. + convert_strings_to_categoricals + Convert string columns to categorical. + """ + from ..io import write_zarr + + # TODO: What is a bool for chunks supposed to do? + if isinstance(chunks, bool): + msg = ( + "Passing `write_zarr(adata, chunks=True)` is no longer supported. " + "Please pass `write_zarr(adata)` instead." + ) + raise ValueError(msg) + write_zarr( + store, + self, + chunks=chunks, + convert_strings_to_categoricals=convert_strings_to_categoricals, + ) + + def chunked_X(self, chunk_size: int | None = None): + """\ + Return an iterator over the rows of the data matrix :attr:`X`. + + Parameters + ---------- + chunk_size + Row size of a single chunk. + """ + if chunk_size is None: + # Should be some adaptive code + chunk_size = 6000 + start = 0 + n = self.n_obs + for _ in range(int(n // chunk_size)): + end = start + chunk_size + yield (self.X[start:end], start, end) + start = end + if start < n: + yield (self.X[start:n], start, n) + + @old_positionals("replace") + def chunk_X( + self, + select: int | Sequence[int] | np.ndarray = 1000, + *, + replace: bool = True, + ): + """\ + Return a chunk of the data matrix :attr:`X` with random or specified indices. + + Parameters + ---------- + select + Depending on the type: + + :class:`int` + A random chunk with `select` rows will be returned. + :term:`sequence` (e.g. a list, tuple or numpy array) of :class:`int` + A chunk with these indices will be returned. + + replace + If `select` is an integer then `True` means random sampling of + indices with replacement, `False` without replacement. + """ + if isinstance(select, int): + select = select if select < self.n_obs else self.n_obs + choice = np.random.choice(self.n_obs, select, replace) + elif isinstance(select, np.ndarray | Sequence): + choice = np.asarray(select) + else: + msg = "select should be int or array" + raise ValueError(msg) + + reverse = None + if self.isbacked: + # h5py can only slice with a sorted list of unique index values + # so random batch with indices [2, 2, 5, 3, 8, 10, 8] will fail + # this fixes the problem + indices, reverse = np.unique(choice, return_inverse=True) + selection = self.X[indices.tolist()] + else: + selection = self.X[choice] + + selection = selection.toarray() if issparse(selection) else selection + return selection if reverse is None else selection[reverse] + + def _has_X(self) -> bool: + """ + Check if X is None. + + This is more efficient than trying `adata.X is None` for views, since creating + views (at least anndata's kind) can be expensive. + """ + if not self.is_view: + return self.X is not None + else: + return self._adata_ref.X is not None + + # -------------------------------------------------------------------------- + # all of the following is for backwards compat + # -------------------------------------------------------------------------- + + @property + @deprecated(Deprecation("0.7.2", deprecation_msg("isview", "is_view"))) + def isview(self) -> bool: + """Whether or not this object is a view.""" + return self.is_view + + def _clean_up_old_format(self, uns): + # multicolumn keys + # all of the rest is only for backwards compat + for bases in [["obs", "smp"], ["var"]]: + axis = bases[0] + for k in [f"{p}{base}_keys_multicol" for p in ["", "_"] for base in bases]: + if uns and k in uns: + keys = list(uns[k]) + del uns[k] + break + else: + keys = [] + # now, for compat, fill the old multicolumn entries into obsm and varm + # and remove them from obs and var + m_attr = getattr(self, f"_{axis}m") + for key in keys: + m_attr[key] = self._get_and_delete_multicol_field(axis, key) + + def _get_and_delete_multicol_field(self, a, key_multicol): + keys = [k for k in getattr(self, a).columns if k.startswith(key_multicol)] + values = getattr(self, a)[keys].values + getattr(self, a).drop(keys, axis=1, inplace=True) + return values + + +@AnnData._remove_unused_categories.register(Dataset2D) +@staticmethod +def _remove_unused_categories_xr( + df_full: Dataset2D, df_sub: Dataset2D, uns: dict[str, Any] +): + pass # this is handled automatically by the categorical arrays themselves i.e., they dedup upon access. + + +def _check_2d_shape(X): + """\ + Check shape of array or sparse matrix. + + Assure that X is always 2D: Unlike numpy we always deal with 2D arrays. + """ + if X.dtype.names is None and len(X.shape) != 2: + msg = f"X needs to be 2-dimensional, not {len(X.shape)}-dimensional." + raise ValueError(msg) + + +def _infer_shape_for_axis( + xxx: pd.DataFrame | Mapping[str, Iterable[Any]] | None, + xxxm: np.ndarray | Mapping[str, Sequence[Any]] | None, + layers: Mapping[str, np.ndarray | sparse.spmatrix] | None, + xxxp: np.ndarray | Mapping[str, Sequence[Any]] | None, + axis: Literal[0, 1], +) -> int | None: + for elem in [xxx, xxxm, xxxp]: + if elem is not None and hasattr(elem, "shape"): + return elem.shape[0] + for elem, id in zip([layers, xxxm, xxxp], ["layers", "xxxm", "xxxp"], strict=True): + if elem is not None: + elem = cast("Mapping", elem) + for sub_elem in elem.values(): + if hasattr(sub_elem, "shape"): + size = cast("int", sub_elem.shape[axis if id == "layers" else 0]) + return size + return None + + +def _infer_shape( + obs: pd.DataFrame | Mapping[str, Iterable[Any]] | None = None, + var: pd.DataFrame | Mapping[str, Iterable[Any]] | None = None, + *, + obsm: np.ndarray | Mapping[str, Sequence[Any]] | None = None, + varm: np.ndarray | Mapping[str, Sequence[Any]] | None = None, + layers: Mapping[str, np.ndarray | sparse.spmatrix] | None = None, + obsp: np.ndarray | Mapping[str, Sequence[Any]] | None = None, + varp: np.ndarray | Mapping[str, Sequence[Any]] | None = None, +): + return ( + _infer_shape_for_axis(obs, obsm, layers, obsp, 0), + _infer_shape_for_axis(var, varm, layers, varp, 1), + ) diff --git a/.venv/lib/python3.11/site-packages/anndata/_core/extensions.py b/.venv/lib/python3.11/site-packages/anndata/_core/extensions.py new file mode 100644 index 0000000000000000000000000000000000000000..ba66c4964012c7c14815df6f46ef401e098ac14b --- /dev/null +++ b/.venv/lib/python3.11/site-packages/anndata/_core/extensions.py @@ -0,0 +1,25 @@ +from __future__ import annotations + +import warnings +from importlib.metadata import version + +from packaging.version import Version +from scverse_misc import make_register_namespace_decorator + +from .anndata import AnnData + +__all__ = ["register_anndata_namespace"] + + +if Version(version("scverse-misc")) > Version("0.1"): + register_anndata_namespace = make_register_namespace_decorator(AnnData, "adata") +else: + with warnings.catch_warnings(): + warnings.filterwarnings( + "ignore", + r".*argument is deprecated and will be removed in the future", + DeprecationWarning, + ) + register_anndata_namespace = make_register_namespace_decorator( + AnnData, "adata", "register_anndata_namespace", "numpy" + ) diff --git a/.venv/lib/python3.11/site-packages/anndata/_core/file_backing.py b/.venv/lib/python3.11/site-packages/anndata/_core/file_backing.py new file mode 100644 index 0000000000000000000000000000000000000000..e0c27416ec643ef9df48ae702e5ec56a02c92a25 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/anndata/_core/file_backing.py @@ -0,0 +1,211 @@ +from __future__ import annotations + +import weakref +from collections.abc import Mapping +from functools import singledispatch +from pathlib import Path, PurePosixPath +from typing import TYPE_CHECKING + +import h5py + +from ..compat import AwkArray, DaskArray, ZarrArray, ZarrGroup +from .sparse_dataset import BaseCompressedSparseDataset +from .xarray import Dataset2D + +if TYPE_CHECKING: + from collections.abc import Iterator + from os import PathLike + from typing import Literal + + from .._types import ArrayStorageType + from . import anndata + + +class AnnDataFileManager: + """Backing file manager for AnnData.""" + + def __init__( + self, + adata: anndata.AnnData, + file_name: PathLike[str] | str | None = None, + file_mode: Literal["r", "r+"] | None = None, + file_obj: h5py.File | None = None, + ): + if file_obj is not None and (file_name is not None or file_mode is not None): + msg = "Cannot provide both a h5py.File and the name and/or mode arguments to constructor" + raise ValueError(msg) + self._adata_ref = weakref.ref(adata) + if file_obj is not None: + self.filename = filename(file_obj) + self._filemode = file_obj.mode + self._file = file_obj + else: + self.filename = file_name + self._filemode = file_mode + self._file = file_obj + if file_name and not self._file: + self.open() + + def __getstate__(self): + state = self.__dict__.copy() + state["_adata_ref"] = state["_adata_ref"]() + return state + + def __setstate__(self, state): + self.__dict__ = state.copy() + self.__dict__["_adata_ref"] = weakref.ref(state["_adata_ref"]) + + @property + def _adata(self): + return self._adata_ref() + + def __repr__(self) -> str: + if self.filename is None: + return "Backing file manager: no file is set." + else: + return f"Backing file manager of file {self.filename}." + + def __contains__(self, x) -> bool: + return x in self._file + + def __iter__(self) -> Iterator[str]: + return iter(self._file) + + def __getitem__( + self, key: str + ) -> h5py.Group | h5py.Dataset | BaseCompressedSparseDataset: + return self._file[key] + + def __setitem__( + self, + key: str, + value: h5py.Group | h5py.Dataset | BaseCompressedSparseDataset, + ): + self._file[key] = value + + def __delitem__(self, key: str): + del self._file[key] + + @property + def filename(self) -> Path: + return self._filename + + @filename.setter + def filename(self, file_name: PathLike[str] | str | None): + self._filename = None if file_name is None else Path(file_name) + + def open( + self, + file_name: PathLike[str] | str | None = None, + filemode: Literal["r", "r+"] | None = None, + ): + if file_name is not None: + self.filename = file_name + if filemode is not None: + self._filemode = filemode + if self.filename is None: + msg = "Cannot open backing file if backing not initialized." + raise ValueError(msg) + self._file = h5py.File(self.filename, self._filemode) + + def close(self): + """Close the backing file, remember filename, do *not* change to memory mode.""" + if self._file is not None: + self._file.close() + + def _to_memory_mode(self): + """Close the backing file, forget filename, *do* change to memory mode.""" + self._adata._X = self._adata.X[()] + self._file.close() + self._file = None + self._filename = None + + @property + def is_open(self) -> bool: + """State of backing file.""" + if self._file is None: + return False + # try accessing the id attribute to see if the file is open + return bool(self._file.id) + + +@singledispatch +def to_memory(x, *, copy: bool = False): + """Permissivley convert objects to in-memory representation. + + If they already are in-memory, (or are just unrecognized) pass a copy through. + """ + if copy and hasattr(x, "copy"): + return x.copy() + else: + return x + + +@to_memory.register(ZarrArray) +@to_memory.register(h5py.Dataset) +def _(x: ArrayStorageType, *, copy: bool = False): + return x[...] + + +@to_memory.register(BaseCompressedSparseDataset) +def _(x: BaseCompressedSparseDataset, *, copy: bool = False): + return x.to_memory() + + +@to_memory.register(DaskArray) +def _(x: DaskArray, *, copy: bool = False): + return x.compute() + + +@to_memory.register(Mapping) +def _(x: Mapping, *, copy: bool = False): + return {k: to_memory(v, copy=copy) for k, v in x.items()} + + +@to_memory.register(AwkArray) +def _(x: AwkArray, *, copy: bool = False): + from copy import copy as _copy + + if copy: + return _copy(x) + else: + return x + + +@to_memory.register(Dataset2D) +def _(x: Dataset2D, *, copy: bool = False): + return x.to_memory(copy=copy) + + +@singledispatch +def filename(x): + msg = f"Not implemented for {type(x)}" + raise NotImplementedError(msg) + + +@filename.register(h5py.Group) +@filename.register(h5py.Dataset) +def _(x): + return x.file.filename + + +@filename.register(ZarrArray) +@filename.register(ZarrGroup) +def _(x): + return x.store.path + + +@singledispatch +def get_elem_name(x): + msg = f"Not implemented for {type(x)}" + raise NotImplementedError(msg) + + +@get_elem_name.register(h5py.Group) +def _(x): + return x.name + + +@get_elem_name.register(ZarrGroup) +def _(x): + return PurePosixPath(x.path).name diff --git a/.venv/lib/python3.11/site-packages/anndata/_core/index.py b/.venv/lib/python3.11/site-packages/anndata/_core/index.py new file mode 100644 index 0000000000000000000000000000000000000000..0a9ae4338454270d93bad3680737f060fcce1663 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/anndata/_core/index.py @@ -0,0 +1,368 @@ +from __future__ import annotations + +from collections.abc import Iterable, Sequence +from functools import singledispatch +from itertools import repeat +from typing import TYPE_CHECKING, cast, overload + +import h5py +import numpy as np +import pandas as pd +from scipy.sparse import issparse + +from ..compat import AwkArray, CSArray, CSMatrix, DaskArray, XDataArray +from .xarray import Dataset2D + +if TYPE_CHECKING: + from numpy.typing import NDArray + + from ..compat import Index, Index1D, Index1DNorm + + +def _normalize_indices( + index: Index | None, names0: pd.Index, names1: pd.Index +) -> tuple[Index1DNorm | int | np.integer, Index1DNorm | int | np.integer]: + # deal with tuples of length 1 + if isinstance(index, tuple) and len(index) == 1: + index = index[0] + ax0, ax1 = unpack_index(index) + ax0 = _normalize_index(ax0, names0) + ax1 = _normalize_index(ax1, names1) + return ax0, ax1 + + +def _normalize_index( # noqa: PLR0911, PLR0912 + indexer: Index1D, index: pd.Index +) -> Index1DNorm | int | np.integer: + # TODO: why is this here? All tests pass without it and it seems at the minimum not strict enough. + if not isinstance(index, pd.RangeIndex) and index.dtype in (np.float64, np.int64): + msg = f"Don’t call _normalize_index with non-categorical/string names and non-range index {index}" + raise TypeError(msg) + + if isinstance(indexer, pd.Index | pd.Series): + indexer = indexer.array + + # the following is insanely slow for sequences, + # we replaced it using pandas below + def name_idx(i): + if isinstance(i, str): + i = index.get_loc(i) + return i + + if isinstance(indexer, slice): + start = name_idx(indexer.start) + stop = name_idx(indexer.stop) + # string slices can only be inclusive, so +1 in that case + if isinstance(indexer.stop, str): + stop = None if stop is None else stop + 1 + step = indexer.step + return slice(start, stop, step) + elif isinstance(indexer, np.integer | int): + return indexer + elif isinstance(indexer, str): + return index.get_loc(indexer) # int + elif isinstance( + indexer, + Sequence + | np.ndarray + | pd.api.extensions.ExtensionArray + | CSMatrix + | np.matrix + | CSArray, + ): + if (shape := getattr(indexer, "shape", None)) is not None and ( + shape == (index.shape[0], 1) or shape == (1, index.shape[0]) + ): + if isinstance(indexer, CSMatrix | CSArray): + indexer = indexer.toarray() + indexer = np.ravel(indexer) + if not isinstance(indexer, np.ndarray): + indexer = np.array(indexer) + if len(indexer) == 0: + indexer = indexer.astype(int) + if isinstance(indexer, np.ndarray) and np.issubdtype( + indexer.dtype, np.floating + ): + indexer_int = indexer.astype(int) + if np.all((indexer - indexer_int) != 0): + msg = f"Indexer {indexer!r} has floating point values." + raise IndexError(msg) + if issubclass(indexer.dtype.type, np.integer | np.floating): + return indexer # Might not work for range indexes + elif issubclass(indexer.dtype.type, np.bool_): + if indexer.shape != index.shape: + msg = ( + f"Boolean index does not match AnnData’s shape along this " + f"dimension. Boolean index has shape {indexer.shape} while " + f"AnnData index has shape {index.shape}." + ) + raise IndexError(msg) + return indexer + else: # indexer should be string array + positions = index.get_indexer(indexer) + if np.any(positions < 0): + not_found = indexer[positions < 0] + msg = ( + f"Values {list(not_found)}, from {list(indexer)}, " + "are not valid obs/ var names or indices." + ) + raise KeyError(msg) + return positions # np.ndarray[int] + elif isinstance(indexer, XDataArray): + if isinstance(indexer.data, DaskArray): + return indexer.data.compute() + return indexer.data + msg = f"Unknown indexer {indexer!r} of type {type(indexer)}" + raise IndexError(msg) + + +def _fix_slice_bounds(s: slice, length: int) -> slice: + """The slice will be clipped to length, and the step won't be None. + + E.g. infer None valued attributes. + """ + step = s.step if s.step is not None else 1 + + # slice constructor would have errored if step was 0 + if step > 0: + start = s.start if s.start is not None else 0 + stop = s.stop if s.stop is not None else length + elif step < 0: + # Reverse + start = s.start if s.start is not None else length + stop = s.stop if s.stop is not None else 0 + + return slice(start, stop, step) + + +def unpack_index(index: Index) -> tuple[Index1D, Index1D]: + if not isinstance(index, tuple): + if index is Ellipsis: + index = slice(None) + return index, slice(None) + num_ellipsis = sum(i is Ellipsis for i in index) + if num_ellipsis > 1: + msg = "an index can only have a single ellipsis ('...')" + raise IndexError(msg) + # If index has Ellipsis, filter it out (and if not, error) + if len(index) > 2: + if not num_ellipsis: + msg = "Received a length 3 index without an ellipsis" + raise IndexError(msg) + index = tuple(i for i in index if i is not Ellipsis) + return index + # If index has Ellipsis, replace it with slice + if len(index) == 2: + index = tuple(slice(None) if i is Ellipsis else i for i in index) + return index + if len(index) == 1: + index = index[0] + if index is Ellipsis: + index = slice(None) + return index, slice(None) + msg = "invalid number of indices" + raise IndexError(msg) + + +@singledispatch +def _subset( + a: np.ndarray | pd.DataFrame, + subset_idx: tuple[Index1DNorm] | tuple[Index1DNorm, Index1DNorm], +): + # Select as combination of indexes, not coordinates + # Correcting for indexing behaviour of np.ndarray + if all(isinstance(x, Iterable) for x in subset_idx): + subset_idx = np.ix_(*subset_idx) + return a[subset_idx] + + +@_subset.register(DaskArray) +def _subset_dask( + a: DaskArray, subset_idx: tuple[Index1DNorm] | tuple[Index1DNorm, Index1DNorm] +): + if len(subset_idx) > 1 and all(isinstance(x, Iterable) for x in subset_idx): + if issparse(a._meta) and a._meta.format == "csc": + return a[:, subset_idx[1]][subset_idx[0], :] + return a[subset_idx[0], :][:, subset_idx[1]] + return a[subset_idx] + + +@_subset.register(CSMatrix) +@_subset.register(CSArray) +def _subset_sparse( + a: CSMatrix | CSArray, + subset_idx: tuple[Index1DNorm] | tuple[Index1DNorm, Index1DNorm], +): + # Correcting for indexing behaviour of sparse.spmatrix + if len(subset_idx) > 1 and all(isinstance(x, Iterable) for x in subset_idx): + first_idx = subset_idx[0] + if issubclass(first_idx.dtype.type, np.bool_): + first_idx = np.flatnonzero(first_idx) + subset_idx = (first_idx.reshape(-1, 1), *subset_idx[1:]) + return a[subset_idx] + + +@_subset.register(pd.DataFrame) +@_subset.register(Dataset2D) +def _subset_df( + df: pd.DataFrame | Dataset2D, + subset_idx: tuple[Index1DNorm] | tuple[Index1DNorm, Index1DNorm], +): + return df.iloc[subset_idx] + + +@_subset.register(AwkArray) +def _subset_awkarray( + a: AwkArray, subset_idx: tuple[Index1DNorm] | tuple[Index1DNorm, Index1DNorm] +): + if all(isinstance(x, Iterable) for x in subset_idx): + subset_idx = np.ix_(*subset_idx) + return a[subset_idx] + + +# Registration for SparseDataset occurs in sparse_dataset.py +@_subset.register(h5py.Dataset) +def _subset_dataset( + d: h5py.Dataset, subset_idx: tuple[Index1DNorm] | tuple[Index1DNorm, Index1DNorm] +): + order: tuple[NDArray[np.integer] | slice, ...] + inv_order: tuple[NDArray[np.integer] | slice, ...] + order, inv_order = zip(*map(_index_order_and_inverse, subset_idx), strict=True) + # check for duplicates or multi-dimensional fancy indexing + array_dims = [i for i in order if isinstance(i, np.ndarray)] + has_duplicates = any(len(np.unique(i)) != len(i) for i in array_dims) + # Use safe indexing if there are duplicates OR multiple array dimensions + # (h5py doesn't support multi-dimensional fancy indexing natively) + if has_duplicates or len(array_dims) > 1: + # For multi-dimensional indexing, bypass the sorting logic and use original indices + return _safe_fancy_index_h5py(d, subset_idx) + # from hdf5, then to real order + return d[order][inv_order] + + +@overload +def _index_order_and_inverse( + axis_idx: NDArray[np.integer] | NDArray[np.bool_], +) -> tuple[NDArray[np.integer], NDArray[np.integer]]: ... +@overload +def _index_order_and_inverse(axis_idx: slice) -> tuple[slice, slice]: ... +def _index_order_and_inverse( + axis_idx: Index1DNorm, +) -> tuple[Index1DNorm, NDArray[np.integer] | slice]: + """Order and get inverse index array.""" + if not isinstance(axis_idx, np.ndarray): + return axis_idx, slice(None) + if axis_idx.dtype == bool: + axis_idx = np.flatnonzero(axis_idx) + order = np.argsort(axis_idx) + return axis_idx[order], np.argsort(order) + + +@overload +def _process_index_for_h5py( + idx: NDArray[np.integer] | NDArray[np.bool_], +) -> tuple[NDArray[np.integer], NDArray[np.integer]]: ... +@overload +def _process_index_for_h5py(idx: slice) -> tuple[slice, None]: ... +def _process_index_for_h5py( + idx: Index1DNorm, +) -> tuple[Index1DNorm, NDArray[np.integer] | None]: + """Process a single index for h5py compatibility, handling sorting and duplicates.""" + if not isinstance(idx, np.ndarray): + # Not an array (slice, integer, list) - no special processing needed + return idx, None + + if idx.dtype == bool: + idx = np.flatnonzero(idx) + + # For h5py fancy indexing, we need sorted indices + # But we also need to track how to reverse the sorting + unique, inverse = np.unique(idx, return_inverse=True) + return ( + # Has duplicates - use unique + inverse mapping approach + (unique, inverse) + if len(unique) != len(idx) + # No duplicates - just sort and track reverse mapping + else _index_order_and_inverse(idx) + ) + + +def _safe_fancy_index_h5py( + dataset: h5py.Dataset, + subset_idx: tuple[Index1DNorm] | tuple[Index1DNorm, Index1DNorm], +) -> h5py.Dataset: + # Handle multi-dimensional indexing of h5py dataset + # This avoids h5py's limitation with multi-dimensional fancy indexing + # without loading the entire dataset into memory + + # Convert boolean arrays to integer arrays and handle sorting for h5py + processed_indices: tuple[NDArray[np.integer] | slice, ...] + reverse_indices: tuple[NDArray[np.integer] | None, ...] + processed_indices, reverse_indices = zip( + *map(_process_index_for_h5py, subset_idx), strict=True + ) + + # First find the index that reduces the size of the dataset the most + i_min = np.argmin([ + _get_index_size(inds, dataset.shape[i]) / dataset.shape[i] + for i, inds in enumerate(processed_indices) + ]) + + # Apply the most selective index first to h5py dataset + first_index = [slice(None)] * len(processed_indices) + first_index[i_min] = processed_indices[i_min] + in_memory_array = cast("np.ndarray", dataset[tuple(first_index)]) + + # Apply remaining indices to the numpy array + remaining_indices = list(processed_indices) + remaining_indices[i_min] = slice(None) # Already applied + result = in_memory_array[tuple(remaining_indices)] + + # Now apply reverse mappings to get the original order + for dim, reverse_map in enumerate(reverse_indices): + if reverse_map is not None: + result = result.take(reverse_map, axis=dim) + + return result + + +def _get_index_size(idx: Index1DNorm, dim_size: int) -> int: + """Get size for any index type.""" + if isinstance(idx, slice): + return len(range(*idx.indices(dim_size))) + elif isinstance(idx, int): + return 1 + else: # For other types, try to get length + return len(idx) + + +def make_slice(idx, dimidx: int, n: int = 2) -> tuple[slice, ...]: + mut = list(repeat(slice(None), n)) + mut[dimidx] = idx + return tuple(mut) + + +def get_vector(adata, k, coldim, idxdim, layer=None): + # adata could be self if Raw and AnnData shared a parent + dims = ("obs", "var") + col = getattr(adata, coldim).columns + idx = getattr(adata, f"{idxdim}_names") + + in_col = k in col + in_idx = k in idx + + if (in_col + in_idx) == 2: + msg = f"Key {k} could be found in both .{idxdim}_names and .{coldim}.columns" + raise ValueError(msg) + elif (in_col + in_idx) == 0: + msg = f"Could not find key {k} in .{idxdim}_names or .{coldim}.columns." + raise KeyError(msg) + elif in_col: + return getattr(adata, coldim)[k].values + elif in_idx: + selected_dim = dims.index(idxdim) + idx = adata._normalize_indices(make_slice(k, selected_dim)) + a = adata._get_X(layer=layer)[idx] + if issparse(a): + a = a.toarray() + return np.ravel(a) diff --git a/.venv/lib/python3.11/site-packages/anndata/_core/merge.py b/.venv/lib/python3.11/site-packages/anndata/_core/merge.py new file mode 100644 index 0000000000000000000000000000000000000000..69b23019c92d94b874d55f693464c309e19c37eb --- /dev/null +++ b/.venv/lib/python3.11/site-packages/anndata/_core/merge.py @@ -0,0 +1,1819 @@ +""" +Code for merging/ concatenating AnnData objects. +""" + +from __future__ import annotations + +import uuid +import warnings +from collections import OrderedDict +from collections.abc import Callable, Mapping, MutableSet +from functools import partial, reduce, singledispatch +from itertools import repeat +from operator import and_, or_, sub +from typing import TYPE_CHECKING, Literal, TypeVar, cast +from warnings import warn + +import numpy as np +import pandas as pd +from natsort import natsorted +from scipy import sparse + +from anndata._core.file_backing import to_memory +from anndata._warnings import ExperimentalFeatureWarning + +from ..compat import ( + AwkArray, + CSArray, + CSMatrix, + CupyArray, + CupyCSRMatrix, + CupySparseMatrix, + DaskArray, +) +from ..utils import asarray, axis_len, warn_once +from .anndata import AnnData +from .index import _subset, make_slice +from .xarray import Dataset2D + +if TYPE_CHECKING: + from collections.abc import Collection, Generator, Iterable, Sequence + from typing import Any + + from numpy.typing import NDArray + from pandas.api.extensions import ExtensionDtype + + from anndata._types import Join_T + + from ..compat import XDataArray + +T = TypeVar("T") + +################### +# Utilities +################### + + +# Pretty much just for maintaining order of keys +class OrderedSet(MutableSet): + def __init__(self, vals=()): + self.dict = OrderedDict(zip(vals, repeat(None))) + + def __contains__(self, val): + return val in self.dict + + def __iter__(self): + return iter(self.dict) + + def __len__(self): + return len(self.dict) + + def __repr__(self): + return "OrderedSet: {" + ", ".join(map(str, self)) + "}" + + def copy(self): + return OrderedSet(self.dict.copy()) + + def add(self, val): + self.dict[val] = None + + def union(self, *vals) -> OrderedSet: + return reduce(or_, vals, self) + + def discard(self, val): + if val in self: + del self.dict[val] + + def difference(self, *vals) -> OrderedSet: + return reduce(sub, vals, self) + + +def union_keys(ds: Collection) -> OrderedSet: + return reduce(or_, ds, OrderedSet()) + + +def intersect_keys(ds: Collection) -> OrderedSet: + return reduce(and_, map(OrderedSet, ds)) + + +class MissingVal: + """Represents a missing value.""" + + +def is_missing(v) -> bool: + return v is MissingVal + + +def not_missing(v) -> bool: + return v is not MissingVal + + +# We need to be able to check for equality of arrays to know which are the same. +# Unfortunately equality of arrays is poorly defined. +# * `np.array_equal` does not work for sparse arrays +# * `np.array_equal(..., equal_nan=True)` does not work for null values at the moment +# (see https://github.com/numpy/numpy/issues/16377) +# So we have to define it ourselves with these two issues in mind. +# TODO: Hopefully this will stop being an issue in the future and this code can be removed. +@singledispatch +def equal(a, b) -> bool: + a = asarray(a) + b = asarray(b) + if a.ndim == b.ndim == 0: + return bool(a == b) + a_na = ( + pd.isna(a) if a.dtype.names is None else np.False_ + ) # pd.isna doesn't work for record arrays + b_na = pd.isna(b) if b.dtype.names is None else np.False_ + return np.array_equal(a_na, b_na) and np.array_equal(a[~a_na], b[~b_na]) + + +@equal.register(pd.DataFrame) +@equal.register(Dataset2D) +@equal.register(pd.Series) +def equal_dataframe(a, b) -> bool: + return a.equals(b) + + +@equal.register(DaskArray) +def equal_dask_array(a, b) -> bool: + import dask.array as da + from dask.base import tokenize + + if a is b: + return True + if a.shape != b.shape: + return False + if isinstance(b, DaskArray) and tokenize(a) == tokenize(b): + return True + if isinstance(a._meta, np.ndarray): + return da.equal(a, b, where=~(da.isnan(a) & da.isnan(b))).all().compute() + if a.chunksize == b.chunksize and isinstance( + a._meta, CupySparseMatrix | CSMatrix | CSArray + ): + # TODO: Maybe also do this in the other case? + return da.map_blocks(equal, a, b, drop_axis=(0, 1)).all() + msg = "Misaligned chunks detected when checking for merge equality of dask arrays. Reading full arrays into memory." + warn(msg, UserWarning, stacklevel=3) + return equal(a.compute(), b.compute()) + + +@equal.register(np.ndarray) +def equal_array(a, b) -> bool: + # Reshaping allows us to compare inputs with >2 dimensions + # We cast to pandas since it will still work with non-numeric types + b = asarray(b) + if a.shape != b.shape: + return False + + return equal(pd.DataFrame(a.reshape(-1)), pd.DataFrame(b.reshape(-1))) + + +@equal.register(CupyArray) +def equal_cupyarray(a, b) -> bool: + import cupy as cp + + return bool(cp.array_equal(a, b, equal_nan=True)) + + +@equal.register(CSMatrix) +@equal.register(CSArray) +@equal.register(CupySparseMatrix) +def equal_sparse(a, b) -> bool: + # It's a weird api, don't blame me + import array_api_compat + + xp = array_api_compat.array_namespace(a.data) + + if isinstance(b, CupySparseMatrix | CSMatrix | CSArray): + if isinstance(a, CupySparseMatrix): + # Comparison broken for CSC matrices + # https://github.com/cupy/cupy/issues/7757 + a, b = CupyCSRMatrix(a), CupyCSRMatrix(b) + comp = a != b + if isinstance(comp, bool): + return not comp + if isinstance(comp, CupySparseMatrix): + # https://github.com/cupy/cupy/issues/7751 + comp = comp.get() + # fmt: off + return ( + (len(comp.data) == 0) + or ( + xp.isnan(a[comp]).all() + and xp.isnan(b[comp]).all() + ) + ) + # fmt: on + else: + return False + + +@equal.register(AwkArray) +def equal_awkward(a, b) -> bool: + from ..compat import awkward as ak + + return ak.almost_equal(a, b) + + +def as_sparse(x, *, use_sparse_array: bool = False) -> CSMatrix | CSArray: + if not isinstance(x, CSMatrix | CSArray): + in_memory_array_class = ( + sparse.csr_array if use_sparse_array else sparse.csr_matrix + ) + if isinstance(x, DaskArray): + x = x.map_blocks( + sparse.csr_matrix, + meta=sparse.csr_matrix(x._meta), + dtype=x.dtype, + ).compute() + return in_memory_array_class(x) + return x + + +def as_cp_sparse(x) -> CupySparseMatrix: + import cupyx.scipy.sparse as cpsparse + + if isinstance(x, cpsparse.spmatrix): + return x + elif isinstance(x, np.ndarray): + return cpsparse.csr_matrix(as_sparse(x)) + else: + return cpsparse.csr_matrix(x) + + +def unify_dtypes( + dfs: Iterable[pd.DataFrame | Dataset2D], +) -> list[pd.DataFrame | Dataset2D]: + """Attempt to unify datatypes from multiple dataframes. + + For catching cases where pandas would convert to object dtype. + """ + dfs = list(dfs) + # Get shared categorical columns + df_dtypes = [ + cast("pd.Series[ExtensionDtype]", df.dtypes).to_dict() + if isinstance(df, pd.DataFrame) + else df.dtypes + for df in dfs + ] + columns = reduce(lambda x, y: x.union(y), [df.columns for df in dfs]) + dtypes = { + col: ( + [df[col] for df in df_dtypes if col in df], + any(col not in df for df in df_dtypes), + ) + for col in columns + } + if len(dtypes) == 0: + return dfs + + new_dtypes = { + col: target_dtype + for col, (dts, has_missing) in dtypes.items() + if (target_dtype := try_unifying_dtype(dts, has_missing=has_missing)) + is not None + } + + dfs = [df.copy(deep=False) for df in dfs] + for df in dfs: + for col, dtype in new_dtypes.items(): + if col in df: + df[col] = df[col].astype(dtype) + return dfs + + +def try_unifying_dtype( + dtypes: Sequence[np.dtype | ExtensionDtype], *, has_missing: bool +) -> ExtensionDtype | type[object] | None: + """Determine unified dtype if possible. + + Returns None if they can’t be unified, or if we can expect pandas to unify them for us. + + Params + ------ + dtypes + A list of dtypes to unify. Can be numpy or pandas dtypes + has_missing + Whether the result needs to accommodate missing values + """ + # Categorical + if any(isinstance(dtype, pd.CategoricalDtype) for dtype in dtypes): + if not all(isinstance(dtype, pd.CategoricalDtype) for dtype in dtypes): + return None + if TYPE_CHECKING: + dtypes = cast("Sequence[pd.CategoricalDtype]", dtypes) + + all_categories = reduce( + lambda x, y: x.union(y), (dtype.categories for dtype in dtypes) + ) + if not any(dtype.ordered for dtype in dtypes): + return pd.CategoricalDtype(natsorted(all_categories), ordered=False) + + dtypes_with_categories = [ + dtype for dtype in dtypes if len(dtype.categories) > 0 + ] + if dtypes_with_categories and all( + len(dtype.categories) == len(all_categories) + and dtype.ordered + and np.all(all_categories == dtype.categories) + for dtype in dtypes_with_categories + ): + return dtypes_with_categories[0] + + return object + + # Boolean + if all(pd.api.types.is_bool_dtype(dtype) for dtype in dtypes) and has_missing: + return pd.BooleanDtype() + + return None + + +def check_combinable_cols(cols: list[pd.Index], join: Join_T): + """Given columns for a set of dataframes, checks if the can be combined. + + Looks for if there are duplicated column names that would show up in the result. + """ + repeated_cols = reduce(lambda x, y: x.union(y[y.duplicated()]), cols, set()) + if join == "inner": + intersecting_cols = intersect_keys(cols) + problem_cols = repeated_cols.intersection(intersecting_cols) + elif join == "outer": + problem_cols = repeated_cols + else: + raise ValueError() + + if len(problem_cols) > 0: + problem_cols = list(problem_cols) + msg = ( + f"Cannot combine dataframes as some contained duplicated column names - " + "causing ambiguity.\n\n" + f"The problem columns are: {problem_cols}" + ) + raise pd.errors.InvalidIndexError(msg) + + +# TODO: open PR or feature request to cupy +def _cp_block_diag(mats, format=None, dtype=None): + """ + Modified version of scipy.sparse.block_diag for cupy sparse. + """ + import cupy as cp + from cupyx.scipy import sparse as cpsparse + + row = [] + col = [] + data = [] + r_idx = 0 + c_idx = 0 + for a in mats: + # if isinstance(a, (list, numbers.Number)): + # a = cpsparse.coo_matrix(a) + nrows, ncols = a.shape + if cpsparse.issparse(a): + a = a.tocoo() + row.append(a.row + r_idx) + col.append(a.col + c_idx) + data.append(a.data) + else: + a_row, a_col = cp.divmod(cp.arange(nrows * ncols), ncols) + row.append(a_row + r_idx) + col.append(a_col + c_idx) + data.append(a.reshape(-1)) + r_idx += nrows + c_idx += ncols + row = cp.concatenate(row) + col = cp.concatenate(col) + data = cp.concatenate(data) + return cpsparse.coo_matrix( + (data, (row, col)), shape=(r_idx, c_idx), dtype=dtype + ).asformat(format) + + +def _dask_block_diag(mats): + from itertools import permutations + + import dask.array as da + + blocks = np.zeros((len(mats), len(mats)), dtype=object) + for i, j in permutations(range(len(mats)), 2): + blocks[i, j] = da.from_array( + sparse.csr_matrix((mats[i].shape[0], mats[j].shape[1])) + ) + for i, x in enumerate(mats): + if not isinstance(x._meta, sparse.csr_matrix): + x = x.map_blocks(sparse.csr_matrix) + blocks[i, i] = x + + return da.block(blocks.tolist()) + + +################### +# Per element logic +################### + + +def unique_value(vals: Collection[T]) -> T | MissingVal: + """ + Given a collection vals, returns the unique value (if one exists), otherwise + returns MissingValue. + """ + unique_val = vals[0] + for v in vals[1:]: + if not equal(v, unique_val): + return MissingVal + return unique_val + + +def first(vals: Collection[T]) -> T | MissingVal: + """ + Given a collection of vals, return the first non-missing one.If they're all missing, + return MissingVal. + """ + for val in vals: + if not_missing(val): + return val + return MissingVal + + +def only(vals: Collection[T]) -> T | MissingVal: + """Return the only value in the collection, otherwise MissingVal.""" + if len(vals) == 1: + return vals[0] + else: + return MissingVal + + +################### +# Merging +################### + + +def merge_nested(ds: Collection[Mapping], keys_join: Callable, value_join: Callable): + out = {} + for k in keys_join(ds): + v = _merge_nested(ds, k, keys_join, value_join) + if not_missing(v): + out[k] = v + return out + + +def _merge_nested( + ds: Collection[Mapping], k, keys_join: Callable, value_join: Callable +): + vals = [d[k] for d in ds if k in d] + if len(vals) == 0: + return MissingVal + elif all(isinstance(v, Mapping) and not isinstance(v, Dataset2D) for v in vals): + new_map = merge_nested(vals, keys_join, value_join) + if len(new_map) == 0: + return MissingVal + else: + return new_map + else: + return value_join(vals) + + +def merge_unique(ds: Collection[Mapping]) -> Mapping: + return merge_nested(ds, union_keys, unique_value) + + +def merge_same(ds: Collection[Mapping]) -> Mapping: + return merge_nested(ds, intersect_keys, unique_value) + + +def merge_first(ds: Collection[Mapping]) -> Mapping: + return merge_nested(ds, union_keys, first) + + +def merge_only(ds: Collection[Mapping]) -> Mapping: + return merge_nested(ds, union_keys, only) + + +################### +# Interface +################### + +# Leaving out for now, it's ugly in the rendered docs and would be adding a dependency. +# from typing_extensions import Literal +# UNS_STRATEGIES_TYPE = Literal[None, "same", "unique", "first", "only"] +MERGE_STRATEGIES = { + None: lambda x: {}, + "same": merge_same, + "unique": merge_unique, + "first": merge_first, + "only": merge_only, +} + +StrategiesLiteral = Literal["same", "unique", "first", "only"] + + +def resolve_merge_strategy( + strategy: str | Callable | None, +) -> Callable[[Collection[Mapping]], Mapping]: + if not isinstance(strategy, Callable): + strategy = MERGE_STRATEGIES[strategy] + return strategy + + +##################### +# Concatenation +##################### + + +class Reindexer: + """ + Indexing to be applied to axis of 2d array orthogonal to the axis being concatenated. + + Attrs + ----- + old_idx + Original index + new_idx + Target index + old_pos + Indices of original index which will be kept + new_pos + Indices of new index which data from old_pos will be placed in. + Together with `old_pos` this forms a mapping. + """ + + def __init__(self, old_idx: pd.Index, new_idx: pd.Index) -> None: + self.old_idx = old_idx + self.new_idx = new_idx + self.no_change = new_idx.equals(old_idx) + + new_pos = new_idx.get_indexer(old_idx) + old_pos = np.arange(len(new_pos)) + + mask = new_pos != -1 + + self.new_pos = new_pos[mask] + self.old_pos = old_pos[mask] + + def __call__(self, el, *, axis=1, fill_value=None): + return self.apply(el, axis=axis, fill_value=fill_value) + + def apply(self, el, *, axis, fill_value=None): # noqa: PLR0911 + """ + Reindex element so el[axis] is aligned to self.new_idx. + + Missing values are to be replaced with `fill_value`. + """ + if self.no_change and (axis_len(el, axis) == len(self.old_idx)): + return el + if isinstance(el, pd.DataFrame | Dataset2D): + return self._apply_to_df_like(el, axis=axis, fill_value=fill_value) + elif isinstance(el, CSMatrix | CSArray | CupySparseMatrix): + return self._apply_to_sparse(el, axis=axis, fill_value=fill_value) + elif isinstance(el, AwkArray): + return self._apply_to_awkward(el, axis=axis, fill_value=fill_value) + elif isinstance(el, DaskArray): + return self._apply_to_dask_array(el, axis=axis, fill_value=fill_value) + elif isinstance(el, CupyArray): + return self._apply_to_cupy_array(el, axis=axis, fill_value=fill_value) + else: + return self._apply_to_array(el, axis=axis, fill_value=fill_value) + + def _apply_to_df_like(self, el: pd.DataFrame | Dataset2D, *, axis, fill_value=None): + if fill_value is None: + fill_value = np.nan + return el.reindex(self.new_idx, axis=axis, fill_value=fill_value) + + def _apply_to_dask_array(self, el: DaskArray, *, axis, fill_value=None): + import dask.array as da + + indexer = self.idx + is_outer = any(indexer == -1) + # Fast path for the majority of sparse matrices whose minor-axis is unchunked and is being reindexed. + # This prevents 0's from being stored explicitly in the sparse matrices when outer joining, for example (see below). + if ( + is_sparse_sub := isinstance(el._meta, CSArray | CSMatrix) + and el.chunksize[minor_axis := int(el._meta.format == "csr")] + == el.shape[minor_axis] + and axis == minor_axis + and is_outer + ): + return el.map_blocks( + partial( + self._apply_to_sparse, + axis=axis, + fill_value=fill_value, + keep_format=True, + ), + chunks=(el.chunks[0], len(self.new_idx)) + if minor_axis == 1 + else (len(self.new_idx), el.chunks[1]), + meta=el._meta, + ) + if fill_value is None: + fill_value = default_fill_value([el]) + shape = list(el.shape) + if el.shape[axis] == 0: + # Presumably faster since it won't allocate the full array + shape[axis] = len(self.new_idx) + return da.broadcast_to(fill_value, tuple(shape)) + + sub_el = _subset(el, make_slice(indexer, axis, len(shape))) + + if is_outer: + # TODO: Remove this condition once https://github.com/dask/dask/pull/12078 is released + if is_sparse_sub and np.isscalar(fill_value): + fill_value = np.array([[fill_value]]) + sub_el[make_slice(indexer == -1, axis, len(shape))] = fill_value + + return sub_el + + def _apply_to_cupy_array(self, el, *, axis, fill_value=None): + import cupy as cp + + if fill_value is None: + fill_value = default_fill_value([el]) + if el.shape[axis] == 0: + # Presumably faster since it won't allocate the full array + shape = list(el.shape) + shape[axis] = len(self.new_idx) + return cp.broadcast_to(cp.asarray(fill_value), tuple(shape)) + + old_idx_tuple = [slice(None)] * len(el.shape) + old_idx_tuple[axis] = self.old_pos + old_idx_tuple = tuple(old_idx_tuple) + new_idx_tuple = [slice(None)] * len(el.shape) + new_idx_tuple[axis] = self.new_pos + new_idx_tuple = tuple(new_idx_tuple) + + out_shape = list(el.shape) + out_shape[axis] = len(self.new_idx) + + out = cp.full(tuple(out_shape), fill_value) + out[new_idx_tuple] = el[old_idx_tuple] + + return out + + def _apply_to_array(self, el, *, axis, fill_value=None): + if fill_value is None: + fill_value = default_fill_value([el]) + if el.shape[axis] == 0: + # Presumably faster since it won't allocate the full array + shape = list(el.shape) + shape[axis] = len(self.new_idx) + return np.broadcast_to(fill_value, tuple(shape)) + + indexer = self.idx + + # Indexes real fast, and does outer indexing + return pd.api.extensions.take( + el, indexer, axis=axis, allow_fill=True, fill_value=fill_value + ) + + def _apply_to_sparse( # noqa: PLR0912 + self, el: CSMatrix | CSArray, *, axis, fill_value=None, keep_format: bool = True + ) -> CSMatrix: + if isinstance(el, CupySparseMatrix): + from cupyx.scipy import sparse + else: + from scipy import sparse + import array_api_compat + + xp = array_api_compat.array_namespace(el.data) + + if fill_value is None: + fill_value = default_fill_value([el]) + if fill_value != 0: + to_fill = self.new_idx.get_indexer(self.new_idx.difference(self.old_idx)) + else: + to_fill = xp.array([]) + + # Fixing outer indexing for missing values + if el.shape[axis] == 0: + shape = list(el.shape) + shape[axis] = len(self.new_idx) + shape = tuple(shape) + if fill_value == 0: + if isinstance(el, CSArray): + memory_class = sparse.csr_array + else: + memory_class = sparse.csr_matrix + return memory_class(shape) + else: + return type(el)(xp.broadcast_to(xp.asarray(fill_value), shape)) + + fill_idxer = None + + if len(to_fill) > 0 or isinstance(el, CupySparseMatrix): + idxmtx_dtype = xp.promote_types(el.dtype, xp.array(fill_value).dtype) + else: + idxmtx_dtype = bool + if isinstance(el, CSArray): + memory_class = sparse.coo_array + else: + memory_class = sparse.coo_matrix + if axis == 1: + idxmtx = memory_class( + ( + xp.ones(len(self.new_pos), dtype=idxmtx_dtype), + (xp.asarray(self.old_pos), xp.asarray(self.new_pos)), + ), + shape=(len(self.old_idx), len(self.new_idx)), + dtype=idxmtx_dtype, + ) + out = el @ idxmtx + + if len(to_fill) > 0: + out = out.tocsc() + fill_idxer = (slice(None), to_fill) + elif axis == 0: + idxmtx = memory_class( + ( + xp.ones(len(self.new_pos), dtype=idxmtx_dtype), + (xp.asarray(self.new_pos), xp.asarray(self.old_pos)), + ), + shape=(len(self.new_idx), len(self.old_idx)), + dtype=idxmtx_dtype, + ) + out = idxmtx @ el + + if len(to_fill) > 0: + out = out.tocsr() + fill_idxer = (to_fill, slice(None)) + + if fill_idxer is not None: + out[fill_idxer] = fill_value + if keep_format: + out = out.tocsr() if el.format == "csr" else out.tocsc() + return out + + def _apply_to_awkward(self, el: AwkArray, *, axis, fill_value=None): + import awkward as ak + + if self.no_change: + return el + elif axis == 1: # Indexing by field + if self.new_idx.isin(self.old_idx).all(): # inner join + return el[self.new_idx] + else: # outer join + # TODO: this code isn't actually hit, we should refactor + msg = "This should be unreachable, please open an issue." + raise Exception(msg) + else: + if len(self.new_idx) > len(self.old_idx): + el = ak.pad_none(el, 1, axis=axis) # axis == 0 + return el[self.idx] + + @property + def idx(self) -> NDArray[np.intp]: + return self.old_idx.get_indexer(self.new_idx) + + +def merge_indices(inds: Iterable[pd.Index], join: Join_T) -> pd.Index: + if join == "inner": + return reduce(lambda x, y: x.intersection(y), inds) + elif join == "outer": + return reduce(lambda x, y: x.union(y), inds) + else: + msg = f"`join` must be one of 'inner' or 'outer', got {join!r}" + raise ValueError(msg) + + +def default_fill_value(els): + """Given some arrays, returns what the default fill value should be. + + This is largely due to backwards compat, and might not be the ideal solution. + """ + if any( + isinstance(el, CSMatrix | CSArray) + or (isinstance(el, DaskArray) and isinstance(el._meta, CSMatrix | CSArray)) + for el in els + ): + return 0 + else: + return np.nan + + +def gen_reindexer(new_var: pd.Index, cur_var: pd.Index) -> Reindexer: + """ + Given a new set of var_names, and a current set, generates a function which will reindex + a matrix to be aligned with the new set. + + Usage + ----- + + >>> a = AnnData(sparse.eye(3, format="csr"), var=pd.DataFrame(index=list("abc"))) + >>> b = AnnData(sparse.eye(2, format="csr"), var=pd.DataFrame(index=list("ba"))) + >>> reindexer = gen_reindexer(a.var_names, b.var_names) + >>> sparse.vstack([a.X, reindexer(b.X)]).toarray() + array([[1., 0., 0.], + [0., 1., 0.], + [0., 0., 1.], + [0., 1., 0.], + [1., 0., 0.]]) + """ + return Reindexer(cur_var, new_var) + + +def np_bool_to_pd_bool_array(df: pd.DataFrame): + for col_name, col_type in dict(df.dtypes).items(): + if col_type is np.dtype(bool): + df[col_name] = pd.array(df[col_name].values) + return df + + +def concat_arrays( # noqa: PLR0911, PLR0912 + arrays, reindexers, axis=0, index=None, fill_value=None, *, force_lazy: bool = False +): + from anndata.experimental.backed._compat import Dataset2D + + arrays = list(arrays) + if fill_value is None: + fill_value = default_fill_value(arrays) + + if any(isinstance(a, Dataset2D) for a in arrays): + if any(isinstance(a, pd.DataFrame) for a in arrays): + arrays = [to_memory(a) if isinstance(a, Dataset2D) else a for a in arrays] + elif not all(isinstance(a, Dataset2D) for a in arrays): + msg = f"Cannot concatenate a Dataset2D with other array types {[type(a) for a in arrays if not isinstance(a, Dataset2D)]}." + raise ValueError(msg) + else: + return concat_dataset2d_on_annot_axis( + arrays, join="outer", force_lazy=force_lazy + ) + if any(isinstance(a, pd.DataFrame) for a in arrays): + # TODO: This is hacky, 0 is a sentinel for outer_concat_aligned_mapping + if not all( + isinstance(a, pd.DataFrame) or a is MissingVal or 0 in a.shape + for a in arrays + ): + msg = "Cannot concatenate a dataframe with other array types." + raise NotImplementedError(msg) + # TODO: behaviour here should be chosen through a merge strategy + df = pd.concat( + unify_dtypes(f(x) for f, x in zip(reindexers, arrays, strict=True)), + axis=axis, + ignore_index=True, + ) + df.index = index + return df + elif any(isinstance(a, AwkArray) for a in arrays): + from ..compat import awkward as ak + + if not all( + isinstance(a, AwkArray) or a is MissingVal or 0 in a.shape for a in arrays + ): + msg = "Cannot concatenate an AwkwardArray with other array types." + raise NotImplementedError(msg) + + return ak.concatenate( + [f(a) for f, a in zip(reindexers, arrays, strict=True)], axis=axis + ) + elif any(isinstance(a, CupySparseMatrix) for a in arrays): + import cupyx.scipy.sparse as cpsparse + + if not all( + isinstance(a, CupySparseMatrix | CupyArray) or 0 in a.shape for a in arrays + ): + msg = "Cannot concatenate a cupy array with other array types." + raise NotImplementedError(msg) + sparse_stack = (cpsparse.vstack, cpsparse.hstack)[axis] + return sparse_stack( + [ + f(as_cp_sparse(a), axis=1 - axis, fill_value=fill_value) + for f, a in zip(reindexers, arrays, strict=True) + ], + format="csr", + ) + elif any(isinstance(a, CupyArray) for a in arrays): + import cupy as cp + + if not all(isinstance(a, CupyArray) or 0 in a.shape for a in arrays): + msg = "Cannot concatenate a cupy array with other array types." + raise NotImplementedError(msg) + return cp.concatenate( + [ + f(cp.asarray(x), fill_value=fill_value, axis=1 - axis) + for f, x in zip(reindexers, arrays, strict=True) + ], + axis=axis, + ) + elif any(isinstance(a, CSMatrix | CSArray) for a in arrays): + sparse_stack = (sparse.vstack, sparse.hstack)[axis] + use_sparse_array = any(issubclass(type(a), CSArray) for a in arrays) + mat = sparse_stack( + [ + f( + as_sparse(a, use_sparse_array=use_sparse_array), + axis=1 - axis, + fill_value=fill_value, + ) + for f, a in zip(reindexers, arrays, strict=True) + ], + format="csr", + ) + return mat + else: + return np.concatenate( + [ + f(x, fill_value=fill_value, axis=1 - axis) + for f, x in zip(reindexers, arrays, strict=True) + ], + axis=axis, + ) + + +def inner_concat_aligned_mapping( + mappings, + *, + reindexers=None, + index=None, + axis=0, + concat_axis=None, + force_lazy: bool = False, +): + if concat_axis is None: + concat_axis = axis + result = {} + + for k in intersect_keys(mappings): + els = [m[k] for m in mappings] + if reindexers is None: + cur_reindexers = gen_inner_reindexers( + els, new_index=index, axis=concat_axis + ) + else: + cur_reindexers = reindexers + + result[k] = concat_arrays( + els, cur_reindexers, index=index, axis=concat_axis, force_lazy=force_lazy + ) + return result + + +def gen_inner_reindexers(els, new_index, axis: Literal[0, 1] = 0) -> list[Reindexer]: + alt_axis = 1 - axis + if axis == 0: + df_indices = lambda x: x.columns + elif axis == 1: + df_indices = lambda x: x.indices + + if all(isinstance(el, pd.DataFrame) for el in els if not_missing(el)): + common_ind = reduce( + lambda x, y: x.intersection(y), (df_indices(el) for el in els) + ) + reindexers = [Reindexer(df_indices(el), common_ind) for el in els] + elif any(isinstance(el, AwkArray) for el in els if not_missing(el)): + if not all(isinstance(el, AwkArray) for el in els if not_missing(el)): + msg = "Cannot concatenate an AwkwardArray with other array types." + raise NotImplementedError(msg) + common_keys = intersect_keys(el.fields for el in els) + # TODO: replace dtype=object once this is fixed: https://github.com/scikit-hep/awkward/issues/3730 + reindexers = [ + Reindexer( + pd.Index(el.fields, dtype=object), + pd.Index(list(common_keys), dtype=object), + ) + for el in els + ] + else: + min_ind = min(el.shape[alt_axis] for el in els) + reindexers = [ + gen_reindexer(pd.RangeIndex(min_ind), pd.RangeIndex(el.shape[alt_axis])) + for el in els + ] + return reindexers + + +def gen_outer_reindexers(els, shapes, new_index: pd.Index, *, axis=0): + if all(isinstance(el, pd.DataFrame) for el in els if not_missing(el)): + reindexers = [ + (lambda x: x) + if not_missing(el) + else (lambda _, shape=shape: pd.DataFrame(index=range(shape))) + for el, shape in zip(els, shapes, strict=True) + ] + elif any(isinstance(el, AwkArray) for el in els if not_missing(el)): + import awkward as ak + + if not all(isinstance(el, AwkArray) for el in els if not_missing(el)): + msg = "Cannot concatenate an AwkwardArray with other array types." + raise NotImplementedError(msg) + warn_once( + "Outer joins on awkward.Arrays will have different return values in the future. " + "For details, and to offer input, please see:\n\n\t" + "https://github.com/scverse/anndata/issues/898", + ExperimentalFeatureWarning, + ) + # all_keys = union_keys(el.fields for el in els if not_missing(el)) + reindexers = [] + for el in els: + if not_missing(el): + reindexers.append(lambda x: x) + else: + reindexers.append( + lambda x: ak.pad_none( + ak.Array([]), + len(x), + 0, + ) + ) + else: + max_col = max(el.shape[1] for el in els if not_missing(el)) + orig_cols = [el.shape[1] if not_missing(el) else 0 for el in els] + reindexers = [ + gen_reindexer(pd.RangeIndex(max_col), pd.RangeIndex(n)) for n in orig_cols + ] + return reindexers + + +def missing_element( + n: int, + els: list[CSArray | CSMatrix | np.ndarray | DaskArray], + axis: Literal[0, 1] = 0, + fill_value: Any | None = None, + off_axis_size: int = 0, +) -> NDArray[np.bool_] | DaskArray: + """Generates value to use when there is a missing element.""" + should_return_dask = any(isinstance(el, DaskArray) for el in els) + # 0 sized array for in-memory prevents allocating unnecessary memory while preserving broadcasting. + shape = (n, off_axis_size) if axis == 0 else (off_axis_size, n) + if should_return_dask: + import dask.array as da + + return da.full( + shape, default_fill_value(els) if fill_value is None else fill_value + ) + return np.zeros(shape, dtype=bool) + + +def outer_concat_aligned_mapping( + mappings, + *, + reindexers=None, + index=None, + axis=0, + concat_axis=None, + fill_value=None, + force_lazy: bool = False, +): + if concat_axis is None: + concat_axis = axis + result = {} + ns = [m.parent.shape[axis] for m in mappings] + + for k in union_keys(mappings): + els = [m.get(k, MissingVal) for m in mappings] + if reindexers is None: + cur_reindexers = gen_outer_reindexers( + els, ns, new_index=index, axis=concat_axis + ) + else: + cur_reindexers = reindexers + + # Dask needs to create a full array and can't do the size-0 trick + off_axis_size = 0 + if any(isinstance(e, DaskArray) for e in els): + if not isinstance(cur_reindexers[0], Reindexer): # pragma: no cover + msg = "Cannot re-index a dask array without a Reindexer" + raise ValueError(msg) + off_axis_size = cur_reindexers[0].idx.shape[0] + # Handling of missing values here is hacky for dataframes + # We should probably just handle missing elements for all types + result[k] = concat_arrays( + [ + el + if not_missing(el) + else missing_element( + n, + axis=concat_axis, + els=els, + fill_value=fill_value, + off_axis_size=off_axis_size, + ) + for el, n in zip(els, ns, strict=True) + ], + cur_reindexers, + axis=concat_axis, + index=index, + fill_value=fill_value, + force_lazy=force_lazy, + ) + return result + + +def concat_pairwise_mapping( + mappings: Collection[Mapping], shapes: Collection[int], join_keys=intersect_keys +): + result = {} + if any(any(isinstance(v, CSArray) for v in m.values()) for m in mappings): + sparse_class = sparse.csr_array + else: + sparse_class = sparse.csr_matrix + + for k in join_keys(mappings): + els = [ + m.get(k, sparse_class((s, s), dtype=bool)) + for m, s in zip(mappings, shapes, strict=True) + ] + if all(isinstance(el, CupySparseMatrix | CupyArray) for el in els): + result[k] = _cp_block_diag(els, format="csr") + elif all(isinstance(el, DaskArray) for el in els): + result[k] = _dask_block_diag(els) + else: + # TODO: Remove the warning catch some time around scipy 1.2 (stated in the warning) + # https://docs.scipy.org/doc/scipy/reference/sparse.migration_to_sparray.html#existing-functions-that-need-careful-migration + with warnings.catch_warnings(): + if any(isinstance(v, np.ndarray) for v in els): + warnings.filterwarnings( + "ignore", + r"`block_diag` is switching to the sparse array interface.", + DeprecationWarning, + ) + + diag = sparse.block_diag(els, format="csr") + # TODO: Remove once we migrate internally to xxx_array + if isinstance(diag, CSArray): + diag = sparse.csr_matrix(diag) + result[k] = diag + return result + + +def merge_dataframes( + dfs: Iterable[pd.DataFrame], new_index, merge_strategy=merge_unique +) -> pd.DataFrame: + dfs = [df.reindex(index=new_index) for df in dfs] + # New dataframe with all shared data + new_df = pd.DataFrame(merge_strategy(dfs), index=new_index) + return new_df + + +def merge_outer(mappings, batch_keys, *, join_index="-", merge=merge_unique): + """ + Combine elements of two mappings, such that non-overlapping entries are added with their batch-key appended. + + Note: this currently does NOT work for nested mappings. Additionally, values are not promised to be unique, and may be overwritten. + """ + all_keys = union_keys(mappings) + out = merge(mappings) + for key in all_keys.difference(out.keys()): + for b, m in zip(batch_keys, mappings, strict=True): + val = m.get(key, None) + if val is not None: + out[f"{key}{join_index}{b}"] = val + return out + + +def _resolve_axis( + axis: Literal["obs", 0, "var", 1], +) -> tuple[Literal[0], Literal["obs"]] | tuple[Literal[1], Literal["var"]]: + if axis in {0, "obs"}: + return (0, "obs") + if axis in {1, "var"}: + return (1, "var") + msg = f"`axis` must be either 0, 1, 'obs', or 'var', was {axis}" + raise ValueError(msg) + + +def axis_indices(adata: AnnData, axis: Literal["obs", 0, "var", 1]) -> pd.Index: + """Helper function to get adata.{dim}_names.""" + _, axis_name = _resolve_axis(axis) + attr = getattr(adata, axis_name) + if isinstance(attr, Dataset2D): + return attr.true_index + else: + return attr.index + + +# TODO: Resolve https://github.com/scverse/anndata/issues/678 and remove this function +def concat_Xs(adatas, reindexers, axis, fill_value): + """ + Shimy until support for some missing X's is implemented. + + Basically just checks if it's one of the two supported cases, or throws an error. + + This is not done inline in `concat` because we don't want to maintain references + to the values of a.X. + """ + Xs = [a.X for a in adatas] + if all(X is None for X in Xs): + return None + elif any(X is None for X in Xs): + msg = ( + "Some (but not all) of the AnnData's to be concatenated had no .X value. " + "Concatenation is currently only implemented for cases where all or none of" + " the AnnData's have .X assigned." + ) + raise NotImplementedError(msg) + else: + return concat_arrays(Xs, reindexers, axis=axis, fill_value=fill_value) + + +def make_dask_col_from_extension_dtype( + col: XDataArray, *, use_only_object_dtype: bool = False +) -> DaskArray: + """ + Creates dask arrays from :class:`pandas.api.extensions.ExtensionArray` dtype :class:`xarray.DataArray`s. + + Parameters + ---------- + col + The columns to be converted + use_only_object_dtype + Whether or not to cast all :class:`pandas.api.extensions.ExtensionArray` dtypes to `object` type, by default False + + Returns + ------- + A :class:`dask.Array`: representation of the column. + """ + import dask.array as da + + from anndata._io.specs.lazy_methods import ( + compute_chunk_layout_for_axis_size, + get_chunksize, + maybe_open_h5, + ) + from anndata.compat import xarray as xr + from anndata.experimental import read_elem_lazy + + base_path_or_zarr_group = col.attrs.get("base_path_or_zarr_group") + elem_name = col.attrs.get("elem_name") + if ( + base_path_or_zarr_group is not None and elem_name is not None + ): # lazy, backed by store + dims = col.dims + with maybe_open_h5(base_path_or_zarr_group, elem_name) as f: + maybe_chunk_size = get_chunksize(read_elem_lazy(f)) + chunk_size = ( + compute_chunk_layout_for_axis_size( + 1000 if maybe_chunk_size is None else maybe_chunk_size[0], + col.shape[0], + ), + ) + + def get_chunk(block_info=None): + # reopening is important to get around h5py's unserializable lock in processes + with maybe_open_h5(base_path_or_zarr_group, elem_name) as f: + v = read_elem_lazy(f) + variable = xr.Variable( + data=xr.core.indexing.LazilyIndexedArray(v), dims=dims + ) + idx = tuple( + slice(start, stop) + for start, stop in block_info[None]["array-location"] + ) + chunk = np.array(variable.data[idx]) + return chunk + + if col.dtype == "category" or col.dtype == "string" or use_only_object_dtype: # noqa PLR1714 + dtype = "object" + else: + dtype = col.dtype.numpy_dtype + return da.map_blocks( + get_chunk, + chunks=chunk_size, + meta=np.array([], dtype=dtype), + dtype=dtype, + name=f"{uuid.uuid4()}/{base_path_or_zarr_group}/{elem_name}-{dtype}", + ) + + return da.from_array(col.values, chunks=-1) # in-memory + + +def make_xarray_extension_dtypes_dask( + annotations: Iterable[Dataset2D], *, use_only_object_dtype: bool = False +) -> Generator[Dataset2D, None, None]: + """ + Creates a generator of Dataset2D objects with dask arrays in place of :class:`pandas.api.extensions.ExtensionArray` dtype columns. + + Parameters + ---------- + annotations + The datasets to be altered + use_only_object_dtype + Whether or not to cast all :class:`pandas.api.extensions.ExtensionArray` dtypes to `object` type, by default False + + Yields + ------ + An altered dataset. + """ + for a in annotations: + extension_cols = { + col for col in a.columns if pd.api.types.is_extension_array_dtype(a[col]) + } + + yield a.copy( + data={ + name: ( + make_dask_col_from_extension_dtype( + col, use_only_object_dtype=use_only_object_dtype + ) + if name in extension_cols + else col + ) + for name, col in a._items() + } + ) + + +DS_CONCAT_DUMMY_INDEX_NAME = "_anndata_concat_index" +DS_MERGE_DUMMY_INDEX_NAME = "_anndata_merge_index" + + +def concat_dataset2d_on_annot_axis( + annotations: Iterable[Dataset2D], + join: Join_T, + *, + force_lazy: bool, + concat_indices: pd.Index | None = None, +) -> Dataset2D: + """Create a concatenate dataset from a list of :class:`~anndata.experimental.backed.Dataset2D` objects. + The goal of this function is to mimic `pd.concat(..., ignore_index=True)` so has some complicated logic + for handling the "index" to ensure (a) nothing is loaded into memory and (b) the true index is always tracked. + + Parameters + ---------- + annotations + The :class:`~anndata.experimental.backed.Dataset2D` objects to be concatenated. + join + Type of join operation + force_lazy + Whether to lazily concatenate elements using dask even when eager concatenation is possible. + concat_indices + Already calculated indices to be used as the index on the concatenated object. + + Returns + ------- + Concatenated :class:`~anndata.experimental.backed.Dataset2D` + """ + import xarray as xr + + from anndata._core.xarray import Dataset2D + from anndata._io.specs.lazy_methods import DUMMY_RANGE_INDEX_KEY + + annotations_re_indexed = [] + have_backed = any(a.is_backed for a in annotations) + if have_backed or force_lazy: + annotations = make_xarray_extension_dtypes_dask(annotations) + else: + annotations = unify_dtypes(annotations) + for a in annotations: + old_key = a.index_dim + is_fake_index = old_key != a.true_index_dim + # First create a dummy index + a.ds.coords[DS_CONCAT_DUMMY_INDEX_NAME] = ( + old_key, + pd.RangeIndex(a.shape[0]), + ) + # Set all the dimensions to this new dummy index + ds_swapped = a.ds.swap_dims({old_key: DS_CONCAT_DUMMY_INDEX_NAME}) + # Move the old coordinate into a variable + old_coord = ds_swapped.coords[old_key] + del ds_swapped.coords[old_key] + ds_swapped[old_key] = old_coord + a = Dataset2D(ds_swapped) + if not is_fake_index: + a.true_index_dim = old_key + annotations_re_indexed.append(a) + # Concat along the dummy index + ds_concat = xr.concat( + [a.ds for a in annotations_re_indexed], + join=join, + dim=DS_CONCAT_DUMMY_INDEX_NAME, + ) + ds_concat.attrs.pop("indexing_key", None) + # Wrapping allows us to use the Dataset2D methods + # directly for setting certain attrs/coords without duplicating here. + ds_concat_2d = Dataset2D(ds_concat) + ds_concat_2d.is_backed = have_backed + if concat_indices is not None: + concat_indices.name = DS_CONCAT_DUMMY_INDEX_NAME + ds_concat_2d.index = concat_indices + ds_concat = ds_concat_2d.ds + else: + ds_concat.coords[DS_CONCAT_DUMMY_INDEX_NAME] = pd.RangeIndex( + ds_concat.coords[DS_CONCAT_DUMMY_INDEX_NAME].shape[0] + ) + # Drop any lingering dimensions (swap doesn't delete) + ds_concat = ds_concat.drop_dims( + d for d in ds_concat.dims if d != DS_CONCAT_DUMMY_INDEX_NAME + ) + # Create a new true index and then delete the columns resulting from the concatenation for each index. + # This includes the dummy column (which is neither a dimension nor a true indexing column) + if concat_indices is None: + index = xr.concat( + [a.true_xr_index for a in annotations_re_indexed], + dim=DS_CONCAT_DUMMY_INDEX_NAME, + ) + # prevent duplicate values + index.coords[DS_CONCAT_DUMMY_INDEX_NAME] = ds_concat.coords[ + DS_CONCAT_DUMMY_INDEX_NAME + ] + ds_concat.coords[DS_CONCAT_DUMMY_INDEX_NAME] = index + for key in { + true_index + for a in annotations_re_indexed + if (true_index := a.true_index_dim) != a.index_dim + }: + del ds_concat[key] + if DUMMY_RANGE_INDEX_KEY in ds_concat: + del ds_concat[DUMMY_RANGE_INDEX_KEY] + ds_concat_2d = Dataset2D(ds_concat) + return ds_concat_2d + + +def concat( # noqa: PLR0912, PLR0913, PLR0915 + adatas: Collection[AnnData] | Mapping[str, AnnData], + *, + axis: Literal["obs", 0, "var", 1] = "obs", + join: Join_T = "inner", + merge: StrategiesLiteral | Callable | None = None, + uns_merge: StrategiesLiteral | Callable | None = None, + label: str | None = None, + keys: Collection | None = None, + index_unique: str | None = None, + fill_value: Any | None = None, + pairwise: bool = False, + force_lazy: bool = False, +) -> AnnData: + """Concatenates AnnData objects along an axis. + + See the :doc:`concatenation <../concatenation>` section in the docs for a more in-depth description. + + Params + ------ + adatas + The objects to be concatenated. If a Mapping is passed, keys are used for the `keys` + argument and values are concatenated. + axis + Which axis to concatenate along. + join + How to align values when concatenating. If "outer", the union of the other axis + is taken. If "inner", the intersection. See :doc:`concatenation <../concatenation>` + for more. + merge + How elements not aligned to the axis being concatenated along are selected. + Currently implemented strategies include: + + * `None`: No elements are kept. + * `"same"`: Elements that are the same in each of the objects. + * `"unique"`: Elements for which there is only one possible value. + * `"first"`: The first element seen at each from each position. + * `"only"`: Elements that show up in only one of the objects. + + For :class:`xarray.Dataset` objects, we use their :func:`xarray.merge` with `override` to stay lazy. + uns_merge + How the elements of `.uns` are selected. Uses the same set of strategies as + the `merge` argument, except applied recursively. + label + Column in axis annotation (i.e. `.obs` or `.var`) to place batch information in. + If it's None, no column is added. + keys + Names for each object being added. These values are used for column values for + `label` or appended to the index if `index_unique` is not `None`. Defaults to + incrementing integer labels. + index_unique + Whether to make the index unique by using the keys. If provided, this + is the delimiter between "{orig_idx}{index_unique}{key}". When `None`, + the original indices are kept. + fill_value + When `join="outer"`, this is the value that will be used to fill the introduced + indices. By default, sparse arrays are padded with zeros, while dense arrays and + DataFrames are padded with missing values. + pairwise + Whether pairwise elements along the concatenated dimension should be included. + This is False by default, since the resulting arrays are often not meaningful. + force_lazy + Whether to lazily concatenate elements using dask even when eager concatenation is possible. + At the moment, this only affects obs/var and elements of obsm/varm that are xarray Datasets. + + Notes + ----- + + .. warning:: + + If you use `join='outer'` this fills 0s for sparse data when + variables are absent in a batch. Use this with care. Dense data is + filled with `NaN`. + + Examples + -------- + + Preparing example objects + + >>> import anndata as ad, pandas as pd, numpy as np + >>> from scipy import sparse + >>> a = ad.AnnData( + ... X=sparse.csr_matrix(np.array([[0, 1], [2, 3]])), + ... obs=pd.DataFrame({"group": ["a", "b"]}, index=["s1", "s2"]), + ... var=pd.DataFrame(index=["var1", "var2"]), + ... varm={ + ... "ones": np.ones((2, 5)), + ... "rand": np.random.randn(2, 3), + ... "zeros": np.zeros((2, 5)), + ... }, + ... uns={"a": 1, "b": 2, "c": {"c.a": 3, "c.b": 4}}, + ... ) + >>> b = ad.AnnData( + ... X=sparse.csr_matrix(np.array([[4, 5, 6], [7, 8, 9]])), + ... obs=pd.DataFrame( + ... {"group": ["b", "c"], "measure": [1.2, 4.3]}, index=["s3", "s4"] + ... ), + ... var=pd.DataFrame(index=["var1", "var2", "var3"]), + ... varm={"ones": np.ones((3, 5)), "rand": np.random.randn(3, 5)}, + ... uns={"a": 1, "b": 3, "c": {"c.b": 4}}, + ... ) + >>> c = ad.AnnData( + ... X=sparse.csr_matrix(np.array([[10, 11], [12, 13]])), + ... obs=pd.DataFrame({"group": ["a", "b"]}, index=["s1", "s2"]), + ... var=pd.DataFrame(index=["var3", "var4"]), + ... uns={"a": 1, "b": 4, "c": {"c.a": 3, "c.b": 4, "c.c": 5}}, + ... ) + + Concatenating along different axes + + >>> ad.concat([a, b]).to_df() + var1 var2 + s1 0 1 + s2 2 3 + s3 4 5 + s4 7 8 + >>> ad.concat([a, c], axis="var").to_df() + var1 var2 var3 var4 + s1 0 1 10 11 + s2 2 3 12 13 + + Inner and outer joins + + >>> inner = ad.concat([a, b]) # Joining on intersection of variables + >>> inner + AnnData object with n_obs × n_vars = 4 × 2 + obs: 'group' + >>> ( + ... inner.obs_names.astype("string"), + ... inner.var_names.astype("string"), + ... ) # doctest: +NORMALIZE_WHITESPACE + (Index(['s1', 's2', 's3', 's4'], dtype='string'), + Index(['var1', 'var2'], dtype='string')) + >>> outer = ad.concat([a, b], join="outer") # Joining on union of variables + >>> outer + AnnData object with n_obs × n_vars = 4 × 3 + obs: 'group', 'measure' + >>> outer.var_names.astype("string") + Index(['var1', 'var2', 'var3'], dtype='string') + >>> outer.to_df() # Sparse arrays are padded with zeroes by default + var1 var2 var3 + s1 0 1 0 + s2 2 3 0 + s3 4 5 6 + s4 7 8 9 + + Using the axis’ index instead of its name + + >>> ad.concat([a, b], axis=0).to_df() # Equivalent to axis="obs" + var1 var2 + s1 0 1 + s2 2 3 + s3 4 5 + s4 7 8 + >>> ad.concat([a, c], axis=1).to_df() # Equivalent to axis="var" + var1 var2 var3 var4 + s1 0 1 10 11 + s2 2 3 12 13 + + Keeping track of source objects + + >>> ad.concat({"a": a, "b": b}, label="batch").obs + group batch + s1 a a + s2 b a + s3 b b + s4 c b + >>> ad.concat([a, b], label="batch", keys=["a", "b"]).obs # Equivalent to previous + group batch + s1 a a + s2 b a + s3 b b + s4 c b + >>> ad.concat({"a": a, "b": b}, index_unique="-").obs + group + s1-a a + s2-a b + s3-b b + s4-b c + + Combining values not aligned to axis of concatenation + + >>> ad.concat([a, b], merge="same") + AnnData object with n_obs × n_vars = 4 × 2 + obs: 'group' + varm: 'ones' + >>> ad.concat([a, b], merge="unique") + AnnData object with n_obs × n_vars = 4 × 2 + obs: 'group' + varm: 'ones', 'zeros' + >>> ad.concat([a, b], merge="first") + AnnData object with n_obs × n_vars = 4 × 2 + obs: 'group' + varm: 'ones', 'rand', 'zeros' + >>> ad.concat([a, b], merge="only") + AnnData object with n_obs × n_vars = 4 × 2 + obs: 'group' + varm: 'zeros' + + The same merge strategies can be used for elements in `.uns` + + >>> dict(ad.concat([a, b, c], uns_merge="same").uns) + {'a': 1, 'c': {'c.b': 4}} + >>> dict(ad.concat([a, b, c], uns_merge="unique").uns) + {'a': 1, 'c': {'c.a': 3, 'c.b': 4, 'c.c': 5}} + >>> dict(ad.concat([a, b, c], uns_merge="only").uns) + {'c': {'c.c': 5}} + >>> dict(ad.concat([a, b, c], uns_merge="first").uns) + {'a': 1, 'b': 2, 'c': {'c.a': 3, 'c.b': 4, 'c.c': 5}} + """ + + from anndata._core.xarray import Dataset2D + from anndata.compat import xarray as xr + + # Argument normalization + merge = resolve_merge_strategy(merge) + uns_merge = resolve_merge_strategy(uns_merge) + + if isinstance(adatas, Mapping): + if keys is not None: + msg = ( + "Cannot specify categories in both mapping keys and using `keys`. " + "Only specify this once." + ) + raise TypeError(msg) + keys, adatas = list(adatas.keys()), list(adatas.values()) + else: + adatas = list(adatas) + + if keys is None: + keys = np.arange(len(adatas)).astype(str) + + axis, axis_name = _resolve_axis(axis) + alt_axis, alt_axis_name = _resolve_axis(axis=1 - axis) + + # Label column + label_col = pd.Categorical.from_codes( + np.repeat(np.arange(len(adatas)), [a.shape[axis] for a in adatas]), + categories=keys, + ) + + # Combining indexes + concat_indices = pd.concat( + [axis_indices(a, axis=axis).to_series() for a in adatas], ignore_index=True + ) + if index_unique is not None: + concat_indices = concat_indices.str.cat( + label_col.map(str, na_action="ignore"), sep=index_unique + ) + concat_indices = pd.Index(concat_indices) + + alt_indices = merge_indices( + [axis_indices(a, axis=alt_axis) for a in adatas], join=join + ) + reindexers = [ + gen_reindexer(alt_indices, axis_indices(a, axis=alt_axis)) for a in adatas + ] + + # Annotation for concatenation axis + check_combinable_cols([getattr(a, axis_name).columns for a in adatas], join=join) + annotations = [getattr(a, axis_name) for a in adatas] + are_any_annotations_dataframes = any( + isinstance(a, pd.DataFrame) for a in annotations + ) + if are_any_annotations_dataframes: + annotations_in_memory = ( + to_memory(a) if isinstance(a, Dataset2D) else a for a in annotations + ) + concat_annot = pd.concat( + unify_dtypes(annotations_in_memory), + join=join, + ignore_index=True, + ) + concat_annot.index = concat_indices + else: + concat_annot = concat_dataset2d_on_annot_axis( + annotations, + join, + force_lazy=force_lazy, + concat_indices=concat_indices, + ) + if label is not None: + concat_annot[label] = label_col + + # Annotation for other axis + alt_annotations = [getattr(a, alt_axis_name) for a in adatas] + are_any_alt_annotations_dataframes = any( + isinstance(a, pd.DataFrame) for a in alt_annotations + ) + if are_any_alt_annotations_dataframes: + alt_annotations_in_memory = [ + to_memory(a) if isinstance(a, Dataset2D) else a for a in alt_annotations + ] + alt_annot = merge_dataframes(alt_annotations_in_memory, alt_indices, merge) + else: + # TODO: figure out mapping of our merge to theirs instead of just taking first, although this appears to be + # the only "lazy" setting so I'm not sure we really want that. + # Because of xarray's merge upcasting, it's safest to simply assume that all dtypes are objects. + annotations_with_only_dask = list( + make_xarray_extension_dtypes_dask( + alt_annotations, use_only_object_dtype=True + ) + ) + for a in annotations_with_only_dask: + if a.true_index_dim != a.index_dim: + a.index = a.true_index + annotations_with_only_dask = [ + a.ds.rename({a.true_index_dim: DS_MERGE_DUMMY_INDEX_NAME}) + for a in annotations_with_only_dask + ] + alt_annot = Dataset2D( + xr.merge(annotations_with_only_dask, join=join, compat="override") + ) + + X = concat_Xs(adatas, reindexers, axis=axis, fill_value=fill_value) + + if join == "inner": + concat_aligned_mapping = inner_concat_aligned_mapping + join_keys = intersect_keys + elif join == "outer": + concat_aligned_mapping = partial( + outer_concat_aligned_mapping, fill_value=fill_value + ) + join_keys = union_keys + else: + msg = f"{join=} should have been validated above by pd.concat" + raise AssertionError(msg) + + layers = concat_aligned_mapping( + [a.layers for a in adatas], axis=axis, reindexers=reindexers + ) + concat_mapping = concat_aligned_mapping( + [getattr(a, f"{axis_name}m") for a in adatas], + axis=axis, + concat_axis=0, + index=concat_indices, + force_lazy=force_lazy, + ) + if pairwise: + concat_pairwise = concat_pairwise_mapping( + mappings=[getattr(a, f"{axis_name}p") for a in adatas], + shapes=[a.shape[axis] for a in adatas], + join_keys=join_keys, + ) + else: + concat_pairwise = {} + + # TODO: Reindex lazily, so we don't have to make those copies until we're sure we need the element + alt_mapping = merge( + [ + {k: r(v, axis=0) for k, v in getattr(a, f"{alt_axis_name}m").items()} + for r, a in zip(reindexers, adatas, strict=True) + ], + ) + alt_pairwise = merge([ + {k: r(r(v, axis=0), axis=1) for k, v in getattr(a, f"{alt_axis_name}p").items()} + for r, a in zip(reindexers, adatas, strict=True) + ]) + uns = uns_merge([a.uns for a in adatas]) + + raw = None + has_raw = [a.raw is not None for a in adatas] + if all(has_raw): + raw = concat( + [ + AnnData( + X=a.raw.X, + obs=pd.DataFrame(index=a.obs_names), + var=a.raw.var, + varm=a.raw.varm, + ) + for a in adatas + ], + join=join, + label=label, + keys=keys, + index_unique=index_unique, + fill_value=fill_value, + axis=axis, + ) + elif any(has_raw): + msg = ( + "Only some AnnData objects have `.raw` attribute, " + "not concatenating `.raw` attributes." + ) + warn(msg, UserWarning, stacklevel=2) + return AnnData(**{ + "X": X, + "layers": layers, + axis_name: concat_annot, + alt_axis_name: alt_annot, + f"{axis_name}m": concat_mapping, + f"{alt_axis_name}m": alt_mapping, + f"{axis_name}p": concat_pairwise, + f"{alt_axis_name}p": alt_pairwise, + "uns": uns, + "raw": raw, + }) diff --git a/.venv/lib/python3.11/site-packages/anndata/_core/raw.py b/.venv/lib/python3.11/site-packages/anndata/_core/raw.py new file mode 100644 index 0000000000000000000000000000000000000000..c7446b067181b27498f5adf04736c3a9cdd57ffa --- /dev/null +++ b/.venv/lib/python3.11/site-packages/anndata/_core/raw.py @@ -0,0 +1,252 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +import h5py +import numpy as np +import pandas as pd +from scipy.sparse import issparse + +from ..compat import CupyArray, CupySparseMatrix +from .aligned_df import _gen_dataframe +from .aligned_mapping import AlignedMappingProperty, AxisArrays +from .index import _normalize_index, _subset, get_vector, unpack_index +from .sparse_dataset import sparse_dataset + +if TYPE_CHECKING: + from collections.abc import Mapping, Sequence + from typing import ClassVar + + from ..compat import CSMatrix, Index, Index1DNorm + from .aligned_mapping import AxisArraysView + from .anndata import AnnData + from .sparse_dataset import BaseCompressedSparseDataset + + +# TODO: Implement views for Raw +class Raw: + is_view: ClassVar = False + + def __init__( + self, + adata: AnnData, + X: np.ndarray | CSMatrix | None = None, + var: pd.DataFrame | Mapping[str, Sequence] | None = None, + varm: AxisArrays | Mapping[str, np.ndarray] | None = None, + ) -> None: + if X is not None and X.shape[0] != adata.n_obs: + msg = f"X has {X.shape[0]} rows, but n_obs is {adata.n_obs}" + raise ValueError(msg) + + self._adata = adata + self._n_obs = adata.n_obs + # construct manually + if adata.isbacked == (X is None): + # Move from GPU to CPU since it's large and not always used + if isinstance(X, CupyArray | CupySparseMatrix): + self._X = X.get() + else: + self._X = X + n_var = None if self._X is None else self._X.shape[1] + self._var = _gen_dataframe( + var, ["var_names"], source="X", attr="var", length=n_var + ) + self.varm = varm + elif X is None: # construct from adata + # Move from GPU to CPU since it's large and not always used + if isinstance(adata.X, CupyArray | CupySparseMatrix): + self._X = adata.X.get() + else: + self._X = adata.X.copy() + self._var = adata.var.copy() + self.varm = adata.varm.copy() + elif adata.isbacked: + msg = "Cannot specify X if adata is backed" + raise ValueError(msg) + + def _get_X(self, layer=None): + if layer is not None: + raise ValueError() + return self.X + + @property + def X(self) -> BaseCompressedSparseDataset | np.ndarray | CSMatrix: + # TODO: Handle unsorted array of integer indices for h5py.Datasets + if not self._adata.isbacked: + return self._X + if not self._adata.file.is_open: + self._adata.file.open() + # Handle legacy file formats: + if "raw/X" in self._adata.file: + X = self._adata.file["raw/X"] + elif "raw.X" in self._adata.file: + X = self._adata.file["raw.X"] # Backwards compat + else: + msg = ( + f"Could not find dataset for raw X in file: " + f"{self._adata.file.filename}." + ) + raise AttributeError(msg) + if isinstance(X, h5py.Group): + X = sparse_dataset(X) + # Check if we need to subset + if self._adata.is_view: + # TODO: As noted above, implement views of raw + # so we can know if we need to subset by var + return _subset(X, (self._adata._oidx, slice(None))) + else: + return X + + @property + def shape(self) -> tuple[int, int]: + return self.n_obs, self.n_vars + + @property + def var(self) -> pd.DataFrame: + return self._var + + @property + def n_vars(self) -> int: + return self._var.shape[0] + + @property + def n_obs(self) -> int: + return self._n_obs + + varm: AlignedMappingProperty[AxisArrays | AxisArraysView] = AlignedMappingProperty( + AxisArrays, 1 + ) + + @property + def var_names(self) -> pd.Index[str]: + return self.var.index + + @property + def obs_names(self) -> pd.Index[str]: + return self._adata.obs_names + + def __getitem__(self, index: Index | tuple[AnnData, Index]) -> Raw: + from .anndata import AnnData + + if ( + isinstance(index, tuple) + and len(index) == 2 + and isinstance(index[0], AnnData) + ): + adata, index = index + oidx, vidx = self._normalize_indices(index) + else: + oidx, vidx = self._normalize_indices(index) + adata = self._adata[oidx] + + # To preserve two dimensional shape + if isinstance(vidx, int | np.integer): + vidx = slice(vidx, vidx + 1, 1) + if isinstance(oidx, int | np.integer): + oidx = slice(oidx, oidx + 1, 1) + + X = _subset(self.X, (oidx, vidx)) if not self._adata.isbacked else None + + var = self._var.iloc[vidx] + new = Raw(adata, X=X, var=var) + if self.varm is not None: + # Since there is no view of raws + new.varm = self.varm._view(_RawViewHack(self, vidx), (vidx,)).copy() + return new + + def __str__(self) -> str: + descr = f"Raw AnnData with n_obs × n_vars = {self.n_obs} × {self.n_vars}" + for attr in ["var", "varm"]: + keys = getattr(self, attr).keys() + if len(keys) > 0: + descr += f"\n {attr}: {str(list(keys))[1:-1]}" + return descr + + def copy(self) -> Raw: + return Raw( + self._adata, + X=self.X.copy(), + var=self.var.copy(), + varm=None if self._varm is None else self._varm.copy(), + ) + + def to_adata(self) -> AnnData: + """Create full AnnData object.""" + from anndata import AnnData + + return AnnData( + X=self.X.copy(), + var=self.var.copy(), + varm=None if self._varm is None else self._varm.copy(), + obs=self._adata.obs.copy(), + obsm=self._adata.obsm.copy(), + obsp=self._adata.obsp.copy(), + uns=self._adata.uns.copy(), + ) + + def _normalize_indices( + self, packed_index: Index + ) -> tuple[Index1DNorm | int | np.integer, Index1DNorm | int | np.integer]: + # deal with slicing with pd.Series + if isinstance(packed_index, pd.Series): + packed_index = packed_index.values + if isinstance(packed_index, tuple): + if len(packed_index) != 2: + raise IndexDimError(len(packed_index)) + if isinstance(packed_index[1], pd.Series): + packed_index = packed_index[0], packed_index[1].values + if isinstance(packed_index[0], pd.Series): + packed_index = packed_index[0].values, packed_index[1] + obs, var = unpack_index(packed_index) + obs = _normalize_index(obs, self._adata.obs_names) + var = _normalize_index(var, self.var_names) + return obs, var + + def var_vector(self, k: str) -> np.ndarray: + # TODO decorator to copy AnnData.var_vector docstring + return get_vector(self, k, "var", "obs") + + def obs_vector(self, k: str) -> np.ndarray: + # TODO decorator to copy AnnData.obs_vector docstring + idx = self._normalize_indices((slice(None), k)) + a = self.X[idx] + if issparse(a): + a = a.toarray() + return np.ravel(a) + + +# This exists to accommodate AlignedMappings, +# until we implement a proper RawView or get rid of Raw in favor of modes. +class _RawViewHack: + def __init__(self, raw: Raw, vidx: slice | np.ndarray): + self.parent_raw = raw + self.vidx = vidx + + @property + def shape(self) -> tuple[int, int]: + return self.parent_raw.n_obs, len(self.var_names) + + @property + def obs_names(self) -> pd.Index: + return self.parent_raw.obs_names + + @property + def var_names(self) -> pd.Index: + return self.parent_raw.var_names[self.vidx] + + +class IndexDimError(IndexError): + MSG = ( + "You tried to slice an AnnData(View) object with an" + "{}-dimensional index, but only 2 dimensions exist in such an object." + ) + MSG_1D = ( + "\nIf you tried to slice cells using adata[cells, ], " + "note that Python (unlike R) uses adata[cells, :] as slicing syntax." + ) + + def __init__(self, n_dims: int): + msg = self.MSG.format(n_dims) + if n_dims == 1: + msg += self.MSG_1D + super().__init__(msg) diff --git a/.venv/lib/python3.11/site-packages/anndata/_core/sparse_dataset.py b/.venv/lib/python3.11/site-packages/anndata/_core/sparse_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..bb63db697c3a2142acc2ee2de80f044c3f119087 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/anndata/_core/sparse_dataset.py @@ -0,0 +1,752 @@ +"""\ +This module implements on disk sparse datasets. + +This code is based on and uses the conventions of h5sparse_ by `Appier Inc.`_. +See the copyright and license note in this directory source code. + +.. _h5sparse: https://github.com/appier/h5sparse +.. _Appier Inc.: https://www.appier.com/ +""" + +# TODO: +# - think about supporting the COO format +from __future__ import annotations + +import warnings +from abc import ABC +from collections.abc import Iterable +from functools import cached_property +from importlib.metadata import version +from itertools import accumulate, chain, pairwise +from math import floor +from pathlib import Path +from typing import TYPE_CHECKING, NamedTuple + +import h5py +import numpy as np +import scipy.sparse as ss +from packaging.version import Version +from scipy.sparse import _sparsetools + +from .. import abc +from .._settings import settings +from ..compat import ( + CSArray, + CSMatrix, + H5Group, + ZarrArray, + ZarrGroup, + _read_attr, + is_zarr_v2, +) +from .index import _fix_slice_bounds, _subset, unpack_index + +if TYPE_CHECKING: + from collections.abc import Sequence + from typing import Literal + + from scipy.sparse._compressed import _cs_matrix + + from .._types import GroupStorageType + from ..compat import H5Array, Index, Index1D, Index1DNorm +else: + from scipy.sparse import spmatrix as _cs_matrix + + +SCIPY_1_15 = Version(version("scipy")) >= Version("1.15rc0") + + +class BackedFormat(NamedTuple): + format: Literal["csr", "csc"] + backed_type: type[BackedSparseMatrix] + memory_type: type[_cs_matrix] + + +class BackedSparseMatrix(_cs_matrix): + """\ + Mixin class for backed sparse matrices. + + Largely needed for the case `backed_sparse_csr(...)[:]`, + since that calls copy on `.data`, `.indices`, and `.indptr`. + """ + + data: GroupStorageType + indices: GroupStorageType + indptr: np.ndarray + + def copy(self) -> CSMatrix: + if isinstance(self.data, h5py.Dataset): + return sparse_dataset(self.data.parent).to_memory() + if isinstance(self.data, ZarrArray): + import zarr + + if is_zarr_v2(): + sparse_group = zarr.open( + store=self.data.store, + mode="r", + chunk_store=self.data.chunk_store, # chunk_store is needed, not clear why + )[Path(self.data.path).parent] + else: + anndata_group = zarr.open_group(store=self.data.store, mode="r") + sparse_group = anndata_group[ + str( + Path(str(self.data.store_path)) + .relative_to(str(anndata_group.store_path)) + .parent + ) + ] + return sparse_dataset(sparse_group).to_memory() + return super().copy() + + def _set_many(self, i: Iterable[int], j: Iterable[int], x): + """\ + Sets value at each (i, j) to x + + Here (i,j) index major and minor respectively, + and must not contain duplicate entries. + """ + # Scipy 1.3+ compat + n_samples = 1 if np.isscalar(x) else len(x) + offsets = self._offsets(i, j, n_samples) + + if -1 not in offsets: + # make a list for interaction with h5py + offsets = list(offsets) + # only affects existing non-zero cells + self.data[offsets] = x + return + + else: + msg = "You cannot change the sparsity structure of a SparseDataset." + raise ValueError(msg) + # replace where possible + # mask = offsets > -1 + # # offsets[mask] + # bool_data_mask = np.zeros(len(self.data), dtype=bool) + # bool_data_mask[offsets[mask]] = True + # self.data[bool_data_mask] = x[mask] + # # self.data[offsets[mask]] = x[mask] + # # only insertions remain + # mask = ~mask + # i = i[mask] + # i[i < 0] += M + # j = j[mask] + # j[j < 0] += N + # self._insert_many(i, j, x[mask]) + + def _zero_many(self, i: Sequence[int], j: Sequence[int]): + """\ + Sets value at each (i, j) to zero, preserving sparsity structure. + + Here (i,j) index major and minor respectively. + """ + offsets = self._offsets(i, j, len(i)) + + # only assign zeros to the existing sparsity structure + self.data[list(offsets[offsets > -1])] = 0 + + def _offsets( + self, i: Iterable[int], j: Iterable[int], n_samples: int + ) -> np.ndarray: + i, j, M, N = self._prepare_indices(i, j) + offsets = np.empty(n_samples, dtype=self.indices.dtype) + ret = _sparsetools.csr_sample_offsets( + M, N, self.indptr, self.indices, n_samples, i, j, offsets + ) + if ret == 1: + # rinse and repeat + self.sum_duplicates() + _sparsetools.csr_sample_offsets( + M, N, self.indptr, self.indices, n_samples, i, j, offsets + ) + return offsets + + def _get_contiguous_compressed_slice( + self, s: slice + ) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + new_indptr = self.indptr[s.start : s.stop + 1] + # If indptr is cached, we need to make a copy of the subset + # so as not to alter the underlying cached data. + if isinstance(self.indptr, np.ndarray): + new_indptr = new_indptr.copy() + + start = new_indptr[0] + stop = new_indptr[-1] + + new_indptr -= start + + new_data = self.data[start:stop] + new_indices = self.indices[start:stop] + + return new_data, new_indices, new_indptr + + +class backed_csr_matrix(BackedSparseMatrix, ss.csr_matrix): + def _get_intXslice(self, row: int, col: slice) -> ss.csr_matrix: + return ss.csr_matrix( + get_compressed_vector(self, row), shape=(1, self.shape[1]) + )[:, col] + + def _get_sliceXslice(self, row: slice, col: slice) -> ss.csr_matrix: + row = _fix_slice_bounds(row, self.shape[0]) + col = _fix_slice_bounds(col, self.shape[1]) + + out_shape = ( + slice_len(row, self.shape[0]), + slice_len(col, self.shape[1]), + ) + if out_shape[0] == 1: + return self._get_intXslice(slice_as_int(row, self.shape[0]), col) + if row.step != 1: + return self._get_arrayXslice(np.arange(*row.indices(self.shape[0])), col) + res = ss.csr_matrix( + self._get_contiguous_compressed_slice(row), + shape=(out_shape[0], self.shape[1]), + ) + return res if out_shape[1] == self.shape[1] else res[:, col] + + def _get_arrayXslice(self, row: Sequence[int], col: slice) -> ss.csr_matrix: + idxs = np.asarray(row) + if len(idxs) == 0: + return ss.csr_matrix((0, self.shape[1])) + if idxs.dtype == bool: + idxs = np.where(idxs) + return ss.csr_matrix( + get_compressed_vectors(self, idxs), shape=(len(idxs), self.shape[1]) + )[:, col] + + +class backed_csc_matrix(BackedSparseMatrix, ss.csc_matrix): + def _get_sliceXint(self, row: slice, col: int) -> ss.csc_matrix: + return ss.csc_matrix( + get_compressed_vector(self, col), shape=(self.shape[0], 1) + )[row, :] + + def _get_sliceXslice(self, row: slice, col: slice) -> ss.csc_matrix: + row = _fix_slice_bounds(row, self.shape[0]) + col = _fix_slice_bounds(col, self.shape[1]) + + out_shape = ( + slice_len(row, self.shape[0]), + slice_len(col, self.shape[1]), + ) + if out_shape[1] == 1: + return self._get_sliceXint(row, slice_as_int(col, self.shape[1])) + if col.step != 1: + return self._get_sliceXarray(row, np.arange(*col.indices(self.shape[1]))) + res = ss.csc_matrix( + self._get_contiguous_compressed_slice(col), + shape=(self.shape[0], out_shape[1]), + ) + return res if out_shape[0] == self.shape[0] else res[row, :] + + def _get_sliceXarray(self, row: slice, col: Sequence[int]) -> ss.csc_matrix: + idxs = np.asarray(col) + if len(idxs) == 0: + return ss.csc_matrix((self.shape[0], 0)) + if idxs.dtype == bool: + idxs = np.where(idxs) + return ss.csc_matrix( + get_compressed_vectors(self, idxs), shape=(self.shape[0], len(idxs)) + )[row, :] + + +FORMATS = [ + BackedFormat("csr", backed_csr_matrix, ss.csr_matrix), + BackedFormat("csc", backed_csc_matrix, ss.csc_matrix), + BackedFormat("csr", backed_csr_matrix, ss.csr_array), + BackedFormat("csc", backed_csc_matrix, ss.csc_array), +] + + +def slice_len(s: slice, l: int) -> int: + """Returns length of `a[s]` where `len(a) == l`.""" + return len(range(*s.indices(l))) + + +def slice_as_int(s: slice, l: int) -> int: + """Converts slices of length 1 to the integer index they’ll access.""" + out = list(range(*s.indices(l))) + assert len(out) == 1 + return out[0] + + +def get_compressed_vectors( + x: BackedSparseMatrix, row_idxs: Iterable[int] +) -> tuple[Sequence, Sequence, Sequence]: + indptr_slices = [slice(*(x.indptr[i : i + 2])) for i in row_idxs] + # HDF5 cannot handle out-of-order integer indexing + if isinstance(x.data, ZarrArray): + as_np_indptr = np.concatenate([ + np.arange(s.start, s.stop) for s in indptr_slices + ]) + data = x.data[as_np_indptr] + indices = x.indices[as_np_indptr] + else: + data = np.concatenate([x.data[s] for s in indptr_slices]) + indices = np.concatenate([x.indices[s] for s in indptr_slices]) + indptr = list(accumulate(chain((0,), (s.stop - s.start for s in indptr_slices)))) + return data, indices, indptr + + +def get_compressed_vectors_for_slices( + x: BackedSparseMatrix, slices: Iterable[slice] +) -> tuple[Sequence, Sequence, Sequence]: + indptr_indices = [x.indptr[slice(s.start, s.stop + 1)] for s in slices] + indptr_limits = [slice(i[0], i[-1]) for i in indptr_indices] + # HDF5 cannot handle out-of-order integer indexing + if isinstance(x.data, ZarrArray): + indptr_int = np.concatenate([np.arange(s.start, s.stop) for s in indptr_limits]) + data = x.data[indptr_int] + indices = x.indices[indptr_int] + else: + data = np.concatenate([x.data[s] for s in indptr_limits]) + indices = np.concatenate([x.indices[s] for s in indptr_limits]) + # Need to track the size of the gaps in the slices to each indptr subselection + gaps = (s1.start - s0.stop for s0, s1 in pairwise(indptr_limits)) + offsets = accumulate(chain([indptr_limits[0].start], gaps)) + start_indptr = indptr_indices[0] - next(offsets) + if len(slices) < 2: # there is only one slice so no need to concatenate + return data, indices, start_indptr + end_indptr = np.concatenate([ + s[1:] - o for s, o in zip(indptr_indices[1:], offsets, strict=True) + ]) + indptr = np.concatenate([start_indptr, end_indptr]) + return data, indices, indptr + + +def get_compressed_vector( + x: BackedSparseMatrix, idx: int +) -> tuple[Sequence, Sequence, Sequence]: + s = slice(*(x.indptr[idx : idx + 2])) + data = x.data[s] + indices = x.indices[s] + indptr = [0, len(data)] + return data, indices, indptr + + +def subset_by_major_axis_mask( + mtx: _cs_matrix, mask: np.ndarray +) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + slices = np.ma.extras._ezclump(mask) + + def mean_slice_length(slices): + return floor(sum(s.stop - s.start for s in slices) / len(slices)) + + # heuristic for whether slicing should be optimized + if len(slices) > 0: + if mean_slice_length(slices) <= 7: + return get_compressed_vectors(mtx, np.where(mask)[0]) + else: + return get_compressed_vectors_for_slices(mtx, slices) + return [], [], [0] + + +def get_memory_class( + format: Literal["csr", "csc"], *, use_sparray_in_io: bool = False +) -> type[_cs_matrix]: + for fmt, _, memory_class in FORMATS: + if format == fmt and ( + (use_sparray_in_io and issubclass(memory_class, CSArray)) + or (not use_sparray_in_io and issubclass(memory_class, CSMatrix)) + ): + return memory_class + msg = f"Format string {format} is not supported." + raise ValueError(msg) + + +def get_backed_class( + format: Literal["csr", "csc"], *, use_sparray_in_io: bool = False +) -> type[BackedSparseMatrix]: + for fmt, backed_class, _ in FORMATS: + if format == fmt and ( + (use_sparray_in_io and issubclass(backed_class, CSArray)) + or (not use_sparray_in_io and issubclass(backed_class, CSMatrix)) + ): + return backed_class + msg = f"Format string {format} is not supported." + raise ValueError(msg) + + +def _get_group_format(group: GroupStorageType) -> str: + if "h5sparse_format" in group.attrs: + # TODO: Warn about an old format + # If this is only just going to be public, I could insist it's not like this + return _read_attr(group.attrs, "h5sparse_format") + else: + # Should this be an extra field? + return _read_attr(group.attrs, "encoding-type").replace("_matrix", "") + + +# Check for the overridden few methods above in our BackedSparseMatrix subclasses +def is_sparse_indexing_overridden( + format: Literal["csr", "csc"], row: Index1D, col: Index1D +): + major_indexer, minor_indexer = (row, col) if format == "csr" else (col, row) + return isinstance(minor_indexer, slice) and ( + isinstance(major_indexer, int | np.integer | slice) + or (isinstance(major_indexer, np.ndarray) and major_indexer.ndim == 1) + ) + + +def validate_indices( + mtx: BackedSparseMatrix, indices: tuple[Index1D, Index1D] +) -> tuple[Index1D, Index1D]: + if hasattr(mtx, "_validate_indices"): + res = mtx._validate_indices(indices) + return res[0] if SCIPY_1_15 else res + # https://github.com/scipy/scipy/pull/23267 + elif Version(version("scipy")) >= Version("1.17.0rc0"): + from scipy.sparse._index import _validate_indices # type: ignore + + return _validate_indices(indices, mtx.shape, mtx.format)[0] + else: # pragma: no cover + msg = "Cannot validate indices" + raise RuntimeError(msg) + + +class BaseCompressedSparseDataset(abc._AbstractCSDataset, ABC): + _group: GroupStorageType + _should_cache_indptr: bool + + def __init__(self, group: GroupStorageType, *, should_cache_indptr: bool = True): + type(self)._check_group_format(group) + self._group = group + self._should_cache_indptr = should_cache_indptr + + @property + def group(self) -> GroupStorageType: + """The group underlying the backed matrix.""" + return self._group + + @group.setter + def group(self, val): + msg = f"Do not reset group on a {type(self)} with {val}. Instead use `sparse_dataset` to make a new class." + raise AttributeError(msg) + + @property + def backend(self) -> Literal["zarr", "hdf5"]: + """Which file type is used on-disk.""" + if isinstance(self.group, ZarrGroup): + return "zarr" + elif isinstance(self.group, H5Group): + return "hdf5" + else: + msg = f"Unknown group type {type(self.group)}" + raise ValueError(msg) + + @property + def dtype(self) -> np.dtype: + """The :class:`numpy.dtype` of the `data` attribute of the sparse matrix.""" + return self._data.dtype + + @classmethod + def _check_group_format(cls, group): + group_format = _get_group_format(group) + assert group_format == cls.format + + @property + def _name(self) -> str: + """Name of the group.""" + return self.group.name + + @property + def shape(self) -> tuple[int, int]: + """Shape of the matrix read off disk.""" + shape = _read_attr(self.group.attrs, "shape", None) + if shape is None: + # TODO warn + shape = self.group.attrs.get("h5sparse_shape") + return tuple(map(int, shape)) + + def __repr__(self) -> str: + name = type(self).__name__.removeprefix("_") + return f"{name}: backend {self.backend}, shape {self.shape}, data_dtype {self.dtype}" + + def __getitem__(self, index: Index | tuple[()]) -> float | CSMatrix | CSArray: + indices = self._normalize_index(index) + row, col = indices + mtx = self._to_backed() + row_sp_matrix_validated, col_sp_matrix_validated = validate_indices( + mtx, indices + ) + + # Handle masked indexing along major axis + if self.format == "csr" and np.array(row).dtype == bool: + sub = ss.csr_matrix( + subset_by_major_axis_mask(mtx, row), shape=(row.sum(), mtx.shape[1]) + )[:, col] + elif self.format == "csc" and np.array(col).dtype == bool: + sub = ss.csc_matrix( + subset_by_major_axis_mask(mtx, col), shape=(mtx.shape[0], col.sum()) + )[row, :] + # read into memory data if we do not override access methods + elif not is_sparse_indexing_overridden( + self.format, row_sp_matrix_validated, col_sp_matrix_validated + ): + sub = self.to_memory()[row_sp_matrix_validated, col_sp_matrix_validated] + else: + sub = mtx[row, col] + + # If indexing is array x array it returns a backed_sparse_matrix + # Not sure what the performance is on that operation + # Also need to check if memory format is not matrix + mtx_fmt = get_memory_class( + self.format, use_sparray_in_io=settings.use_sparse_array_on_read + ) + must_convert_to_array = issubclass(mtx_fmt, CSArray) and not isinstance( + sub, CSArray + ) + if isinstance(sub, BackedSparseMatrix) or must_convert_to_array: + return mtx_fmt(sub) + else: + return sub + + def _normalize_index( + self, index: Index | tuple[()] + ) -> tuple[np.ndarray, np.ndarray]: + if isinstance(index, tuple) and not len(index): + index = slice(None) + row, col = unpack_index(index) + if all(isinstance(x, Iterable) for x in (row, col)): + row, col = np.ix_(row, col) + return row, col + + def __setitem__(self, index: Index | tuple[()], value) -> None: + msg = ( + "__setitem__ for backed sparse will be removed in the next anndata release." + ) + warnings.warn(msg, FutureWarning, stacklevel=2) + row, col = self._normalize_index(index) + mock_matrix = self._to_backed() + mock_matrix[row, col] = value + + # TODO: split to other classes? + def append(self, sparse_matrix: CSMatrix | CSArray) -> None: # noqa: PLR0912, PLR0915 + """Append an in-memory or on-disk sparse matrix to the current object's store. + + Parameters + ---------- + sparse_matrix + The matrix to append. + + Raises + ------ + NotImplementedError + If the matrix to append is not one of :class:`~scipy.sparse.csr_array`, :class:`~scipy.sparse.csc_array`, :class:`~scipy.sparse.csr_matrix`, or :class:`~scipy.sparse.csc_matrix`. + ValueError + If both the on-disk and to-append matrices are not of the same format i.e., `csr` or `csc`. + OverflowError + If the underlying data store has a 32 bit indptr, and the new matrix is too large to fit in it i.e., would cause a 64 bit `indptr` to be written. + AssertionError + If the on-disk data does not have `csc` or `csr` format. + """ + # Prep variables + shape = self.shape + if isinstance(sparse_matrix, BaseCompressedSparseDataset): + sparse_matrix = sparse_matrix._to_backed() + + # Check input + if not ss.issparse(sparse_matrix): + msg = ( + "Currently, only sparse matrices of equivalent format can be " + "appended to a SparseDataset." + ) + raise NotImplementedError(msg) + if self.format not in {"csr", "csc"}: + msg = f"The append method for format {self.format} is not implemented." + raise NotImplementedError(msg) + if self.format != sparse_matrix.format: + msg = ( + f"Matrices must have same format. Currently are " + f"{self.format!r} and {sparse_matrix.format!r}" + ) + raise ValueError(msg) + [indptr_offset] = self.group["indices"].shape + if self.group["indptr"].dtype == np.int32: + new_nnz = indptr_offset + sparse_matrix.indices.shape[0] + if new_nnz >= np.iinfo(np.int32).max: + msg = ( + "This array was written with a 32 bit intptr, but is now large " + "enough to require 64 bit values. Please recreate the array with " + "a 64 bit indptr." + ) + raise OverflowError(msg) + + # shape + if self.format == "csr": + assert shape[1] == sparse_matrix.shape[1], ( + "CSR matrices must have same size of dimension 1 to be appended." + ) + new_shape = (shape[0] + sparse_matrix.shape[0], shape[1]) + elif self.format == "csc": + assert shape[0] == sparse_matrix.shape[0], ( + "CSC matrices must have same size of dimension 0 to be appended." + ) + new_shape = (shape[0], shape[1] + sparse_matrix.shape[1]) + else: + msg = "We forgot to update this branching to a new format" + raise AssertionError(msg) + if "h5sparse_shape" in self.group.attrs: + del self.group.attrs["h5sparse_shape"] + self.group.attrs["shape"] = new_shape + + # data + data = self.group["data"] + orig_data_size = data.shape[0] + data.resize((orig_data_size + sparse_matrix.data.shape[0],)) + # see https://github.com/zarr-developers/zarr-python/discussions/2712 for why we need to read first + append_data = sparse_matrix.data + append_indices = sparse_matrix.indices + if isinstance(sparse_matrix.data, ZarrArray) and not is_zarr_v2(): + data[orig_data_size:] = append_data[...] + else: + data[orig_data_size:] = append_data + # indptr + indptr = self.group["indptr"] + orig_data_size = indptr.shape[0] + indptr.resize((orig_data_size + sparse_matrix.indptr.shape[0] - 1,)) + indptr[orig_data_size:] = ( + sparse_matrix.indptr[1:].astype(np.int64) + indptr_offset + ) + + # indices + if isinstance(sparse_matrix.data, ZarrArray) and not is_zarr_v2(): + append_indices = append_indices[...] + indices = self.group["indices"] + orig_data_size = indices.shape[0] + indices.resize((orig_data_size + sparse_matrix.indices.shape[0],)) + indices[orig_data_size:] = append_indices + + # Clear cached property + for attr in ["_indptr", "_indices", "_data"]: + if hasattr(self, attr): + delattr(self, attr) + + @cached_property + def _indptr(self) -> np.ndarray: + """\ + Other than `data` and `indices`, this is only as long as the major axis + + It should therefore fit into memory, so we cache it for faster access. + """ + if self._should_cache_indptr: + return self.group["indptr"][...] + return self.group["indptr"] + + @cached_property + def _indices(self) -> H5Array | ZarrArray: + """\ + Cache access to the indices to prevent unnecessary reads of the zarray + """ + return self.group["indices"] + + @cached_property + def _data(self) -> H5Array | ZarrArray: + """\ + Cache access to the data to prevent unnecessary reads of the zarray + """ + return self.group["data"] + + def _to_backed(self) -> BackedSparseMatrix: + format_class = get_backed_class(self.format) + mtx = format_class(self.shape, dtype=self.dtype) + mtx.data = self._data + mtx.indices = self._indices + mtx.indptr = self._indptr + return mtx + + def to_memory(self) -> CSMatrix | CSArray: + format_class = get_memory_class( + self.format, use_sparray_in_io=settings.use_sparse_array_on_read + ) + mtx = format_class(self.shape, dtype=self.dtype) + mtx.data = self._data[...] + mtx.indices = self._indices[...] + mtx.indptr = self._indptr + return mtx + + +class _CSRDataset(BaseCompressedSparseDataset, abc.CSRDataset): + """Internal concrete version of :class:`anndata.abc.CSRDataset`.""" + + +class _CSCDataset(BaseCompressedSparseDataset, abc.CSCDataset): + """Internal concrete version of :class:`anndata.abc.CSRDataset`.""" + + +def sparse_dataset( + group: GroupStorageType, + *, + should_cache_indptr: bool = True, +) -> abc.CSRDataset | abc.CSCDataset: + """Generates a backed mode-compatible sparse dataset class. + + Parameters + ---------- + group + The backing group store. + should_cache_indptr + Whether or not to cache the indptr for repeated reuse as a :class:`numpy.ndarray`. + The default is `True` but one might set it to false if the dataset is repeatedly reopened + using this command, and then only a subset is read in before closing again. + See https://github.com/scverse/anndata/blob/3c489b979086c39c59d3eb5dad90ebacce3b9a80/src/anndata/_io/specs/lazy_methods.py#L85-L95 + for the target use-case. + + Returns + ------- + Sparse dataset class. + + Example + ------- + + First we'll need a stored dataset: + + >>> import scanpy as sc + >>> import h5py + >>> from anndata.io import sparse_dataset + >>> from anndata.io import read_elem + >>> sc.datasets.pbmc68k_reduced().raw.to_adata().write_h5ad("pbmc.h5ad") + + Initialize a sparse dataset from storage + + >>> f = h5py.File("pbmc.h5ad") + >>> X = sparse_dataset(f["X"]) + >>> X + CSRDataset: backend hdf5, shape (700, 765), data_dtype float32 + + Indexing returns sparse matrices + + >>> X[100:200] # doctest: +ELLIPSIS + <...sparse matrix of...float32...with 25003 stored elements...> + + These can also be used inside of an AnnData object, no need for backed mode + + >>> from anndata import AnnData + >>> adata = AnnData( + ... layers={"backed": X}, obs=read_elem(f["obs"]), var=read_elem(f["var"]) + ... ) + >>> adata.layers["backed"] + CSRDataset: backend hdf5, shape (700, 765), data_dtype float32 + + Indexing access (i.e., from views) brings selection into memory + + >>> adata[adata.obs["bulk_labels"] == "CD56+ NK"].layers[ + ... "backed" + ... ] # doctest: +ELLIPSIS + <...sparse matrix of...float32...with 7340 stored elements...> + """ + encoding_type = _get_group_format(group) + if encoding_type == "csr": + return _CSRDataset(group, should_cache_indptr=should_cache_indptr) + elif encoding_type == "csc": + return _CSCDataset(group, should_cache_indptr=should_cache_indptr) + msg = f"Unknown encoding type {encoding_type}" + raise ValueError(msg) + + +@_subset.register(BaseCompressedSparseDataset) +def subset_sparsedataset( + d, subset_idx: tuple[Index1DNorm] | tuple[Index1DNorm, Index1DNorm] +): + return d[subset_idx] diff --git a/.venv/lib/python3.11/site-packages/anndata/_core/storage.py b/.venv/lib/python3.11/site-packages/anndata/_core/storage.py new file mode 100644 index 0000000000000000000000000000000000000000..e3e00ba7d2cf89a41c02dba26b259af59e17d4dd --- /dev/null +++ b/.venv/lib/python3.11/site-packages/anndata/_core/storage.py @@ -0,0 +1,74 @@ +from __future__ import annotations + +import warnings +from typing import TYPE_CHECKING, get_args + +import numpy as np +import pandas as pd +from scipy import sparse + +from anndata.compat import CSArray, CSMatrix + +from .._warnings import ImplicitModificationWarning +from ..compat import XDataset +from ..utils import ( + ensure_df_homogeneous, + join_english, + raise_value_error_if_multiindex_columns, +) +from .xarray import Dataset2D + +if TYPE_CHECKING: + from typing import Any + + +def coerce_array( + value: Any, + *, + name: str, + allow_df: bool = False, + allow_array_like: bool = False, +): + """Coerce arrays stored in layers/X, and aligned arrays ({obs,var}{m,p}).""" + from ..typing import ArrayDataStructureTypes + + # If value is a scalar and we allow that, return it + if allow_array_like and np.isscalar(value): + return value + # If value is one of the allowed types, return it + array_data_structure_types = get_args(ArrayDataStructureTypes) + if isinstance(value, XDataset): + value = Dataset2D(value) + if isinstance(value, (*array_data_structure_types, Dataset2D)): + if isinstance(value, np.matrix): + msg = f"{name} should not be a np.matrix, use np.ndarray instead." + warnings.warn(msg, ImplicitModificationWarning, stacklevel=3) + value = value.A + return value + is_non_csc_r_array_or_matrix = ( + (isinstance(value, base) and not isinstance(value, csr_c_format)) + for base, csr_c_format in [ + (sparse.spmatrix, CSMatrix), + (sparse.sparray, CSArray), + ] + ) + if any(is_non_csc_r_array_or_matrix): + msg = f"Only CSR and CSC {'matrices' if isinstance(value, sparse.spmatrix) else 'arrays'} are supported." + raise ValueError(msg) + if isinstance(value, pd.DataFrame): + if allow_df: + raise_value_error_if_multiindex_columns(value, name) + return value if allow_df else ensure_df_homogeneous(value, name) + # if value is an array-like object, try to convert it + e = None + if allow_array_like: + try: + # TODO: asarray? asanyarray? + return np.array(value) + except (ValueError, TypeError) as _e: + e = _e + # if value isn’t the right type or convertible, raise an error + msg = f"{name} needs to be of one of {join_english(map(str, array_data_structure_types))}, not {type(value)}." + if e is not None: + msg += " (Failed to convert it to an array, see above for details.)" + raise ValueError(msg) from e diff --git a/.venv/lib/python3.11/site-packages/anndata/_core/views.py b/.venv/lib/python3.11/site-packages/anndata/_core/views.py new file mode 100644 index 0000000000000000000000000000000000000000..330e83f88096962a0b04a1dab3c37ea1489ac3e6 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/anndata/_core/views.py @@ -0,0 +1,486 @@ +from __future__ import annotations + +import warnings +from contextlib import contextmanager +from copy import deepcopy +from functools import reduce, singledispatch, wraps +from typing import TYPE_CHECKING, Literal + +import numpy as np +import pandas as pd +from pandas.api.types import is_bool_dtype +from scipy import sparse + +from anndata._warnings import ImplicitModificationWarning + +from .._settings import settings +from ..compat import ( + AwkArray, + CupyArray, + CupyCSCMatrix, + CupyCSRMatrix, + DaskArray, + ZappyArray, +) +from .access import ElementRef +from .xarray import Dataset2D + +if TYPE_CHECKING: + from collections.abc import Callable, Iterable, KeysView, Sequence + from typing import Any, ClassVar + + from numpy.typing import NDArray + + from anndata import AnnData + + from ..compat import Index1DNorm + + +@contextmanager +def view_update(adata_view: AnnData, attr_name: str, keys: tuple[str, ...]): + """Context manager for updating a view of an AnnData object. + + Contains logic for "actualizing" a view. Yields the object to be modified in-place. + + Parameters + ---------- + adata_view + A view of an AnnData + attr_name + Name of the attribute being updated + keys + Keys to the attribute being updated + + Yields + ------ + + `adata.attr[key1][key2][keyn]...` + """ + new = adata_view.copy() + attr = getattr(new, attr_name) + container = reduce(lambda d, k: d[k], keys, attr) + yield container + adata_view._init_as_actual(new) + + +class _SetItemMixin: + """\ + Class which (when values are being set) lets their parent AnnData view know, + so it can make a copy of itself. + This implements copy-on-modify semantics for views of AnnData objects. + """ + + _view_args: ElementRef | None + + def __setitem__(self, idx: Any, value: Any): + if self._view_args is None: + super().__setitem__(idx, value) + else: + warnings.warn( + f"Trying to modify attribute `.{self._view_args.attrname}` of view, " + "initializing view as actual.", + ImplicitModificationWarning, + stacklevel=2, + ) + with view_update(*self._view_args) as container: + container[idx] = value + + +class _ViewMixin(_SetItemMixin): + def __init__( + self, + *args, + view_args: tuple[AnnData, str, tuple[str, ...]] | None = None, + **kwargs, + ): + if view_args is not None: + view_args = ElementRef(*view_args) + self._view_args = view_args + super().__init__(*args, **kwargs) + + # TODO: This makes `deepcopy(obj)` return `obj._view_args.parent._adata_ref`, fix it + def __deepcopy__(self, memo): + parent, attrname, _keys = self._view_args + return deepcopy(getattr(parent._adata_ref, attrname)) + + +_UFuncMethod = Literal["__call__", "reduce", "reduceat", "accumulate", "outer", "inner"] + + +class ArrayView(_SetItemMixin, np.ndarray): + def __new__( + cls, + input_array: Sequence[Any], + view_args: tuple[AnnData, str, tuple[str, ...]] | None = None, + ): + arr = np.asanyarray(input_array).view(cls) + + if view_args is not None: + view_args = ElementRef(*view_args) + arr._view_args = view_args + return arr + + def __array_finalize__(self, obj: np.ndarray | None): + if obj is not None: + self._view_args = getattr(obj, "_view_args", None) + + def __array_ufunc__( + self: ArrayView, + ufunc: Callable[..., Any], + method: _UFuncMethod, + *inputs, + out: tuple[np.ndarray, ...] | None = None, + **kwargs, + ) -> np.ndarray: + """Makes numpy ufuncs convert all instances of views to plain arrays. + + See https://numpy.org/devdocs/user/basics.subclassing.html#array-ufunc-for-ufuncs + """ + + def convert_all(arrs: Iterable[np.ndarray]) -> Iterable[np.ndarray]: + return ( + arr.view(np.ndarray) if isinstance(arr, ArrayView) else arr + for arr in arrs + ) + + if out is None: + outputs = (None,) * ufunc.nout + else: + out = outputs = tuple(convert_all(out)) + + results = super().__array_ufunc__( + ufunc, method, *convert_all(inputs), out=out, **kwargs + ) + if results is NotImplemented: + return NotImplemented + + if ufunc.nout == 1: + results = (results,) + results = tuple( + (np.asarray(result) if output is None else output) + for result, output in zip(results, outputs, strict=True) + ) + return results[0] if len(results) == 1 else results + + def keys(self) -> KeysView[str]: + # it’s a structured array + return self.dtype.names + + def copy(self, order: str = "C") -> np.ndarray: + # we want a conventional array + return np.array(self) + + def toarray(self) -> np.ndarray: + return self.copy() + + +# Extends DaskArray +# Calls parent __new__ constructor since +# even calling astype on a dask array +# needs a .compute() call to actually happen. +# So no construction by view casting like ArrayView +class DaskArrayView(_SetItemMixin, DaskArray): + def __new__( + cls, + input_array: DaskArray, + view_args: tuple[AnnData, str, tuple[str, ...]] | None = None, + ): + arr = super().__new__( + cls, + dask=input_array.dask, + name=input_array.name, + chunks=input_array.chunks, + dtype=input_array.dtype, + meta=input_array._meta, + shape=input_array.shape, + ) + if view_args is not None: + view_args = ElementRef(*view_args) + arr._view_args = view_args + + return arr + + def __array_finalize__(self, obj: DaskArray | None): + if obj is not None: + self._view_args = getattr(obj, "_view_args", None) + + def keys(self) -> KeysView[str]: + # it’s a structured array + return self.dtype.names + + +# Unlike array views, SparseCSRMatrixView and SparseCSCMatrixView +# do not propagate through subsetting +class SparseCSRMatrixView(_ViewMixin, sparse.csr_matrix): + # https://github.com/scverse/anndata/issues/656 + def copy(self) -> sparse.csr_matrix: + return sparse.csr_matrix(self).copy() + + +class SparseCSCMatrixView(_ViewMixin, sparse.csc_matrix): + # https://github.com/scverse/anndata/issues/656 + def copy(self) -> sparse.csc_matrix: + return sparse.csc_matrix(self).copy() + + +class SparseCSRArrayView(_ViewMixin, sparse.csr_array): + # https://github.com/scverse/anndata/issues/656 + def copy(self) -> sparse.csr_array: + return sparse.csr_array(self).copy() + + +class SparseCSCArrayView(_ViewMixin, sparse.csc_array): + # https://github.com/scverse/anndata/issues/656 + def copy(self) -> sparse.csc_array: + return sparse.csc_array(self).copy() + + +class CupySparseCSRView(_ViewMixin, CupyCSRMatrix): + def copy(self) -> CupyCSRMatrix: + return CupyCSRMatrix(self).copy() + + +class CupySparseCSCView(_ViewMixin, CupyCSCMatrix): + def copy(self) -> CupyCSCMatrix: + return CupyCSCMatrix(self).copy() + + +class CupyArrayView(_ViewMixin, CupyArray): + def __new__( + cls, + input_array: Sequence[Any], + view_args: tuple[AnnData, str, tuple[str, ...]] | None = None, + ): + import cupy as cp + + arr = cp.asarray(input_array).view(type=cls) + + if view_args is not None: + view_args = ElementRef(*view_args) + arr._view_args = view_args + return arr + + def copy(self) -> CupyArray: + import cupy as cp + + return cp.array(self).copy() + + +class DictView(_ViewMixin, dict): + pass + + +class DataFrameView(_ViewMixin, pd.DataFrame): + _metadata: ClassVar = ["_view_args"] + + @wraps(pd.DataFrame.drop) + def drop(self, *args, inplace: bool = False, **kw): + if not inplace: + return self.copy().drop(*args, **kw) + with view_update(*self._view_args) as df: + df.drop(*args, inplace=True, **kw) + + def __setattr__(self, key: str, value: Any): + if key == "index": + warnings.warn( + f"Trying to modify {key} of attribute `.{self._view_args.attrname}` of view, " + "initializing view as actual.", + ImplicitModificationWarning, + stacklevel=2, + ) + with view_update(*self._view_args) as container: + setattr(container, key, value) + else: + super().__setattr__(key, value) + + +@singledispatch +def as_view(obj, view_args): + msg = f"No view type has been registered for {type(obj)}" + raise NotImplementedError(msg) + + +@as_view.register(np.ndarray) +def as_view_array(array, view_args): + return ArrayView(array, view_args=view_args) + + +@as_view.register(DaskArray) +def as_view_dask_array(array, view_args): + return DaskArrayView(array, view_args=view_args) + + +@as_view.register(pd.DataFrame) +def as_view_df(df, view_args): + if settings.remove_unused_categories: + for col in df.columns: + if isinstance(df[col].dtype, pd.CategoricalDtype): + # TODO: this mode is going away + with pd.option_context("mode.chained_assignment", None): + df[col] = df[col].cat.remove_unused_categories() + return DataFrameView(df, view_args=view_args) + + +@as_view.register(sparse.csr_matrix) +def as_view_csr_matrix(mtx, view_args): + return SparseCSRMatrixView(mtx, view_args=view_args) + + +@as_view.register(sparse.csc_matrix) +def as_view_csc_matrix(mtx, view_args): + return SparseCSCMatrixView(mtx, view_args=view_args) + + +@as_view.register(sparse.csr_array) +def as_view_csr_array(mtx, view_args): + return SparseCSRArrayView(mtx, view_args=view_args) + + +@as_view.register(sparse.csc_array) +def as_view_csc_array(mtx, view_args): + return SparseCSCArrayView(mtx, view_args=view_args) + + +@as_view.register(dict) +def as_view_dict(d, view_args): + return DictView(d, view_args=view_args) + + +@as_view.register(ZappyArray) +def as_view_zappy(z, view_args): + # Previous code says ZappyArray works as view, + # but as far as I can tell they’re immutable. + return z + + +@as_view.register(CupyArray) +def as_view_cupy(array, view_args): + return CupyArrayView(array, view_args=view_args) + + +@as_view.register(CupyCSRMatrix) +def as_view_cupy_csr(mtx, view_args): + return CupySparseCSRView(mtx, view_args=view_args) + + +@as_view.register(CupyCSCMatrix) +def as_view_cupy_csc(mtx, view_args): + return CupySparseCSCView(mtx, view_args=view_args) + + +@as_view.register(Dataset2D) +def _(a: Dataset2D, view_args): + return a + + +try: + import weakref + + from ..compat import awkward as ak + + # Registry to store weak references from AwkwardArrayViews to their parent AnnData container + _registry = weakref.WeakValueDictionary() + _PARAM_NAME = "_view_args" + + class AwkwardArrayView(_ViewMixin, AwkArray): + @property + def _view_args(self): + """Override _view_args to retrieve the values from awkward arrays parameters. + + Awkward arrays cannot be subclassed like other python objects. Instead subclasses need + to be attached as "behavior". These "behaviors" cannot take any additional parameters (as we do + for other data types to store `_view_args`). Therefore, we need to store `_view_args` using awkward's + parameter mechanism. These parameters need to be json-serializable, which is why we can't store + ElementRef directly, but need to replace the reference to the parent AnnDataView container with a weak + reference. + """ + parent_key, attrname, keys = self.layout.parameter(_PARAM_NAME) + parent = _registry[parent_key] + return ElementRef(parent, attrname, keys) + + def __copy__(self) -> AwkArray: + """ + Turn the AwkwardArrayView into an actual AwkwardArray with no special behavior. + + Need to override __copy__ instead of `.copy()` as awkward arrays don't implement `.copy()` + and are copied using python's standard copy mechanism in `aligned_mapping.py`. + """ + array = self + # makes a shallow copy and removes the reference to the original AnnData object + array = ak.with_parameter(self, _PARAM_NAME, None) + array = ak.with_parameter(array, "__list__", None) + return array + + @as_view.register(AwkArray) + def as_view_awkarray(array, view_args): + parent, attrname, keys = view_args + parent_key = f"target-{id(parent)}" + _registry[parent_key] = parent + # TODO: See https://github.com/scverse/anndata/pull/647#discussion_r963494798_ for more details and + # possible strategies to stack behaviors. + # A better solution might be based on xarray-style "attrs", once this is implemented + # https://github.com/scikit-hep/awkward/issues/1391#issuecomment-1412297114 + if type(array).__name__ != "Array": + msg = ( + "Cannot create a view of an awkward array with __array__ parameter. " + "Please open an issue in the AnnData repo and describe your use-case." + ) + raise NotImplementedError(msg) + array = ak.with_parameter(array, _PARAM_NAME, (parent_key, attrname, keys)) + array = ak.with_parameter(array, "__list__", "AwkwardArrayView") + return array + + ak.behavior["AwkwardArrayView"] = AwkwardArrayView + +except ImportError: + + class AwkwardArrayView: + pass + + +def _resolve_idxs( + old: tuple[Index1DNorm, Index1DNorm], + new: tuple[Index1DNorm, Index1DNorm], + adata: AnnData, +) -> tuple[Index1DNorm, Index1DNorm]: + o, v = (_resolve_idx(old[i], new[i], adata.shape[i]) for i in (0, 1)) + return o, v + + +@singledispatch +def _resolve_idx(old: Index1DNorm, new: Index1DNorm, l: Literal[0, 1]) -> Index1DNorm: + raise NotImplementedError + + +@_resolve_idx.register(np.ndarray) +def _resolve_idx_ndarray( + old: NDArray[np.bool_] | NDArray[np.integer], new: Index1DNorm, l: Literal[0, 1] +) -> NDArray[np.bool_] | NDArray[np.integer]: + if is_bool_dtype(old) and is_bool_dtype(new): + mask_new = np.zeros_like(old) + mask_new[np.flatnonzero(old)[new]] = True + return mask_new + if is_bool_dtype(old): + old = np.where(old)[0] + return old[new] + + +@_resolve_idx.register(slice) +def _resolve_idx_slice( + old: slice, new: Index1DNorm, l: Literal[0, 1] +) -> slice | NDArray[np.integer]: + if isinstance(new, slice): + return _resolve_idx_slice_slice(old, new, l) + else: + return np.arange(*old.indices(l))[new] + + +def _resolve_idx_slice_slice(old: slice, new: slice, l: Literal[0, 1]) -> slice: + r = range(*old.indices(l))[new] + # Convert back to slice + start, stop, step = r.start, r.stop, r.step + if len(r) == 0: + stop = start + elif stop < 0: + stop = None + return slice(start, stop, step) diff --git a/.venv/lib/python3.11/site-packages/anndata/_core/xarray.py b/.venv/lib/python3.11/site-packages/anndata/_core/xarray.py new file mode 100644 index 0000000000000000000000000000000000000000..c9721f773606248c84882c2a73c7487ff0cb2365 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/anndata/_core/xarray.py @@ -0,0 +1,451 @@ +from __future__ import annotations + +import warnings +from collections.abc import Hashable, Mapping +from dataclasses import dataclass +from functools import wraps +from typing import TYPE_CHECKING, Self, TypeVar, overload + +import numpy as np +import pandas as pd + +from ..compat import XDataArray, XDataset, XVariable, pandas_as_str + +if TYPE_CHECKING: + from collections.abc import Callable, Collection, Iterable, Iterator + from typing import Any, Literal + + from .._types import Dataset2DIlocIndexer + +P = TypeVar("P") +R = TypeVar("R") + + +def requires_xarray(func: Callable[P, R]) -> Callable[P, R]: + @wraps(func) + def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: + try: + import xarray # noqa: F401 + except ImportError as e: + msg = "xarray is required to read dataframes lazily. Please install xarray." + raise ImportError(msg) from e + return func(*args, **kwargs) + + return wrapper + + +class Dataset2D(Mapping[Hashable, XDataArray | Self]): + r""" + A wrapper class meant to enable working with lazy dataframe data according to + :class:`~anndata.AnnData`'s internal API. This class ensures that "dataframe-invariants" + are respected, namely that there is only one 1d dim and coord with the same name i.e., + like a :class:`pandas.DataFrame`. + + You should not have to initiate this class yourself. Setting an :class:`xarray.Dataset` + into a relevant part of the :class:`~anndata.AnnData` object will attempt to wrap that + object in this object, trying to enforce the "dataframe-invariants." + + Because xarray requires :attr:`xarray.Dataset.coords` to be in-memory, this class provides + handling for an out-of-memory index via :attr:`~anndata.experimental.backed.Dataset2D.true_index`. + This feature is helpful for loading remote data faster where the index itself may not be initially useful + for constructing the object e.g., cell ids. + """ + + @staticmethod + def _validate_shape_invariants(ds: XDataset): + """ + Validate that the dataset has only one dimension, which is the index dimension. + This is a requirement for 2D datasets. + """ + if not isinstance(ds, XDataset): + msg = f"Expected an xarray Dataset, found {type(ds)}" + raise TypeError(msg) + if (is_coords_too_long := (len(ds.coords) != 1)) or len(ds.dims) != 1: + string, length, rep = ( + ("coordinate", len(ds.coords), ds.coords) + if is_coords_too_long + else ("dimension", len(ds.dims), ds.dims) + ) + msg = f"Dataset should have exactly one {string}, found {length}: {rep}" + raise ValueError(msg) + if next(iter(ds.dims)) != next(iter(ds.coords)): + msg = f"Dataset dimension {next(iter(ds.dims))} does not match coordinate {next(iter(ds.coords))}." + raise ValueError(msg) + + def __init__(self, ds: XDataset): + Dataset2D._validate_shape_invariants(ds) + self._ds = ds + + @property + def ds(self) -> XDataset: + """The underlying :class:`xarray.Dataset`.""" + return self._ds + + def keys(self) -> list[Hashable]: + return list(iter(self.ds)) + + @property + def is_backed(self) -> bool: + """ + Check whether or not the object is backed, used to indicate if there are any in-memory objects. + Must be externally set, defaults false. + """ + return self.ds.attrs.get("is_backed", False) + + @is_backed.setter + def is_backed(self, isbacked: bool) -> None: + if not isbacked and "is_backed" in self.ds.attrs: + del self.ds.attrs["is_backed"] + else: + self.ds.attrs["is_backed"] = isbacked + + @property + def index_dim(self) -> str: + """The underlying computational index i.e., the lone coordinate dimension.""" + if len(self.ds.sizes) != 1: + msg = f"xarray Dataset should not have more than 1 dims, found {len(self.ds.sizes)} {self.ds.sizes}, {self}" + raise ValueError(msg) + return next(iter(self.ds.coords.keys())) + + @property + def true_index_dim(self) -> str: + """Key of the “true” index. + + Because xarray loads its coordinates/indexes in memory, + we allow for signaling that a given variable, which is not a coordinate, is the "true" index. + + For example, the true index may be cell names but loading these over an internet connection may not be + desirable or necessary for most use cases such as getting a quick preview of the columns or loading only + one column that isn't the index. + + This property is the key of said variable. The default is `index_dim` if this variable has not been set. + """ + return self.ds.attrs.get("indexing_key", self.index_dim) + + @true_index_dim.setter + def true_index_dim(self, val: str | None) -> None: + if val is None or (val == self.index_dim and "indexing_key" in self.ds.attrs): + del self.ds.attrs["indexing_key"] + elif val not in self.ds.dims: + if val not in self.ds.data_vars: + msg = f"Unknown variable `{val}`." + raise ValueError(msg) + self.ds.attrs["indexing_key"] = val + + @property + def xr_index(self) -> XDataArray: + """The coordinate of :attr:`anndata.experimental.backed.Dataset2D.index_dim`""" + return self.ds[self.index_dim] + + @property + def index(self) -> pd.Index: + """A :class:`pandas.Index` object corresponding to :attr:`anndata.experimental.backed.Dataset2D.index_dim`. + + :attr:`~anndata.AnnData` internally looks for :attr:`~pandas.DataFrame.index` so this ensures usability. + + Returns + ------- + The index of the of the dataframe as resolved from :attr:`~xarray.Dataset.coords`. + """ + return self.ds.indexes[self.index_dim] + + @index.setter + def index(self, val: object | pd.Index | XDataArray) -> None: + index_dim = self.index_dim + if ( + isinstance(val, pd.Index | XDataArray) + and val.name is not None + and val.name != index_dim + ): + # swap the names of the dimensions out and drop the old index variable, setting `coords` in the process if `val` came from this dataset. + self._ds = self.ds.swap_dims({index_dim: val.name}).drop_vars(index_dim) + # swapping dims only changes the name, but not the underlying value i.e., the coordinate, if the underlying value was not present in the dataset. + # If we were to `__setitem__` on `.coords` without checking, `val` could have the old `index_dim` as its `name` because it was present in the dataset. + if val.name not in self.ds.coords: + self.ds.coords[val.name] = val + self._validate_shape_invariants(self._ds) + else: + self.ds.coords[index_dim] = (index_dim, val) + # without `indexing_key` explicitly set on `self.ds.attrs`, `self.true_index_dim` will use the `self.index_dim` + if "indexing_key" in self.ds.attrs and ( + hasattr(val, "name") and val.name == self.ds.attrs["indexing_key"] + ): + del self.ds.attrs["indexing_key"] + + @property + def true_xr_index(self) -> XDataArray: + """The index :class:`~anndata.AnnData` is actually interested in e.g., cell names, for verification.""" + return self.ds[self.true_index_dim] + + @property + def true_index(self) -> pd.Index: + """:attr:`~anndata.experimental.backed.Dataset2D.true_xr_index` as a :class:`pandas.Index`.""" + idx = self.true_xr_index.to_index() + idx.name = self.true_xr_index.name + return idx + + @property + def shape(self) -> tuple[int, int]: + """:attr:`~anndata.AnnData` internally looks for :attr:`~pandas.DataFrame.shape` so this ensures usability. + + Returns + ------- + The (2D) shape of the dataframe resolved from :attr:`~xarray.Dataset.sizes`. + """ + return (self.ds.sizes[self.index_dim], len(self.ds)) + + @property + def iloc(self) -> Dataset2DIlocIndexer: + """:attr:`~anndata.AnnData` internally looks for :attr:`~pandas.DataFrame.iloc` so this ensures usability. + + Returns + ------- + Handler class for doing the iloc-style indexing using :meth:`~xarray.Dataset.isel`. + """ + + return IlocGetter(self.ds, self.index_dim) + + # See https://github.com/pydata/xarray/blob/568f3c1638d2d34373408ce2869028faa3949446/xarray/core/dataset.py#L1239-L1248 + # for typing + @overload + def __getitem__(self, key: Hashable) -> XDataArray: ... + @overload + def __getitem__(self, key: Collection[Hashable]) -> Dataset2D: ... + def __getitem__( + self, key: Mapping[Any, Any] | Hashable | Iterable[Hashable] + ) -> Dataset2D | XDataArray: + ret = self.ds.__getitem__(key) + if is_empty := (len(key) == 0 and not isinstance(key, tuple)): # empty Dataset + ret.coords[self.index_dim] = self.xr_index + if isinstance(ret, XDataset): + # If we get an xarray Dataset, we return a Dataset2D + as_2d = Dataset2D(ret) + if not is_empty and self.true_index_dim not in [ + *as_2d.columns, + as_2d.index_dim, + ]: + as_2d[self.true_index_dim] = self.true_index + as_2d.is_backed = self.is_backed + return as_2d + return ret + + def to_memory(self, *, copy: bool = False) -> pd.DataFrame: + """ + Converts to :class:`pandas.DataFrame`. + The index of the dataframe comes from :attr:`~anndata.experimental.backed.Dataset2D.true_index_dim` + if it differs from :attr:`~anndata.experimental.backed.Dataset2D.index_dim`. + + Parameters + ---------- + copy + Unused argument + + Returns + ------- + :class:`pandas.DataFrame` with index set accordingly. + """ + from anndata._core.merge import ( + DS_CONCAT_DUMMY_INDEX_NAME, + DS_MERGE_DUMMY_INDEX_NAME, + ) + + index_key = self.ds.attrs.get("indexing_key", None) + all_columns = {*self.columns, *([] if index_key is None else [index_key])} + # https://github.com/pydata/xarray/issues/10419 + non_nullable_string_cols = { + col + for col in all_columns + if not self[col].attrs.get("is_nullable_string", False) + } + df = self.ds.to_dataframe() + for col in all_columns - non_nullable_string_cols: + df[col] = ( + pandas_as_str(df[col]) if col == index_key else df[col].astype("string") + ) + if df.index.name != index_key and index_key is not None: + df = df.set_index(index_key) + if df.index.name in { + "_index", + DS_CONCAT_DUMMY_INDEX_NAME, + DS_MERGE_DUMMY_INDEX_NAME, + }: + df.index.name = None # matches old AnnData object + return df + + @property + def columns(self) -> pd.Index: + """ + :class:`~anndata.AnnData` internally looks for :attr:`~pandas.DataFrame.columns` so this ensures usability + + Returns + ------- + :class:`pandas.Index` that represents the "columns." + """ + columns = set(self.ds.keys()) + index_key = self.ds.attrs.get("indexing_key", None) + if index_key is not None: + columns.discard(index_key) + return pd.Index(columns) + + @columns.setter + def columns(self, val) -> None: + if len(self.columns.symmetric_difference(val)) > 0: + msg = "Trying to rename the keys of the mapping with new names - please use a different API to rename the keys of the underlying dataset mapping." + raise ValueError(msg) + warnings.warn( + "Renaming or reordering columns on `Dataset2D` has no effect because the underlying data structure has no apparent ordering on its keys", + UserWarning, + stacklevel=2, + ) + + def __setitem__( + self, key: Hashable | Iterable[Hashable] | Mapping, value: Any + ) -> None: + """ + Setting can only be performed when the incoming value is “standalone” like :class:`nump.ndarray` to mimic pandas. + One can also use the tuple setting style like `ds["foo"] = (ds.index_dim, value)` to set the value, although the index name must match. + Similarly, one can use the :class:`xarray.DataArray` but it must have the same (one and only one) dim name/coord name as `self.index_dim`. + + For supported setter values see :meth:`xarray.Dataset.__setitem__`. + """ + if key == self.index_dim: + msg = f"Cannot set the index dimension {self.index_dim} as if it were a variable. Use `ds.index = ...` instead." + raise KeyError(msg) + if isinstance(value, tuple): + if isinstance(value[0], tuple): + if value[0][0] != self.index_dim: + msg = f"Dimension tuple should have only {self.index_dim} as its dimension, found {value[0][0]}" + raise ValueError(msg) + if len(value[0]) > 1: + msg = "Dimension tuple is too long." + raise ValueError(msg) + elif value[0] != self.index_dim: + msg = f"Setting value tuple should have first entry {self.index_dim}, found {value[0]}" + raise ValueError(msg) + elif isinstance(value, XDataArray | XDataset | XVariable): + value_typ = type(value).__name__ + # https://docs.xarray.dev/en/stable/generated/xarray.Dataset.dims.html#xarray.Dataset.dims + # Unfortunately `dims` not the same across data structures. + with warnings.catch_warnings(action="ignore"): + dims = ( + list(value.dims.keys()) + if isinstance(value, XDataset) + else value.dims + ) + if ( + isinstance(value, XDataArray) + and value.name is not None + and value.name != key + ): + msg = f"{value_typ} should have name {key}, found {value.name}" + raise ValueError(msg) + if len(dims) != 1: + msg = f"{value_typ} should have only one dimension, found {len(dims)}" + raise ValueError(msg) + if dims[0] != self.index_dim: + msg = f"{value_typ} should have dimension {self.index_dim}, found {dims[0]}" + raise ValueError(msg) + if not isinstance(value, XVariable) and ( + self.index_dim not in value.coords + or value.coords[self.index_dim].name != self.index_dim + ): + msg = f"{value_typ} should have coordinate {self.index_dim} with same name, found {value.coords} with name {value.coords[next(iter(value.coords.keys()))].name}" + raise ValueError(msg) + else: + # maintain setting behavior of a 2D dataframe i.e., one dim + value = (self.index_dim, value) + self.ds.__setitem__(key, value) + + def copy( + self, + data: Mapping | None = None, + *, + deep: bool = False, + ) -> Dataset2D: + """ + Return a copy of the Dataset2D object. + See :meth:`xarray.Dataset.copy` for more information. + """ + as_2d = Dataset2D(self.ds.copy(deep=deep, data=data)) + as_2d.true_index_dim = self.true_index_dim + as_2d.is_backed = self.is_backed + return as_2d + + def __iter__(self) -> Iterator[Hashable]: + return iter(self.ds) + + def __len__(self) -> int: + return len(self.ds) + + @property + def dtypes(self) -> Mapping[Hashable, np.dtype]: + """ + Return a Mapping with the dtypes of the variables in the Dataset2D. + """ + return self.ds.dtypes + + def equals(self, b: object) -> bool: + """Thin wrapper around :meth:`xarray.Dataset.equals`""" + if isinstance(b, Dataset2D): + b = b.ds + return self.ds.equals(b) + + def reindex( + self, + index: pd.Index | None = None, + axis: Literal[0] = 0, + fill_value: Any | None = np.nan, + ) -> Dataset2D: + """Reindex the current object against a new index. + + Parameters + ---------- + index + The new index for reindexing, by default None + axis + Provided for API consistency, should not be called over axis!=0, by default 0 + fill_value + The value with which to fill in via :meth:`pandas.Series.reindex`, by default np.nan + + Returns + ------- + Reindexed dataset. + """ + index_dim = self.index_dim + if axis != 0: # pragma: no cover + msg = f"Only axis 0 is supported, got axis: {axis}" + raise ValueError(msg) + # Dataset.reindex() can't handle ExtensionArrays + extension_arrays = { + col: data + for col, data in self._items() + if pd.api.types.is_extension_array_dtype(data.dtype) + } + el = self.ds.drop_vars(extension_arrays.keys()) + el = el.reindex({index_dim: index}, method=None, fill_value=fill_value) + for col, data in extension_arrays.items(): + el[col] = XDataArray.from_series( + pd.Series(data.data, index=self.index).reindex( + index.rename(self.index.name) if index is not None else index, + fill_value=fill_value, + ) + ) + return Dataset2D(el) + + # Used "publicly" in src/anndata/_core/merge.py but not intended for public use. + def _items(self): + for col in self: + yield col, self[col] + + +@dataclass(frozen=True) +class IlocGetter: + _ds: XDataset + _coord: str + + def __getitem__(self, idx) -> Dataset2D: + # xarray seems to have some code looking for a second entry in tuples, + # so we unpack the tuple + if isinstance(idx, tuple) and len(idx) == 1: + idx = idx[0] + return Dataset2D(self._ds.isel(**{self._coord: idx})) diff --git a/.venv/lib/python3.11/site-packages/anndata/_io/__init__.py b/.venv/lib/python3.11/site-packages/anndata/_io/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..94b31ae9817a28357b17f7fe8b8ebe1993e26d84 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/anndata/_io/__init__.py @@ -0,0 +1,17 @@ +from __future__ import annotations + +import warnings + +__all__: list[str] = [] + + +def __getattr__(key: str): + from .. import io + + attr = getattr(io, key) + msg = ( + f"Importing {key} from `anndata._io` is deprecated. " + "Please use anndata.io instead." + ) + warnings.warn(msg, FutureWarning, stacklevel=2) + return attr diff --git a/.venv/lib/python3.11/site-packages/anndata/_io/__pycache__/__init__.cpython-311.pyc b/.venv/lib/python3.11/site-packages/anndata/_io/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..41d100aaf5c06e4945c6a62d74dd20ba69277ea1 Binary files /dev/null and b/.venv/lib/python3.11/site-packages/anndata/_io/__pycache__/__init__.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/anndata/_io/__pycache__/h5ad.cpython-311.pyc b/.venv/lib/python3.11/site-packages/anndata/_io/__pycache__/h5ad.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b7e05af8155af737532f343e3920dc6be87fbf8d Binary files /dev/null and b/.venv/lib/python3.11/site-packages/anndata/_io/__pycache__/h5ad.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/anndata/_io/__pycache__/read.cpython-311.pyc b/.venv/lib/python3.11/site-packages/anndata/_io/__pycache__/read.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bfb9c134769a57cf1302fc82b12cb22a93f79be8 Binary files /dev/null and b/.venv/lib/python3.11/site-packages/anndata/_io/__pycache__/read.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/anndata/_io/__pycache__/utils.cpython-311.pyc b/.venv/lib/python3.11/site-packages/anndata/_io/__pycache__/utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7680c8406eac4fa82257acf820920d363c0a7d68 Binary files /dev/null and b/.venv/lib/python3.11/site-packages/anndata/_io/__pycache__/utils.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/anndata/_io/__pycache__/write.cpython-311.pyc b/.venv/lib/python3.11/site-packages/anndata/_io/__pycache__/write.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1f0d4f2279862d9a9cc6085a260fbe87349da807 Binary files /dev/null and b/.venv/lib/python3.11/site-packages/anndata/_io/__pycache__/write.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/anndata/_io/__pycache__/zarr.cpython-311.pyc b/.venv/lib/python3.11/site-packages/anndata/_io/__pycache__/zarr.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..14963978659d520f21530b4a648869829d9b165c Binary files /dev/null and b/.venv/lib/python3.11/site-packages/anndata/_io/__pycache__/zarr.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/anndata/_io/h5ad.py b/.venv/lib/python3.11/site-packages/anndata/_io/h5ad.py new file mode 100644 index 0000000000000000000000000000000000000000..309fe754499fb2f70c654325f63dd513a98e58e9 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/anndata/_io/h5ad.py @@ -0,0 +1,395 @@ +from __future__ import annotations + +import re +from functools import partial +from pathlib import Path +from types import MappingProxyType +from typing import TYPE_CHECKING, TypeVar, cast +from warnings import warn + +import h5py +import numpy as np +import pandas as pd +from scipy import sparse + +from anndata._warnings import OldFormatWarning + +from .._core.anndata import AnnData +from .._core.file_backing import filename +from .._core.sparse_dataset import BaseCompressedSparseDataset +from ..compat import ( + CSMatrix, + _clean_uns, + _decode_structured_array, + _from_fixed_length_strings, +) +from ..experimental import read_dispatched +from .specs import read_elem, write_elem +from .specs.registry import IOSpec, write_spec +from .utils import ( + _read_legacy_raw, + idx_chunks_along_axis, + no_write_dataset_2d, + report_read_key_on_error, + report_write_key_on_error, +) + +if TYPE_CHECKING: + from collections.abc import Callable, Collection, Container, Mapping, Sequence + from os import PathLike + from typing import Any, Literal + + from .._core.file_backing import AnnDataFileManager + from .._core.raw import Raw + from .._types import StorageType + +T = TypeVar("T") + + +@no_write_dataset_2d +def write_h5ad( + filepath: PathLike[str] | str, + adata: AnnData, + *, + as_dense: Sequence[str] = (), + convert_strings_to_categoricals: bool = True, + dataset_kwargs: Mapping[str, Any] = MappingProxyType({}), + **kwargs, +) -> None: + """See :meth:`~anndata.AnnData.write_h5ad`.""" + if isinstance(as_dense, str): + as_dense = [as_dense] + if "raw.X" in as_dense: + as_dense = list(as_dense) + as_dense[as_dense.index("raw.X")] = "raw/X" + if any(val not in {"X", "raw/X"} for val in as_dense): + msg = "Currently, only `X` and `raw/X` are supported values in `as_dense`" + raise NotImplementedError(msg) + if "raw/X" in as_dense and adata.raw is None: + msg = "Cannot specify writing `raw/X` to dense if it doesn’t exist." + raise ValueError(msg) + + if convert_strings_to_categoricals: + adata.strings_to_categoricals() + if adata.raw is not None: + adata.strings_to_categoricals(adata.raw.var) + dataset_kwargs = {**dataset_kwargs, **kwargs} + filepath = Path(filepath) + mode = "a" if adata.isbacked else "w" + if adata.isbacked: # close so that we can reopen below + adata.file.close() + + with h5py.File(filepath, mode) as f: + # TODO: Use spec writing system for this + # Currently can't use write_dispatched here because this function is also called to do an + # inplace update of a backed object, which would delete "/" + f = cast("h5py.Group", f["/"]) + f.attrs.setdefault("encoding-type", "anndata") + f.attrs.setdefault("encoding-version", "0.1.0") + + _write_x( + f, + adata, # accessing adata.X reopens adata.file if it’s backed + is_backed=adata.isbacked and adata.filename == filepath, + as_dense=as_dense, + dataset_kwargs=dataset_kwargs, + ) + _write_raw(f, adata.raw, as_dense=as_dense, dataset_kwargs=dataset_kwargs) + write_elem(f, "obs", adata.obs, dataset_kwargs=dataset_kwargs) + write_elem(f, "var", adata.var, dataset_kwargs=dataset_kwargs) + write_elem(f, "obsm", dict(adata.obsm), dataset_kwargs=dataset_kwargs) + write_elem(f, "varm", dict(adata.varm), dataset_kwargs=dataset_kwargs) + write_elem(f, "obsp", dict(adata.obsp), dataset_kwargs=dataset_kwargs) + write_elem(f, "varp", dict(adata.varp), dataset_kwargs=dataset_kwargs) + write_elem(f, "layers", dict(adata.layers), dataset_kwargs=dataset_kwargs) + write_elem(f, "uns", dict(adata.uns), dataset_kwargs=dataset_kwargs) + + +def _write_x( + f: h5py.Group, + adata: AnnData, + *, + is_backed: bool, + as_dense: Container[str], + dataset_kwargs: Mapping[str, Any], +) -> None: + if "X" in as_dense and isinstance(adata.X, CSMatrix | BaseCompressedSparseDataset): + write_sparse_as_dense(f, "X", adata.X, dataset_kwargs=dataset_kwargs) + elif is_backed: + pass # If adata.isbacked, X should already be up to date + elif adata.X is None: + f.pop("X", None) + else: + write_elem(f, "X", adata.X, dataset_kwargs=dataset_kwargs) + + +def _write_raw( + f: h5py.Group, + raw: Raw, + *, + as_dense: Container[str], + dataset_kwargs: Mapping[str, Any], +) -> None: + if "raw/X" in as_dense and isinstance( + raw.X, CSMatrix | BaseCompressedSparseDataset + ): + write_sparse_as_dense(f, "raw/X", raw.X, dataset_kwargs=dataset_kwargs) + write_elem(f, "raw/var", raw.var, dataset_kwargs=dataset_kwargs) + write_elem(f, "raw/varm", dict(raw.varm), dataset_kwargs=dataset_kwargs) + elif raw is not None: + write_elem(f, "raw", raw, dataset_kwargs=dataset_kwargs) + + +@report_write_key_on_error +@write_spec(IOSpec("array", "0.2.0")) +def write_sparse_as_dense( + f: h5py.Group, + key: str, + value: CSMatrix | BaseCompressedSparseDataset, + *, + dataset_kwargs: Mapping[str, Any] = MappingProxyType({}), +): + real_key = None # Flag for if temporary key was used + if key in f: + if isinstance(value, BaseCompressedSparseDataset) and ( + filename(value.group) == filename(f) + ): # Write to temporary key before overwriting + real_key = key + # Transform key to temporary, e.g. raw/X -> raw/_X, or X -> _X + key = re.sub(r"(.*)(\w(?!.*/))", r"\1_\2", key.rstrip("/")) + else: + del f[key] # Wipe before write + dset = f.create_dataset(key, shape=value.shape, dtype=value.dtype, **dataset_kwargs) + compressed_axis = int(isinstance(value, sparse.csc_matrix)) + for idx in idx_chunks_along_axis(value.shape, compressed_axis, 1000): + dset[idx] = value[idx].toarray() + if real_key is not None: + del f[real_key] + f[real_key] = f[key] + del f[key] + + +def read_h5ad_backed( + filename: str | PathLike[str], mode: Literal["r", "r+"] +) -> AnnData: + f = h5py.File(filename, mode) + d = dict(filename=f) + + attributes = ["obsm", "varm", "obsp", "varp", "uns", "layers"] + df_attributes = ["obs", "var"] + + if "encoding-type" in f.attrs: + attributes.extend(df_attributes) + else: + for k in df_attributes: + if k in f: # Backwards compat + d[k] = read_dataframe(f[k]) + + d.update({k: read_elem(f[k]) for k in attributes if k in f}) + + d["raw"] = _read_raw(f, attrs={"var", "varm"}) + + adata = AnnData(**d) + assert adata.file._file is f + + # Backwards compat to <0.7 + if isinstance(f["obs"], h5py.Dataset): + _clean_uns(adata) + + return adata + + +def read_h5ad( + filename: PathLike[str] | str, + backed: Literal["r", "r+"] | bool | None = None, # noqa: FBT001 + *, + as_sparse: Sequence[str] = (), + as_sparse_fmt: type[CSMatrix] = sparse.csr_matrix, + chunk_size: int = 6000, # TODO, probably make this 2d chunks +) -> AnnData: + """\ + Read `.h5ad`-formatted hdf5 file. + + Parameters + ---------- + filename + File name of data file. + backed + If `'r'`, load :class:`~anndata.AnnData` in `backed` mode + instead of fully loading it into memory (`memory` mode). + If you want to modify backed attributes of the AnnData object, + you need to choose `'r+'`. + + Currently, `backed` only support updates to `X`. That means any + changes to other slots like `obs` will not be written to disk in + `backed` mode. If you would like save changes made to these slots + of a `backed` :class:`~anndata.AnnData`, write them to a new file + (see :meth:`~anndata.AnnData.write`). For an example, see + :ref:`read-partial`. + as_sparse + If an array was saved as dense, passing its name here will read it as + a sparse_matrix, by chunk of size `chunk_size`. + as_sparse_fmt + Sparse format class to read elements from `as_sparse` in as. + chunk_size + Used only when loading sparse dataset that is stored as dense. + Loading iterates through chunks of the dataset of this row size + until it reads the whole dataset. + Higher size means higher memory consumption and higher (to a point) + loading speed. + """ + if backed not in {None, False}: + mode = backed + if mode is True: + mode = "r+" + assert mode in {"r", "r+"} + return read_h5ad_backed(filename, mode) + + if as_sparse_fmt not in (sparse.csr_matrix, sparse.csc_matrix): + msg = "Dense formats can only be read to CSR or CSC matrices at this time." + raise NotImplementedError(msg) + as_sparse = [as_sparse] if isinstance(as_sparse, str) else list(as_sparse) + for i in range(len(as_sparse)): + if as_sparse[i] in {("raw", "X"), "raw.X"}: + as_sparse[i] = "raw/X" + elif as_sparse[i] not in {"raw/X", "X"}: + msg = "Currently only `X` and `raw/X` can be read as sparse." + raise NotImplementedError(msg) + + rdasp = partial( + read_dense_as_sparse, sparse_format=as_sparse_fmt, axis_chunk=chunk_size + ) + + with h5py.File(filename, "r") as f: + + def callback(read_func, elem_name: str, elem: StorageType, iospec: IOSpec): + if iospec.encoding_type == "anndata" or elem_name.endswith("/"): + return AnnData(**{ + # This is covering up backwards compat in the anndata initializer + # In most cases we should be able to call `func(elen[k])` instead + k: read_dispatched(elem[k], callback) + for k in elem + if not k.startswith("raw.") + }) + elif elem_name.startswith("/raw."): + return None + elif elem_name == "/X" and "X" in as_sparse: + return rdasp(elem) + elif elem_name == "/raw": + return _read_raw(f, as_sparse, rdasp) + elif elem_name in {"/obs", "/var"}: + # Backwards compat + return read_dataframe(elem) + return read_func(elem) + + adata = read_dispatched(f, callback=callback) + + # Backwards compat (should figure out which version) + if "raw.X" in f: + raw = AnnData(**_read_raw(f, as_sparse, rdasp)) + raw.obs_names = adata.obs_names + adata.raw = raw + + # Backwards compat to <0.7 + if isinstance(f["obs"], h5py.Dataset): + _clean_uns(adata) + + return adata + + +def _read_raw( + f: h5py.File | AnnDataFileManager, + as_sparse: Collection[str] = (), + rdasp: Callable[[h5py.Dataset], CSMatrix] | None = None, + *, + attrs: Collection[str] = ("X", "var", "varm"), +) -> dict: + if as_sparse: + assert rdasp is not None, "must supply rdasp if as_sparse is supplied" + raw = {} + if "X" in attrs and "raw/X" in f: + read_x = rdasp if "raw/X" in as_sparse else read_elem + raw["X"] = read_x(f["raw/X"]) + for v in ("var", "varm"): + if v in attrs and f"raw/{v}" in f: + raw[v] = read_elem(f[f"raw/{v}"]) + return _read_legacy_raw(f, raw, read_dataframe, read_elem, attrs=attrs) + + +@report_read_key_on_error +def read_dataframe_legacy(dataset: h5py.Dataset) -> pd.DataFrame: + """Read pre-anndata 0.7 dataframes.""" + msg = ( + f"{dataset.name!r} was written with a very old version of AnnData. " + "Consider rewriting it." + ) + warn(msg, OldFormatWarning, stacklevel=2) + df = pd.DataFrame( + _decode_structured_array( + _from_fixed_length_strings(dataset[()]), dtype=dataset.dtype + ) + ) + return df.set_index(df.columns[0]) + + +def read_dataframe(group: h5py.Group | h5py.Dataset) -> pd.DataFrame: + """Backwards compat function""" + if not isinstance(group, h5py.Group): + return read_dataframe_legacy(group) + else: + return read_elem(group) + + +@report_read_key_on_error +def read_dataset(dataset: h5py.Dataset): + string_dtype = h5py.check_string_dtype(dataset.dtype) + if (string_dtype is not None) and (string_dtype.encoding == "utf-8"): + dataset = dataset.asstr() + value = dataset[()] + if not hasattr(value, "dtype"): + return value + elif isinstance(value.dtype, str): + pass + elif issubclass(value.dtype.type, np.bytes_): + value = value.astype(str) + # Backwards compat, old datasets have strings as one element 1d arrays + if len(value) == 1: + return value[0] + elif len(value.dtype.descr) > 1: # Compound dtype + # For backwards compat, now strings are written as variable length + value = _decode_structured_array( + _from_fixed_length_strings(value), dtype=value.dtype + ) + if value.shape == (): + value = value[()] + return value + + +@report_read_key_on_error +def read_dense_as_sparse( + dataset: h5py.Dataset, sparse_format: CSMatrix, axis_chunk: int +): + if sparse_format == sparse.csr_matrix: + return read_dense_as_csr(dataset, axis_chunk) + elif sparse_format == sparse.csc_matrix: + return read_dense_as_csc(dataset, axis_chunk) + else: + msg = f"Cannot read dense array as type: {sparse_format}" + raise ValueError(msg) + + +def read_dense_as_csr(dataset: h5py.Dataset, axis_chunk: int = 6000): + sub_matrices = [] + for idx in idx_chunks_along_axis(dataset.shape, 0, axis_chunk): + dense_chunk = dataset[idx] + sub_matrix = sparse.csr_matrix(dense_chunk) + sub_matrices.append(sub_matrix) + return sparse.vstack(sub_matrices, format="csr") + + +def read_dense_as_csc(dataset: h5py.Dataset, axis_chunk: int = 6000): + sub_matrices = [] + for idx in idx_chunks_along_axis(dataset.shape, 1, axis_chunk): + sub_matrix = sparse.csc_matrix(dataset[idx]) + sub_matrices.append(sub_matrix) + return sparse.hstack(sub_matrices, format="csc") diff --git a/.venv/lib/python3.11/site-packages/anndata/_io/read.py b/.venv/lib/python3.11/site-packages/anndata/_io/read.py new file mode 100644 index 0000000000000000000000000000000000000000..56357ba1822015bba668e6e8c00e2191e7a811d9 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/anndata/_io/read.py @@ -0,0 +1,511 @@ +from __future__ import annotations + +import bz2 +import gzip +from collections import OrderedDict +from importlib.metadata import version +from os import PathLike, fspath +from pathlib import Path +from types import MappingProxyType +from typing import TYPE_CHECKING +from warnings import warn + +import h5py +import numpy as np +import pandas as pd +from packaging.version import Version +from scipy import sparse + +from .. import AnnData +from ..compat import old_positionals, pandas_as_str +from .utils import is_float + +if TYPE_CHECKING: + from collections.abc import Generator, Iterable, Iterator, Mapping + + +@old_positionals("first_column_names", "dtype") +def read_csv( + filename: PathLike[str] | str | Iterator[str], + delimiter: str | None = ",", + *, + first_column_names: bool | None = None, + dtype: str = "float32", +) -> AnnData: + """\ + Read `.csv` file. + + Same as :func:`~anndata.io.read_text` but with default delimiter `','`. + + Parameters + ---------- + filename + Data file. + delimiter + Delimiter that separates data within text file. + If `None`, will split at arbitrary number of white spaces, + which is different from enforcing splitting at single white space `' '`. + first_column_names + Assume the first column stores row names. + dtype + Numpy data type. + """ + return read_text( + filename, delimiter, first_column_names=first_column_names, dtype=dtype + ) + + +def read_excel( + filename: PathLike[str] | str, sheet: str | int, dtype: str = "float32" +) -> AnnData: + """\ + Read `.xlsx` (Excel) file. + + Assumes that the first columns stores the row names and the first row the + column names. + + Parameters + ---------- + filename + File name to read from. + sheet + Name of sheet in Excel file. + """ + # rely on pandas for reading an excel file + from pandas import read_excel + + df = read_excel(fspath(filename), sheet) + X = df.values[:, 1:] + row = dict(row_names=pandas_as_str(df.iloc[:, 0]).array) + col = dict(col_names=pandas_as_str(df.columns[1:]).array) + return AnnData(X, row, col) + + +def read_umi_tools(filename: PathLike[str] | str, dtype=None) -> AnnData: + """\ + Read a gzipped condensed count matrix from umi_tools. + + Parameters + ---------- + filename + File name to read from. + """ + # import pandas for conversion of a dict of dicts into a matrix + # import gzip to read a gzipped file :-) + table = pd.read_table(filename, dtype={"gene": "category", "cell": "category"}) + + X = sparse.csr_matrix( + (table["count"], (table["cell"].cat.codes, table["gene"].cat.codes)), + dtype=dtype, + ) + obs = pd.DataFrame(index=pd.Index(table["cell"].cat.categories, name="cell")) + var = pd.DataFrame(index=pd.Index(table["gene"].cat.categories, name="gene")) + + return AnnData(X=X, obs=obs, var=var) + + +def read_hdf(filename: PathLike[str] | str, key: str) -> AnnData: + """\ + Read `.h5` (hdf5) file. + + Note: Also looks for fields `row_names` and `col_names`. + + Parameters + ---------- + filename + Filename of data file. + key + Name of dataset in the file. + """ + with h5py.File(filename, "r") as f: + # the following is necessary in Python 3, because only + # a view and not a list is returned + keys = list(f) + if key == "": + msg = ( + f"The file {filename} stores the following sheets:\n{keys}\n" + f"Call read/read_hdf5 with one of them." + ) + raise ValueError(msg) + # read array + X = f[key][()] + # try to find row and column names + rows_cols = [{}, {}] + for iname, name in enumerate(["row_names", "col_names"]): + if name in keys: + rows_cols[iname][name] = f[name][()] + adata = AnnData(X, rows_cols[0], rows_cols[1]) + return adata + + +def _fmt_loom_axis_attrs( + input: Mapping, idx_name: str, dimm_mapping: Mapping[str, Iterable[str]] +) -> tuple[pd.DataFrame, Mapping[str, np.ndarray]]: + axis_df = pd.DataFrame() + axis_mapping = {} + for key, names in dimm_mapping.items(): + axis_mapping[key] = np.array([input.pop(name) for name in names]).T + + for k, v in input.items(): + if v.ndim > 1 and v.shape[1] > 1: + axis_mapping[k] = v + else: + axis_df[k] = v + + if idx_name in axis_df: + axis_df.set_index(idx_name, drop=True, inplace=True) + + return axis_df, axis_mapping + + +@old_positionals( + "sparse", + "cleanup", + "X_name", + "obs_names", + "obsm_names", + "var_names", + "varm_names", + "dtype", + "obsm_mapping", + "varm_mapping", +) +def read_loom( # noqa: PLR0912, PLR0913 + filename: PathLike[str] | str, + *, + sparse: bool = True, + cleanup: bool = False, + X_name: str = "spliced", + obs_names: str = "CellID", + obsm_names: Mapping[str, Iterable[str]] | None = None, + var_names: str = "Gene", + varm_names: Mapping[str, Iterable[str]] | None = None, + dtype: str = "float32", + obsm_mapping: Mapping[str, Iterable[str]] = MappingProxyType({}), + varm_mapping: Mapping[str, Iterable[str]] = MappingProxyType({}), + **kwargs, +) -> AnnData: + """\ + Read `.loom`-formatted hdf5 file. + + This reads the whole file into memory. + + Beware that you have to explicitly state when you want to read the file as + sparse data. + + Parameters + ---------- + filename + The filename. + sparse + Whether to read the data matrix as sparse. + cleanup + Whether to collapse all obs/var fields that only store + one unique value into `.uns['loom-.']`. + X_name + Loompy key with which the data matrix :attr:`~anndata.AnnData.X` is initialized. + obs_names + Loompy key where the observation/cell names are stored. + obsm_mapping + Loompy keys which will be constructed into observation matrices + var_names + Loompy key where the variable/gene names are stored. + varm_mapping + Loompy keys which will be constructed into variable matrices + **kwargs: + Arguments to loompy.connect + + Example + ------- + + .. code:: python + + pbmc = anndata.io.read_loom( + "pbmc.loom", + sparse=True, + X_name="lognorm", + obs_names="cell_names", + var_names="gene_names", + obsm_mapping={ + "X_umap": ["umap_1", "umap_2"] + } + ) + """ + # Deprecations + if obsm_names is not None: + msg = ( + "Argument obsm_names has been deprecated in favour of `obsm_mapping`. " + "In 0.9 this will be an error." + ) + warn(msg, FutureWarning, stacklevel=2) + if obsm_mapping != {}: + msg = ( + "Received values for both `obsm_names` and `obsm_mapping`. This is " + "ambiguous, only pass `obsm_mapping`." + ) + raise ValueError(msg) + obsm_mapping = obsm_names + if varm_names is not None: + msg = ( + "Argument varm_names has been deprecated in favour of `varm_mapping`. " + "In 0.9 this will be an error." + ) + warn(msg, FutureWarning, stacklevel=2) + if varm_mapping != {}: + msg = ( + "Received values for both `varm_names` and `varm_mapping`. This is " + "ambiguous, only pass `varm_mapping`." + ) + raise ValueError(msg) + varm_mapping = varm_names + + filename = fspath(filename) # allow passing pathlib.Path objects + from loompy import connect + + if TYPE_CHECKING: + from loompy import LoomConnection + + lc: LoomConnection + with connect(filename, "r", **kwargs) as lc: + assert lc.layers is not None + + if X_name not in lc.layers: + X_name = "" + X = lc.layers[X_name].sparse().T.tocsr() if sparse else lc.layers[X_name][()].T + X = X.astype(dtype, copy=False) + + layers = OrderedDict() + if X_name != "": + layers["matrix"] = ( + lc.layers[""].sparse().T.tocsr() if sparse else lc.layers[""][()].T + ) + for key, layer in lc.layers.items(): + if key != "": + layers[key] = layer.sparse().T.tocsr() if sparse else layer[()].T + + # TODO: Figure out the singleton obs elements + obs, obsm = _fmt_loom_axis_attrs(dict(lc.col_attrs), obs_names, obsm_mapping) + var, varm = _fmt_loom_axis_attrs(dict(lc.row_attrs), var_names, varm_mapping) + + uns = {} + if cleanup: + uns_obs = {} + for key in obs.columns: + if len(obs[key].unique()) == 1: + uns_obs[key] = obs[key].iloc[0] + del obs[key] + if uns_obs: + uns["loom-obs"] = uns_obs + uns_var = {} + for key in var.columns: + if len(var[key].unique()) == 1: + uns_var[key] = var[key].iloc[0] + del var[key] + if uns_var: + uns["loom-var"] = uns_var + + adata = AnnData( + X, + obs=obs, + var=var, + layers=layers, + obsm=obsm if obsm else None, + varm=varm if varm else None, + uns=uns, + ) + return adata + + +def read_mtx(filename: PathLike[str] | str, dtype: str = "float32") -> AnnData: + """\ + Read `.mtx` file. + + Parameters + ---------- + filename + The filename. + dtype + Numpy data type. + """ + from scipy.io import mmread + + # could be rewritten accounting for dtype to be more performant + # https://github.com/scverse/anndata/issues/2477 for spmatrix + X = mmread( + fspath(filename), + **( + {"spmatrix": True} + if Version(version("scipy")) >= Version("1.18.0rc1") + else {} + ), + ).astype(dtype) + from scipy.sparse import csr_matrix + + X = csr_matrix(X) + return AnnData(X) + + +@old_positionals("first_column_names", "dtype") +def read_text( + filename: PathLike[str] | str | Iterator[str], + delimiter: str | None = None, + *, + first_column_names: bool | None = None, + dtype: str = "float32", +) -> AnnData: + """\ + Read `.txt`, `.tab`, `.data` (text) file. + + Same as :func:`~anndata.io.read_csv` but with default delimiter `None`. + + Parameters + ---------- + filename + Data file, filename or stream. + delimiter + Delimiter that separates data within text file. If `None`, will split at + arbitrary number of white spaces, which is different from enforcing + splitting at single white space `' '`. + first_column_names + Assume the first column stores row names. + dtype + Numpy data type. + """ + if not isinstance(filename, PathLike | str | bytes): + return _read_text( + filename, delimiter, first_column_names=first_column_names, dtype=dtype + ) + + filename = Path(filename) + if filename.suffix == ".gz": + with gzip.open(str(filename), mode="rt") as f: + return _read_text( + f, delimiter, first_column_names=first_column_names, dtype=dtype + ) + elif filename.suffix == ".bz2": + with bz2.open(str(filename), mode="rt") as f: + return _read_text( + f, delimiter, first_column_names=first_column_names, dtype=dtype + ) + else: + with filename.open() as f: + return _read_text( + f, delimiter, first_column_names=first_column_names, dtype=dtype + ) + + +def _iter_lines(file_like: Iterable[str]) -> Generator[str, None, None]: + """Helper for iterating only nonempty lines without line breaks""" + for line in file_like: + line = line.rstrip("\r\n") + if line: + yield line + + +def _read_text( # noqa: PLR0912, PLR0915 + f: Iterator[str], + delimiter: str | None, + *, + first_column_names: bool | None, + dtype: str, +) -> AnnData: + comments = [] + data = [] + lines = _iter_lines(f) + col_names = [] + row_names = [] + # read header and column names + for line in lines: + if line.startswith("#"): + comment = line.lstrip("# ") + if comment: + comments.append(comment) + else: + if delimiter is not None and delimiter not in line: + msg = f"Did not find delimiter {delimiter!r} in first line." + raise ValueError(msg) + line_list = line.split(delimiter) + # the first column might be row names, so check the last + if not is_float(line_list[-1]): + col_names = line_list + # logg.msg(" assuming first line in file stores column names", v=4) + elif not is_float(line_list[0]) or first_column_names: + first_column_names = True + row_names.append(line_list[0]) + data.append(np.array(line_list[1:], dtype=dtype)) + else: + data.append(np.array(line_list, dtype=dtype)) + break + if not col_names: + # try reading col_names from the last comment line + if len(comments) > 0: + # logg.msg(" assuming last comment line stores variable names", v=4) + col_names = np.array(comments[-1].split()) + # just numbers as col_names + else: + # logg.msg(" did not find column names in file", v=4) + col_names = np.arange(len(data[0])).astype(str) + col_names = np.array(col_names, dtype=str) + # read another line to check if first column contains row names or not + if first_column_names is None: + first_column_names = False + for line in lines: + line_list = line.split(delimiter) + if first_column_names or not is_float(line_list[0]): + # logg.msg(" assuming first column in file stores row names", v=4) + first_column_names = True + row_names.append(line_list[0]) + data.append(np.array(line_list[1:], dtype=dtype)) + else: + data.append(np.array(line_list, dtype=dtype)) + break + # if row names are just integers + if len(data) > 1 and data[0].size != data[1].size: + # logg.msg( + # " assuming first row stores column names and first column row names", + # v=4, + # ) + first_column_names = True + col_names = np.array(data[0]).astype(int).astype(str) + row_names.append(data[1][0].astype(int).astype(str)) + data = [data[1][1:]] + # parse the file + for line in lines: + line_list = line.split(delimiter) + if first_column_names: + row_names.append(line_list[0]) + data.append(np.array(line_list[1:], dtype=dtype)) + else: + data.append(np.array(line_list, dtype=dtype)) + # logg.msg(" read data into list of lists", t=True, v=4) + # transform to array, this takes a long time and a lot of memory + # but it’s actually the same thing as np.genfromtxt does + # - we don’t use the latter as it would involve another slicing step + # in the end, to separate row_names from float data, slicing takes + # a lot of memory and CPU time + if data[0].size != data[-1].size: + msg = ( + f"Length of first line ({data[0].size}) is different " + f"from length of last line ({data[-1].size})." + ) + raise ValueError(msg) + data = np.array(data, dtype=dtype) + # logg.msg(" constructed array from list of list", t=True, v=4) + # transform row_names + if not row_names: + row_names = np.arange(len(data)).astype(str) + # logg.msg(" did not find row names in file", v=4) + else: + row_names = np.array(row_names) + for iname, name in enumerate(row_names): + row_names[iname] = name.strip('"') + # adapt col_names if necessary + if col_names.size > data.shape[1]: + col_names = col_names[1:] + for iname, name in enumerate(col_names): + col_names[iname] = name.strip('"') + return AnnData( + data, + obs=dict(obs_names=row_names), + var=dict(var_names=col_names), + ) diff --git a/.venv/lib/python3.11/site-packages/anndata/_io/specs/__init__.py b/.venv/lib/python3.11/site-packages/anndata/_io/specs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d97578c1d2add57d195d57c9183b0c04eb170698 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/anndata/_io/specs/__init__.py @@ -0,0 +1,26 @@ +from __future__ import annotations + +from . import lazy_methods, methods +from .registry import ( + _LAZY_REGISTRY, # noqa: F401 + _REGISTRY, # noqa: F401 + IOSpec, + Reader, + Writer, + get_spec, + read_elem, + read_elem_lazy, + write_elem, +) + +__all__ = [ + "IOSpec", + "Reader", + "Writer", + "get_spec", + "lazy_methods", + "methods", + "read_elem", + "read_elem_lazy", + "write_elem", +] diff --git a/.venv/lib/python3.11/site-packages/anndata/_io/specs/__pycache__/__init__.cpython-311.pyc b/.venv/lib/python3.11/site-packages/anndata/_io/specs/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..42da45cdc8a97727e92baa1cab8d6ec6b123ac1f Binary files /dev/null and b/.venv/lib/python3.11/site-packages/anndata/_io/specs/__pycache__/__init__.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/anndata/_io/specs/__pycache__/lazy_methods.cpython-311.pyc b/.venv/lib/python3.11/site-packages/anndata/_io/specs/__pycache__/lazy_methods.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..27fdf1f2aaf79d60dcaabbec31adbc3aa620652a Binary files /dev/null and b/.venv/lib/python3.11/site-packages/anndata/_io/specs/__pycache__/lazy_methods.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/anndata/_io/specs/__pycache__/methods.cpython-311.pyc b/.venv/lib/python3.11/site-packages/anndata/_io/specs/__pycache__/methods.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f3c5d2639d6c4605295c190524cfbe11104ccea2 Binary files /dev/null and b/.venv/lib/python3.11/site-packages/anndata/_io/specs/__pycache__/methods.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/anndata/_io/specs/__pycache__/registry.cpython-311.pyc b/.venv/lib/python3.11/site-packages/anndata/_io/specs/__pycache__/registry.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a6375a5640ae31772ed8fcfa352eca31182bba81 Binary files /dev/null and b/.venv/lib/python3.11/site-packages/anndata/_io/specs/__pycache__/registry.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/anndata/_io/specs/lazy_methods.py b/.venv/lib/python3.11/site-packages/anndata/_io/specs/lazy_methods.py new file mode 100644 index 0000000000000000000000000000000000000000..3f6af21a2f2c45c2e195750a688ecec4009a3684 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/anndata/_io/specs/lazy_methods.py @@ -0,0 +1,397 @@ +from __future__ import annotations + +from contextlib import contextmanager +from functools import partial, singledispatch +from pathlib import Path +from typing import TYPE_CHECKING, overload + +import h5py +import numpy as np +import pandas as pd +from scipy import sparse + +import anndata as ad +from anndata._core.file_backing import filename, get_elem_name +from anndata._core.xarray import Dataset2D, requires_xarray +from anndata.abc import CSCDataset, CSRDataset +from anndata.compat import ( + NULLABLE_NUMPY_STRING_TYPE, + NUMPY_2, + DaskArray, + H5Array, + H5Group, + XDataset, + XVariable, + ZarrArray, + ZarrGroup, + pandas_as_str, +) + +from .registry import _LAZY_REGISTRY, IOSpec, read_elem + +if TYPE_CHECKING: + from collections.abc import Generator, Mapping, Sequence + from typing import Literal, ParamSpec, TypeVar + + from anndata.experimental.backed._lazy_arrays import CategoricalArray, MaskedArray + + from ...compat import CSArray, CSMatrix, H5File + from .registry import LazyDataStructures, LazyReader + + BlockInfo = Mapping[ + None, + dict[str, Sequence[tuple[int, int]]], + ] + + P = ParamSpec("P") + R = TypeVar("R") + D = TypeVar("D") + + +@overload +@contextmanager +def maybe_open_h5( + path_or_other: Path, elem_name: str +) -> Generator[H5File, None, None]: ... +@overload +@contextmanager +def maybe_open_h5(path_or_other: D, elem_name: str) -> Generator[D, None, None]: ... +@contextmanager +def maybe_open_h5( + path_or_other: H5File | D, elem_name: str +) -> Generator[H5File | D, None, None]: + if not isinstance(path_or_other, Path): + yield path_or_other + return + file = h5py.File(path_or_other, "r") + try: + yield file[elem_name] + finally: + file.close() + + +_DEFAULT_STRIDE = 1000 + + +def compute_chunk_layout_for_axis_size( + chunk_axis_size: int, full_axis_size: int +) -> tuple[int, ...]: + # A zero-length axis must be expressed as a single zero-length chunk: + # dask rejects empty chunk tuples ("Empty tuples are not allowed in + # chunks"), and ``np.divmod(0, 0)`` would otherwise divide by zero. + if full_axis_size == 0: + return (0,) + n_strides, rest = np.divmod(full_axis_size, chunk_axis_size) + chunk = (chunk_axis_size,) * n_strides + if rest > 0: + chunk += (rest,) + return chunk + + +def make_dask_chunk( + path_or_sparse_dataset: Path | D, + elem_name: str, + block_info: BlockInfo | None = None, +) -> CSMatrix | CSArray: + if block_info is None: + msg = "Block info is required" + raise ValueError(msg) + # We need to open the file in each task since `dask` cannot share h5py objects when using `dask.distributed` + # https://github.com/scverse/anndata/issues/1105 + with maybe_open_h5(path_or_sparse_dataset, elem_name) as f: + # See https://github.com/scverse/anndata/pull/2005 for why + # should_cache_indptr is False. + # The prupose of caching the indptr was when the dataset is reused + # which is in general the case but is not here. Hence + # caching it on every access to the dataset here is quite costly. + mtx = ( + ad.io.sparse_dataset(f, should_cache_indptr=False) + if isinstance(f, H5Group) + else f + ) + idx = tuple( + slice(start, stop) for start, stop in block_info[None]["array-location"] + ) + chunk = mtx[idx] + return chunk + + +@singledispatch +def get_chunksize(obj) -> tuple[int, ...]: + if hasattr(obj, "chunks"): + return obj.chunks + msg = "object of type {type(obj)} has no recognized chunks" + raise ValueError(msg) + + +@_LAZY_REGISTRY.register_read(H5Group, IOSpec("csc_matrix", "0.1.0")) +@_LAZY_REGISTRY.register_read(H5Group, IOSpec("csr_matrix", "0.1.0")) +@_LAZY_REGISTRY.register_read(ZarrGroup, IOSpec("csc_matrix", "0.1.0")) +@_LAZY_REGISTRY.register_read(ZarrGroup, IOSpec("csr_matrix", "0.1.0")) +def read_sparse_as_dask( + elem: H5Group | ZarrGroup, + *, + _reader: LazyReader, + chunks: tuple[int, ...] | None = None, # only tuple[int, int] is supported here +) -> DaskArray: + import dask.array as da + + path_or_sparse_dataset = ( + Path(filename(elem)) + if isinstance(elem, H5Group) + else ad.io.sparse_dataset(elem, should_cache_indptr=False) + ) + elem_name = get_elem_name(elem) + shape: tuple[int, int] = tuple(elem.attrs["shape"]) + if isinstance(path_or_sparse_dataset, CSRDataset | CSCDataset): + dtype = path_or_sparse_dataset.dtype + else: + dtype = elem["data"].dtype + is_csc: bool = elem.attrs["encoding-type"] == "csc_matrix" + + stride: int = _DEFAULT_STRIDE + major_dim, minor_dim = (1, 0) if is_csc else (0, 1) + if chunks is not None: + if len(chunks) != 2: + msg = "`chunks` must be a tuple of two integers" + raise ValueError(msg) + if chunks[minor_dim] not in {shape[minor_dim], -1, None}: + msg = ( + "Only the major axis can be chunked. " + f"Try setting chunks to {((-1, _DEFAULT_STRIDE) if is_csc else (_DEFAULT_STRIDE, -1))}" + ) + raise ValueError(msg) + stride = ( + chunks[major_dim] + if chunks[major_dim] not in {None, -1} + else shape[major_dim] + ) + + shape_minor, shape_major = shape if is_csc else shape[::-1] + chunks_major = compute_chunk_layout_for_axis_size(stride, shape_major) + chunks_minor = (shape_minor,) + chunk_layout = ( + (chunks_minor, chunks_major) if is_csc else (chunks_major, chunks_minor) + ) + memory_format = sparse.csc_matrix if is_csc else sparse.csr_matrix + make_chunk = partial(make_dask_chunk, path_or_sparse_dataset, elem_name) + da_mtx = da.map_blocks( + make_chunk, + dtype=dtype, + chunks=chunk_layout, + meta=memory_format((0, 0), dtype=dtype), + ) + return da_mtx + + +def resolve_chunks( + elem: H5Array | ZarrArray, + chunks_arg: tuple[int, ...] | None, + shape: tuple[int, ...], +) -> tuple[int, ...]: + shape = tuple(elem.shape) + if chunks_arg is not None: + # None and -1 on a given axis indicate that one should use the shape + # in `dask`'s semantics. + return tuple( + c if c not in {None, -1} else s + for c, s in zip(chunks_arg, shape, strict=True) + ) + elif elem.chunks is None: # h5 unchunked + return tuple(min(_DEFAULT_STRIDE, s) for s in shape) + return elem.chunks + + +# TODO: `map_blocks` of a string array in h5py is so insanely slow on benchmarking that in the case someone has +# a pure string annotation (not categoricals! or nullables strings!), it's probably better to pay the memory penalty. +# In the long run, it might be good to figure out what exactly is going on here but for now, this will do. +@_LAZY_REGISTRY.register_read(H5Array, IOSpec("string-array", "0.2.0")) +def read_h5_string_array( + elem: H5Array, *, _reader: LazyReader, chunks: tuple[int, ...] | None = None +) -> DaskArray: + import dask.array as da + + chunks = resolve_chunks(elem, chunks, tuple(elem.shape)) + return da.from_array(read_elem(elem), chunks=chunks) + + +@_LAZY_REGISTRY.register_read(H5Array, IOSpec("array", "0.2.0")) +def read_h5_array( + elem: H5Array, *, _reader: LazyReader, chunks: tuple[int, ...] | None = None +) -> DaskArray: + import dask.array as da + + path = Path(elem.file.filename) + elem_name: str = elem.name + shape = tuple(elem.shape) + dtype = elem.dtype + chunks = resolve_chunks(elem, chunks, shape) + + chunk_layout = tuple( + compute_chunk_layout_for_axis_size(chunks[i], shape[i]) + for i in range(len(shape)) + ) + + make_chunk = partial(make_dask_chunk, path, elem_name) + return da.map_blocks( + make_chunk, dtype=dtype, chunks=chunk_layout, meta=np.array([]) + ) + + +@_LAZY_REGISTRY.register_read(ZarrArray, IOSpec("string-array", "0.2.0")) +@_LAZY_REGISTRY.register_read(ZarrArray, IOSpec("array", "0.2.0")) +def read_zarr_array( + elem: ZarrArray, *, _reader: LazyReader, chunks: tuple[int, ...] | None = None +) -> DaskArray: + import dask.array as da + + return da.from_zarr(elem, chunks=chunks) + + +def _gen_xarray_dict_iterator_from_elems( + elem_dict: dict[str, LazyDataStructures], + dim_name: str, + index: np.typing.NDArray, +) -> Generator[tuple[str, XVariable], None, None]: + from anndata.experimental.backed._lazy_arrays import CategoricalArray, MaskedArray + + from ...compat import xarray as xr + + for k, v in elem_dict.items(): + if isinstance(v, DaskArray) and k != dim_name: + variable = xr.Variable([dim_name], data=v) + elif isinstance(v, CategoricalArray | MaskedArray) and k != dim_name: + variable = xr.Variable( + [dim_name], + data=xr.core.indexing.LazilyIndexedArray(v), + attrs={ + "base_path_or_zarr_group": v.base_path_or_zarr_group, + "elem_name": v.elem_name, + "is_nullable_string": isinstance(v, MaskedArray) + and ( + v.dtype == NULLABLE_NUMPY_STRING_TYPE + or isinstance(v.dtype, pd.StringDtype | np.dtypes.StringDType) + ), + }, + ) + elif k == dim_name: + variable = xr.Variable([dim_name], data=index) + else: + msg = f"Could not read {k}: {v} from into xarray Dataset2D" + raise ValueError(msg) + yield k, variable + + +DUMMY_RANGE_INDEX_KEY = "_anndata_dummy_range_index" + + +@_LAZY_REGISTRY.register_read(ZarrGroup, IOSpec("dataframe", "0.2.0")) +@_LAZY_REGISTRY.register_read(H5Group, IOSpec("dataframe", "0.2.0")) +@requires_xarray +def read_dataframe( + elem: H5Group | ZarrGroup, + *, + _reader: LazyReader, + use_range_index: bool = False, + chunks: tuple[int, ...] | None = None, +) -> Dataset2D: + # going through dask for reading into memory the index doesn't make sense, hence the ternary. + elem_dict = { + k: _reader.read_elem(elem[k], chunks=chunks) + if (use_range_index and k == elem.attrs["_index"]) or k != elem.attrs["_index"] + else pd.Index(ad.io.read_elem(elem[k])) + for k in [*elem.attrs["column-order"], elem.attrs["_index"]] + } + if ( + pd.api.types.is_string_dtype(elem_dict[elem.attrs["_index"]]) + and not use_range_index + ): + elem_dict[elem.attrs["_index"]] = pandas_as_str(elem_dict[elem.attrs["_index"]]) + # If we use a range index, the coord axis needs to have the special dim name + # which is used below as well. + if not use_range_index: + dim_name = elem.attrs["_index"] + # no sense in reading this in multiple times since xarray requires an in-memory index + index = elem_dict[dim_name] + else: + dim_name = DUMMY_RANGE_INDEX_KEY + index = pd.RangeIndex(len(elem_dict[elem.attrs["_index"]])).astype("str") + elem_xarray_dict = dict( + _gen_xarray_dict_iterator_from_elems(elem_dict, dim_name, index) + ) + if use_range_index: + elem_xarray_dict[DUMMY_RANGE_INDEX_KEY] = XVariable( + [DUMMY_RANGE_INDEX_KEY], + data=index, + ) + ds = Dataset2D(XDataset(elem_xarray_dict)) + ds.is_backed = True + # We ensure the indexing_key attr always points to the true index + # so that the roundtrip works even for the `use_range_index` `True` case + ds.true_index_dim = elem.attrs["_index"] + return ds + + +@_LAZY_REGISTRY.register_read(ZarrGroup, IOSpec("categorical", "0.2.0")) +@_LAZY_REGISTRY.register_read(H5Group, IOSpec("categorical", "0.2.0")) +@requires_xarray +def read_categorical( + elem: H5Group | ZarrGroup, + *, + _reader: LazyReader, + chunks: tuple[int, ...] | None = None, +) -> CategoricalArray: + from anndata.experimental.backed._lazy_arrays import CategoricalArray + + del chunks # ignored when reading groups + + base_path_or_zarr_group = ( + Path(filename(elem)) if isinstance(elem, H5Group) else elem + ) + elem_name = get_elem_name(elem) + return CategoricalArray( + codes=elem["codes"], + categories=elem["categories"], + ordered=elem.attrs["ordered"], + base_path_or_zarr_group=base_path_or_zarr_group, + elem_name=elem_name, + ) + + +@requires_xarray +def read_nullable( + elem: H5Group | ZarrGroup, + *, + encoding_type: Literal[ + "nullable-integer", "nullable-boolean", "nullable-string-array" + ], + _reader: LazyReader, + chunks: tuple[int, ...] | None = None, +) -> MaskedArray: + from anndata.experimental.backed._lazy_arrays import MaskedArray + + del chunks # ignored when reading groups + + base_path_or_zarr_group = ( + Path(filename(elem)) if isinstance(elem, H5Group) else elem + ) + elem_name = get_elem_name(elem) + values = elem["values"] + # HDF5 stores strings as bytes; use .astype("T") to decode on access + # h5py recommends .astype("T") over .asstr() when using numpy ≥2 + if encoding_type == "nullable-string-array" and isinstance(elem, H5Group): + values = values.astype("T") if NUMPY_2 else values.asstr() + return MaskedArray( + values=values, + mask=elem["mask"], + dtype_str=encoding_type, + base_path_or_zarr_group=base_path_or_zarr_group, + elem_name=elem_name, + ) + + +for dtype in ["integer", "boolean", "string-array"]: + for group_type in [ZarrGroup, H5Group]: + _LAZY_REGISTRY.register_read(group_type, IOSpec(f"nullable-{dtype}", "0.1.0"))( + partial(read_nullable, encoding_type=f"nullable-{dtype}") + ) diff --git a/.venv/lib/python3.11/site-packages/anndata/_io/specs/methods.py b/.venv/lib/python3.11/site-packages/anndata/_io/specs/methods.py new file mode 100644 index 0000000000000000000000000000000000000000..e436b59f76dec61dd6f11458b3db9a41654bff8b --- /dev/null +++ b/.venv/lib/python3.11/site-packages/anndata/_io/specs/methods.py @@ -0,0 +1,1477 @@ +from __future__ import annotations + +import warnings +from collections.abc import Mapping +from contextlib import contextmanager, nullcontext +from copy import copy +from functools import partial, wraps +from importlib.metadata import version +from itertools import product +from types import MappingProxyType +from typing import TYPE_CHECKING, Protocol, TypeVar +from warnings import warn + +import h5py +import numpy as np +import pandas as pd +import zarr +from packaging.version import Version +from scipy import sparse + +import anndata as ad +from anndata import AnnData, Raw +from anndata._core import views +from anndata._core.index import _normalize_indices +from anndata._core.merge import intersect_keys +from anndata._core.sparse_dataset import _CSCDataset, _CSRDataset, sparse_dataset +from anndata._io.utils import check_key, zero_dim_array_as_scalar +from anndata._types import StorageType +from anndata._warnings import OldFormatWarning +from anndata.compat import ( + AwkArray, + CupyArray, + CupyCSCMatrix, + CupyCSRMatrix, + DaskArray, + H5Array, + H5File, + H5Group, + ZarrArray, + ZarrGroup, + _decode_structured_array, + _from_fixed_length_strings, + _read_attr, + _require_group_write_dataframe, +) +from anndata.typing import RWAble + +from ..._settings import settings +from ...compat import NULLABLE_NUMPY_STRING_TYPE, PANDAS_STRING_ARRAY_TYPES, is_zarr_v2 +from .registry import _REGISTRY, IOSpec, read_elem, read_elem_partial + +if TYPE_CHECKING: + from collections.abc import Generator, Iterator + from os import PathLike + from typing import Any, Literal + + from numpy import typing as npt + from numpy.typing import NDArray + + from anndata._types import ArrayStorageType, GroupStorageType + from anndata.compat import CSArray, CSMatrix + from anndata.typing import AxisStorable, InMemoryArrayOrScalarType + + from ...types import _WriteInternal + from .registry import Reader, Writer + +#################### +# Dask utils # +#################### + +try: + from dask.utils import SerializableLock as Lock +except ImportError: + from threading import Lock + +# to fix https://github.com/dask/distributed/issues/780 +GLOBAL_LOCK = Lock() + +#################### +# Dispatch methods # +#################### + +# def is_full_slice(idx): +# if isinstance(idx, tuple)len(idx) == 1: + +# if isinstance(idx, type(None)): +# return True +# elif idx is Ellipsis: +# return True +# elif isinstance(idx, tuple): +# for el in idx: +# if isinstance(el, type(None)): +# pass +# elif isinstance(el, slice): +# if el != slice(None): +# return False +# else: +# return False +# return True +# return False + + +def zarr_v3_compressor_compat(dataset_kwargs: dict) -> dict: + """Handle mismatch between our compressor kwarg and :func:`zarr.create_array` in v3's `compressors` arg + See https://zarr.readthedocs.io/en/stable/api/zarr/create/#zarr.create_array + + Parameters + ---------- + dataset_kwarg + The kwarg dict potentially containing "compressor" + + Returns + ------- + The kwarg dict with "compressor" moved to "compressors" if zarr v3 is in use. + """ + if not is_zarr_v2() and "compressor" in dataset_kwargs: + dataset_kwargs["compressors"] = dataset_kwargs.pop("compressor") + return dataset_kwargs + + +@contextmanager +def zarr_v3_sharding(dataset_kwargs: dict, format: Literal[2, 3]) -> Generator[dict]: + has_no_shards_kwarg = "shards" not in dataset_kwargs + use_auto_sharding = ( + has_no_shards_kwarg and ad.settings.auto_shard_zarr_v3 and format == 3 + ) + if has_no_shards_kwarg and ad.settings.auto_shard_zarr_v3 is None and format == 3: + warnings.warn( + "zarr v3 autosharding will be the default in the next minor release.", + UserWarning, + stacklevel=2, + ) + elif use_auto_sharding: + dataset_kwargs = {**dataset_kwargs, "shards": "auto"} + # Auto shard sizes are a relatively recent feature + supports_auto_shard_size = Version(version("zarr")) >= Version("3.1.4") + has_auto_shard_size = supports_auto_shard_size and isinstance( + zarr.config.get("array.target_shard_size_bytes"), int + ) + # 1GB uncompressed shard size seems reasonable. + # Shards need to generally held completely in memory before writing. + # Even at a compression ration of 6x, that's still a ~20x improvement on number of files. + # Users can ovetrride this nonetheless, hence the above checks. + with ( + zarr.config.set({"array.target_shard_size_bytes": 1_000_000_000}) + if supports_auto_shard_size and not has_auto_shard_size and use_auto_sharding + else nullcontext() + ): + yield dataset_kwargs + + +def _to_cpu_mem_wrapper(write_func): + """ + Wrapper to bring cupy types into cpu memory before writing. + + Ideally we do direct writing at some point. + """ + + def wrapper( + f, + k, + cupy_val: CupyArray | CupyCSCMatrix | CupyCSRMatrix, + *, + _writer: Writer, + dataset_kwargs: Mapping[str, Any] = MappingProxyType({}), + ): + return write_func( + f, k, cupy_val.get(), _writer=_writer, dataset_kwargs=dataset_kwargs + ) + + return wrapper + + +S = TypeVar("S", bound=StorageType) +T = TypeVar("T", bound=RWAble) + + +def suppress_autoshard_warning( + func: _WriteInternal[S, T], +) -> _WriteInternal[S, T]: + @wraps(func) + def wrapper( + f: S, + k: str, + val: T, + *, + _writer: Writer, + dataset_kwargs: Mapping[str, Any] = MappingProxyType({}), + ): + with warnings.catch_warnings(): + # Suppress warnings only if the user has opted into autosharding at the top level. + # If someone provides `shards` explicitly, then they should get the warning. + if ad.settings.auto_shard_zarr_v3 and "shards" not in dataset_kwargs: + warnings.filterwarnings( + "ignore", + r"Automatic shard shape inference is experimental", + UserWarning, + ) + return func(f, k, val, _writer=_writer, dataset_kwargs=dataset_kwargs) + + return wrapper + + +################################ +# Fallbacks / backwards compat # +################################ + +# Note: there is no need for writing in a backwards compatible format, maybe + + +@_REGISTRY.register_read(H5File, IOSpec("", "")) +@_REGISTRY.register_read(H5Group, IOSpec("", "")) +@_REGISTRY.register_read(H5Array, IOSpec("", "")) +def read_basic( + elem: H5File | H5Group | H5Array, *, _reader: Reader +) -> dict[str, InMemoryArrayOrScalarType] | npt.NDArray | CSMatrix | CSArray: + from anndata._io import h5ad + + warn( + f"Element '{elem.name}' was written without encoding metadata.", + OldFormatWarning, + stacklevel=3, + ) + + if isinstance(elem, Mapping): + # Backwards compat sparse arrays + if "h5sparse_format" in elem.attrs: + return sparse_dataset(elem).to_memory() + return {k: _reader.read_elem(v) for k, v in dict(elem).items()} + elif isinstance(elem, h5py.Dataset): + return h5ad.read_dataset(elem) # TODO: Handle legacy + + +@_REGISTRY.register_read(ZarrGroup, IOSpec("", "")) +@_REGISTRY.register_read(ZarrArray, IOSpec("", "")) +def read_basic_zarr( + elem: ZarrGroup | ZarrArray, *, _reader: Reader +) -> dict[str, InMemoryArrayOrScalarType] | npt.NDArray | CSMatrix | CSArray: + from anndata._io import zarr + + warn( + f"Element '{elem.name}' was written without encoding metadata.", + OldFormatWarning, + stacklevel=3, + ) + if isinstance(elem, ZarrGroup): + # Backwards compat sparse arrays + if "h5sparse_format" in elem.attrs: + return sparse_dataset(elem).to_memory() + return {k: _reader.read_elem(v) for k, v in dict(elem).items()} + elif isinstance(elem, ZarrArray): + return zarr.read_dataset(elem) # TODO: Handle legacy + + +# @_REGISTRY.register_read_partial(IOSpec("", "")) +# def read_basic_partial(elem, *, items=None, indices=(slice(None), slice(None))): +# if isinstance(elem, Mapping): +# return _read_partial(elem, items=items, indices=indices) +# elif indices != (slice(None), slice(None)): +# return elem[indices] +# else: +# return elem[()] + + +########### +# AnnData # +########### + + +def read_indices(group): + obs_group = group["obs"] + obs_idx_elem = obs_group[_read_attr(obs_group.attrs, "_index")] + obs_idx = read_elem(obs_idx_elem) + var_group = group["var"] + var_idx_elem = var_group[_read_attr(var_group.attrs, "_index")] + var_idx = read_elem(var_idx_elem) + return obs_idx, var_idx + + +def read_partial( # noqa: PLR0913 + pth: PathLike[str] | str, + *, + obs_idx=slice(None), + var_idx=slice(None), + X=True, + obs=None, + var=None, + obsm=None, + varm=None, + obsp=None, + varp=None, + layers=None, + uns=None, +) -> ad.AnnData: + result = {} + with h5py.File(pth, "r") as f: + obs_idx, var_idx = _normalize_indices((obs_idx, var_idx), *read_indices(f)) + result["obs"] = read_elem_partial( + f["obs"], items=obs, indices=(obs_idx, slice(None)) + ) + result["var"] = read_elem_partial( + f["var"], items=var, indices=(var_idx, slice(None)) + ) + if X: + result["X"] = read_elem_partial(f["X"], indices=(obs_idx, var_idx)) + else: + result["X"] = sparse.csr_matrix((len(result["obs"]), len(result["var"]))) + if "obsm" in f: + result["obsm"] = _read_partial( + f["obsm"], items=obsm, indices=(obs_idx, slice(None)) + ) + if "varm" in f: + result["varm"] = _read_partial( + f["varm"], items=varm, indices=(var_idx, slice(None)) + ) + if "obsp" in f: + result["obsp"] = _read_partial( + f["obsp"], items=obsp, indices=(obs_idx, obs_idx) + ) + if "varp" in f: + result["varp"] = _read_partial( + f["varp"], items=varp, indices=(var_idx, var_idx) + ) + if "layers" in f: + result["layers"] = _read_partial( + f["layers"], items=layers, indices=(obs_idx, var_idx) + ) + if "uns" in f: + result["uns"] = _read_partial(f["uns"], items=uns) + + return ad.AnnData(**result) + + +def _read_partial(group, *, items=None, indices=(slice(None), slice(None))): + if group is None: + return None + keys = intersect_keys((group,)) if items is None else intersect_keys((group, items)) + result = {} + for k in keys: + next_items = items.get(k, None) if isinstance(items, Mapping) else None + result[k] = read_elem_partial(group[k], items=next_items, indices=indices) + return result + + +@_REGISTRY.register_write(ZarrGroup, AnnData, IOSpec("anndata", "0.1.0")) +@_REGISTRY.register_write(H5Group, AnnData, IOSpec("anndata", "0.1.0")) +@suppress_autoshard_warning +def write_anndata( + f: GroupStorageType, + k: str, + adata: AnnData, + *, + _writer: Writer, + dataset_kwargs: Mapping[str, Any] = MappingProxyType({}), +): + g = f.require_group(k) + if adata.X is not None: + _writer.write_elem(g, "X", adata.X, dataset_kwargs=dataset_kwargs) + _writer.write_elem(g, "obs", adata.obs, dataset_kwargs=dataset_kwargs) + _writer.write_elem(g, "var", adata.var, dataset_kwargs=dataset_kwargs) + _writer.write_elem(g, "obsm", dict(adata.obsm), dataset_kwargs=dataset_kwargs) + _writer.write_elem(g, "varm", dict(adata.varm), dataset_kwargs=dataset_kwargs) + _writer.write_elem(g, "obsp", dict(adata.obsp), dataset_kwargs=dataset_kwargs) + _writer.write_elem(g, "varp", dict(adata.varp), dataset_kwargs=dataset_kwargs) + _writer.write_elem(g, "layers", dict(adata.layers), dataset_kwargs=dataset_kwargs) + _writer.write_elem(g, "uns", dict(adata.uns), dataset_kwargs=dataset_kwargs) + _writer.write_elem(g, "raw", adata.raw, dataset_kwargs=dataset_kwargs) + + +@_REGISTRY.register_read(H5Group, IOSpec("anndata", "0.1.0")) +@_REGISTRY.register_read(H5Group, IOSpec("raw", "0.1.0")) +@_REGISTRY.register_read(H5File, IOSpec("anndata", "0.1.0")) +@_REGISTRY.register_read(H5File, IOSpec("raw", "0.1.0")) +@_REGISTRY.register_read(ZarrGroup, IOSpec("anndata", "0.1.0")) +@_REGISTRY.register_read(ZarrGroup, IOSpec("raw", "0.1.0")) +def read_anndata(elem: GroupStorageType | H5File, *, _reader: Reader) -> AnnData: + d = {} + for k in [ + "X", + "obs", + "var", + "obsm", + "varm", + "obsp", + "varp", + "layers", + "uns", + "raw", + ]: + if k in elem: + d[k] = _reader.read_elem(elem[k]) + return AnnData(**d) + + +@_REGISTRY.register_write(H5Group, Raw, IOSpec("raw", "0.1.0")) +@_REGISTRY.register_write(ZarrGroup, Raw, IOSpec("raw", "0.1.0")) +@suppress_autoshard_warning +def write_raw( + f: GroupStorageType, + k: str, + raw: Raw, + *, + _writer: Writer, + dataset_kwargs: Mapping[str, Any] = MappingProxyType({}), +): + g = f.require_group(k) + _writer.write_elem(g, "X", raw.X, dataset_kwargs=dataset_kwargs) + _writer.write_elem(g, "var", raw.var, dataset_kwargs=dataset_kwargs) + _writer.write_elem(g, "varm", dict(raw.varm), dataset_kwargs=dataset_kwargs) + + +######## +# Null # +######## + + +@_REGISTRY.register_read(H5Array, IOSpec("null", "0.1.0")) +@_REGISTRY.register_read(ZarrArray, IOSpec("null", "0.1.0")) +def read_null(_elem, _reader) -> None: + return None + + +@_REGISTRY.register_write(H5Group, type(None), IOSpec("null", "0.1.0")) +def write_null_h5py(f, k, _v, _writer, dataset_kwargs=MappingProxyType({})): + dataset_kwargs = _remove_scalar_compression_args(dataset_kwargs) + f.create_dataset(k, data=h5py.Empty("f"), **dataset_kwargs) + + +@_REGISTRY.register_write(ZarrGroup, type(None), IOSpec("null", "0.1.0")) +@suppress_autoshard_warning +def write_null_zarr(f, k, _v, _writer, dataset_kwargs=MappingProxyType({})): + dataset_kwargs = _remove_scalar_compression_args(dataset_kwargs) + # zarr has no first-class null dataset + if is_zarr_v2(): + import zarr + + # zarr has no first-class null dataset + f.create_dataset(k, data=zarr.empty(()), **dataset_kwargs) + else: + # TODO: why is this not actually storing the empty info with a f.empty call? + # It fails complaining that k doesn't exist when updating the attributes. + f.create_array(k, shape=(), dtype="bool") + + +############ +# Mappings # +############ + + +@_REGISTRY.register_read(H5Group, IOSpec("dict", "0.1.0")) +@_REGISTRY.register_read(ZarrGroup, IOSpec("dict", "0.1.0")) +def read_mapping(elem: GroupStorageType, *, _reader: Reader) -> dict[str, AxisStorable]: + return {k: _reader.read_elem(v) for k, v in dict(elem).items()} + + +@_REGISTRY.register_write(H5Group, dict, IOSpec("dict", "0.1.0")) +@_REGISTRY.register_write(ZarrGroup, dict, IOSpec("dict", "0.1.0")) +@suppress_autoshard_warning +def write_mapping( + f: GroupStorageType, + k: str, + v: dict[str, AxisStorable], + *, + _writer: Writer, + dataset_kwargs: Mapping[str, Any] = MappingProxyType({}), +): + g = f.require_group(k) + for sub_k, sub_v in v.items(): + _writer.write_elem(g, sub_k, sub_v, dataset_kwargs=dataset_kwargs) + + +############## +# np.ndarray # +############## + + +@_REGISTRY.register_write(H5Group, list, IOSpec("array", "0.2.0")) +@_REGISTRY.register_write(ZarrGroup, list, IOSpec("array", "0.2.0")) +@suppress_autoshard_warning +def write_list( + f: GroupStorageType, + k: str, + elem: list[AxisStorable], + *, + _writer: Writer, + dataset_kwargs: Mapping[str, Any] = MappingProxyType({}), +): + _writer.write_elem(f, k, np.array(elem), dataset_kwargs=dataset_kwargs) + + +# TODO: Is this the right behavior for MaskedArrays? +# It's in the `AnnData.concatenate` docstring, but should we keep it? +@_REGISTRY.register_write(H5Group, views.ArrayView, IOSpec("array", "0.2.0")) +@_REGISTRY.register_write(H5Group, np.ndarray, IOSpec("array", "0.2.0")) +@_REGISTRY.register_write(H5Group, np.ma.MaskedArray, IOSpec("array", "0.2.0")) +@_REGISTRY.register_write(ZarrGroup, views.ArrayView, IOSpec("array", "0.2.0")) +@_REGISTRY.register_write(ZarrGroup, np.ndarray, IOSpec("array", "0.2.0")) +@_REGISTRY.register_write(ZarrGroup, np.ma.MaskedArray, IOSpec("array", "0.2.0")) +@_REGISTRY.register_write(ZarrGroup, ZarrArray, IOSpec("array", "0.2.0")) +@_REGISTRY.register_write(ZarrGroup, H5Array, IOSpec("array", "0.2.0")) +@suppress_autoshard_warning +@zero_dim_array_as_scalar +def write_basic( + f: GroupStorageType, + k: str, + elem: views.ArrayView | np.ndarray | h5py.Dataset | np.ma.MaskedArray | ZarrArray, + *, + _writer: Writer, + dataset_kwargs: Mapping[str, Any] = MappingProxyType({}), +): + """Write methods which underlying library handles natively.""" + dataset_kwargs = dict(dataset_kwargs) + dtype = dataset_kwargs.pop("dtype", elem.dtype) + if isinstance(f, H5Group) or is_zarr_v2(): + f.create_dataset(k, data=elem, shape=elem.shape, dtype=dtype, **dataset_kwargs) + else: + dataset_kwargs = zarr_v3_compressor_compat(dataset_kwargs) + with zarr_v3_sharding( + dataset_kwargs, format=f.metadata.zarr_format + ) as dataset_kwargs: + f.create_array(k, shape=elem.shape, dtype=dtype, **dataset_kwargs) + # see https://github.com/zarr-developers/zarr-python/discussions/2712 + if isinstance(elem, ZarrArray | H5Array): + f[k][...] = elem[...] + else: + f[k][...] = elem + + +def _iter_chunks_for_copy( + elem: ArrayStorageType, dest: ArrayStorageType +) -> Iterator[slice | tuple[list[slice]]]: + """ + Returns an iterator of tuples of slices for copying chunks from `elem` to `dest`. + + * If `dest` has chunks, it will return the chunks of `dest`. + * If `dest` is not chunked, we write it in ~100MB chunks or 1000 rows, whichever is larger. + """ + if dest.chunks and hasattr(dest, "iter_chunks"): + return dest.iter_chunks() + else: + shape = elem.shape + # Number of rows that works out to + n_rows = max( + ad.settings.min_rows_for_chunked_h5_copy, + elem.chunks[0] if elem.chunks is not None else 1, + ) + return (slice(i, min(i + n_rows, shape[0])) for i in range(0, shape[0], n_rows)) + + +@_REGISTRY.register_write(H5Group, H5Array, IOSpec("array", "0.2.0")) +@_REGISTRY.register_write(H5Group, ZarrArray, IOSpec("array", "0.2.0")) +def write_chunked_dense_array_to_group( + f: H5Group, + k: str, + elem: ArrayStorageType, + *, + _writer: Writer, + dataset_kwargs: Mapping[str, Any] = MappingProxyType({}), +): + """Write to a h5py.Dataset in chunks. + + `h5py.Group.create_dataset(..., data: h5py.Dataset)` will load all of `data` into memory + before writing. Instead, we will write in chunks to avoid this. We don't need to do this for + zarr since zarr handles this automatically. + """ + dtype = dataset_kwargs.get("dtype", elem.dtype) + kwargs = {**dataset_kwargs, "dtype": dtype} + dest = f.create_dataset(k, shape=elem.shape, **kwargs) + + for chunk in _iter_chunks_for_copy(elem, dest): + dest[chunk] = elem[chunk] + + +_REGISTRY.register_write(H5Group, CupyArray, IOSpec("array", "0.2.0"))( + _to_cpu_mem_wrapper(write_basic) +) +_REGISTRY.register_write(ZarrGroup, CupyArray, IOSpec("array", "0.2.0"))( + suppress_autoshard_warning(_to_cpu_mem_wrapper(write_basic)) +) + + +@_REGISTRY.register_write(ZarrGroup, views.DaskArrayView, IOSpec("array", "0.2.0")) +@_REGISTRY.register_write(ZarrGroup, DaskArray, IOSpec("array", "0.2.0")) +@_REGISTRY.register_write(H5Group, views.DaskArrayView, IOSpec("array", "0.2.0")) +@_REGISTRY.register_write(H5Group, DaskArray, IOSpec("array", "0.2.0")) +@suppress_autoshard_warning +def write_basic_dask_dask_dense( + f: ZarrGroup | H5Group, + k: str, + elem: DaskArray, + *, + _writer: Writer, + dataset_kwargs: Mapping[str, Any] = MappingProxyType({}), +): + import dask.array as da + + dataset_kwargs = dict(dataset_kwargs) + is_h5 = isinstance(f, H5Group) + if is_zarr_v2() or is_h5: + g = f.require_dataset(k, shape=elem.shape, dtype=elem.dtype, **dataset_kwargs) + else: + dataset_kwargs = zarr_v3_compressor_compat(dataset_kwargs) + with zarr_v3_sharding( + dataset_kwargs, format=f.metadata.zarr_format + ) as dataset_kwargs: + g = f.require_array(k, shape=elem.shape, dtype=elem.dtype, **dataset_kwargs) + da.store(elem, g, scheduler="threads") + + +@_REGISTRY.register_read(H5Array, IOSpec("array", "0.2.0")) +@_REGISTRY.register_read(ZarrArray, IOSpec("array", "0.2.0")) +@_REGISTRY.register_read(ZarrArray, IOSpec("string-array", "0.2.0")) +def read_array(elem: ArrayStorageType, *, _reader: Reader) -> npt.NDArray: + return elem[()] + + +@_REGISTRY.register_read_partial(H5Array, IOSpec("array", "0.2.0")) +@_REGISTRY.register_read_partial(ZarrArray, IOSpec("string-array", "0.2.0")) +def read_array_partial(elem, *, items=None, indices=(slice(None, None))): + return elem[indices] + + +@_REGISTRY.register_read_partial(ZarrArray, IOSpec("array", "0.2.0")) +def read_zarr_array_partial(elem, *, items=None, indices=(slice(None, None))): + return elem.oindex[indices] + + +# arrays of strings +@_REGISTRY.register_read(H5Array, IOSpec("string-array", "0.2.0")) +def read_string_array(d: H5Array, *, _reader: Reader): + return read_array(d.asstr(), _reader=_reader) + + +@_REGISTRY.register_read_partial(H5Array, IOSpec("string-array", "0.2.0")) +def read_string_array_partial(d, items=None, indices=slice(None)): + return read_array_partial(d.asstr(), items=items, indices=indices) + + +@_REGISTRY.register_write( + H5Group, (views.ArrayView, "U"), IOSpec("string-array", "0.2.0") +) +@_REGISTRY.register_write( + H5Group, (views.ArrayView, "O"), IOSpec("string-array", "0.2.0") +) +@_REGISTRY.register_write(H5Group, (np.ndarray, "U"), IOSpec("string-array", "0.2.0")) +@_REGISTRY.register_write(H5Group, (np.ndarray, "O"), IOSpec("string-array", "0.2.0")) +@_REGISTRY.register_write(H5Group, (np.ndarray, "T"), IOSpec("string-array", "0.2.0")) +@zero_dim_array_as_scalar +def write_vlen_string_array( + f: H5Group, + k: str, + elem: np.ndarray, + *, + _writer: Writer, + dataset_kwargs: Mapping[str, Any] = MappingProxyType({}), +): + """Write methods which underlying library handles nativley.""" + str_dtype = h5py.special_dtype(vlen=str) + f.create_dataset(k, data=elem.astype(str_dtype), dtype=str_dtype, **dataset_kwargs) + + +@_REGISTRY.register_write( + ZarrGroup, (views.ArrayView, "U"), IOSpec("string-array", "0.2.0") +) +@_REGISTRY.register_write( + ZarrGroup, (views.ArrayView, "O"), IOSpec("string-array", "0.2.0") +) +@_REGISTRY.register_write(ZarrGroup, (np.ndarray, "U"), IOSpec("string-array", "0.2.0")) +@_REGISTRY.register_write(ZarrGroup, (np.ndarray, "O"), IOSpec("string-array", "0.2.0")) +@_REGISTRY.register_write(ZarrGroup, (np.ndarray, "T"), IOSpec("string-array", "0.2.0")) +@suppress_autoshard_warning +@zero_dim_array_as_scalar +def write_vlen_string_array_zarr( + f: ZarrGroup, + k: str, + elem: np.ndarray, + *, + _writer: Writer, + dataset_kwargs: Mapping[str, Any] = MappingProxyType({}), +): + if is_zarr_v2(): + import numcodecs + + if Version(version("numcodecs")) < Version("0.13"): + msg = "Old numcodecs version detected. Please update for improved performance and stability." + warnings.warn(msg, UserWarning, stacklevel=2) + # Workaround for https://github.com/zarr-developers/numcodecs/issues/514 + if hasattr(elem, "flags") and not elem.flags.writeable: + elem = elem.copy() + + f.create_dataset( + k, + shape=elem.shape, + dtype=object, + object_codec=numcodecs.VLenUTF8(), + **dataset_kwargs, + ) + f[k][:] = elem + else: + from numcodecs import VLenUTF8 + from zarr.core.dtype import VariableLengthUTF8 + + dataset_kwargs = dict(dataset_kwargs) + dataset_kwargs = zarr_v3_compressor_compat(dataset_kwargs) + dtype = VariableLengthUTF8() + filters, fill_value = None, None + if f.metadata.zarr_format == 2: + filters, fill_value = [VLenUTF8()], "" + with zarr_v3_sharding( + dataset_kwargs, format=f.metadata.zarr_format + ) as dataset_kwargs: + f.create_array( + k, + shape=elem.shape, + dtype=dtype, + filters=filters, + fill_value=fill_value, + **dataset_kwargs, + ) + f[k][:] = elem + + +############### +# np.recarray # +############### + + +def _to_hdf5_vlen_strings(value: np.ndarray) -> np.ndarray: + """This corrects compound dtypes to work with hdf5 files.""" + new_dtype = [] + for dt_name, (dt_type, _) in value.dtype.fields.items(): + if dt_type.kind in {"U", "O"}: + new_dtype.append((dt_name, h5py.special_dtype(vlen=str))) + else: + new_dtype.append((dt_name, dt_type)) + return value.astype(new_dtype) + + +@_REGISTRY.register_read(H5Array, IOSpec("rec-array", "0.2.0")) +@_REGISTRY.register_read(ZarrArray, IOSpec("rec-array", "0.2.0")) +def read_recarray(d: ArrayStorageType, *, _reader: Reader) -> np.recarray | npt.NDArray: + value = d[()] + value = _decode_structured_array( + _from_fixed_length_strings(value), dtype=value.dtype + ) + return value + + +@_REGISTRY.register_write(H5Group, (np.ndarray, "V"), IOSpec("rec-array", "0.2.0")) +@_REGISTRY.register_write(H5Group, np.recarray, IOSpec("rec-array", "0.2.0")) +def write_recarray( + f: H5Group, + k: str, + elem: np.ndarray | np.recarray, + *, + _writer: Writer, + dataset_kwargs: Mapping[str, Any] = MappingProxyType({}), +): + f.create_dataset(k, data=_to_hdf5_vlen_strings(elem), **dataset_kwargs) + + +@_REGISTRY.register_write(ZarrGroup, (np.ndarray, "V"), IOSpec("rec-array", "0.2.0")) +@_REGISTRY.register_write(ZarrGroup, np.recarray, IOSpec("rec-array", "0.2.0")) +def write_recarray_zarr( + f: ZarrGroup, + k: str, + elem: np.ndarray | np.recarray, + *, + _writer: Writer, + dataset_kwargs: Mapping[str, Any] = MappingProxyType({}), +): + from anndata.compat import _to_fixed_length_strings + + elem = _to_fixed_length_strings(elem) + if is_zarr_v2(): + f.create_dataset(k, data=elem, shape=elem.shape, **dataset_kwargs) + else: + dataset_kwargs = dict(dataset_kwargs) + dataset_kwargs = zarr_v3_compressor_compat(dataset_kwargs) + # https://github.com/zarr-developers/zarr-python/issues/3546 + # with zarr_v3_sharding( + # dataset_kwargs, format=f.metadata.zarr_format + # ) as dataset_kwargs: + f.create_array(k, shape=elem.shape, dtype=elem.dtype, **dataset_kwargs) + f[k][...] = elem + + +################# +# Sparse arrays # +################# + + +def write_sparse_compressed( + f: GroupStorageType, + key: str, + value: CSMatrix | CSArray, + *, + _writer: Writer, + fmt: Literal["csr", "csc"], + dataset_kwargs=MappingProxyType({}), +): + g = f.require_group(key) + g.attrs["shape"] = value.shape + dataset_kwargs = dict(dataset_kwargs) + indptr_dtype = dataset_kwargs.pop("indptr_dtype", value.indptr.dtype) + + # Allow resizing for hdf5 + if isinstance(f, H5Group): + dataset_kwargs = dict(maxshape=(None,), **dataset_kwargs) + dataset_kwargs = zarr_v3_compressor_compat(dataset_kwargs) + + for attr_name in ["data", "indices", "indptr"]: + attr = getattr(value, attr_name) + dtype = indptr_dtype if attr_name == "indptr" else attr.dtype + if ( + attr_name == "indices" + and settings.write_csr_csc_indices_with_min_possible_dtype + ): + # np.min_scalar_type can return things like np.ulonglong which zarr doesn't understand + # and I find this clearer as to what the result type is i.e., unsigned or signed. + # For example `np.iinfo(np.uint16).max + 1` could be either `uint32` or `int32`, + # and there's nothing in numpy's docs disallowing this output to change. + if (minor_axis_size := value.shape[value.format == "csr"]) <= np.iinfo( + np.uint8 + ).max: + dtype = np.dtype("uint8") + elif minor_axis_size <= np.iinfo(np.uint16).max: + dtype = np.dtype("uint16") + elif minor_axis_size <= np.iinfo(np.uint32).max: + dtype = np.dtype("uint32") + elif minor_axis_size <= np.iinfo(np.uint64).max: + dtype = np.dtype("uint64") + if isinstance(f, H5Group) or is_zarr_v2(): + g.create_dataset( + attr_name, data=attr, shape=attr.shape, dtype=dtype, **dataset_kwargs + ) + else: + with zarr_v3_sharding( + dataset_kwargs, format=f.metadata.zarr_format + ) as dataset_kwargs_local: + arr = g.create_array( + attr_name, shape=attr.shape, dtype=dtype, **dataset_kwargs_local + ) + # see https://github.com/zarr-developers/zarr-python/discussions/2712 + arr[...] = attr[...] + + +write_csr, write_csc = ( + suppress_autoshard_warning(partial(write_sparse_compressed, fmt=fmt)) + for fmt in ["csr", "csc"] +) + +for store_type, (cls, spec, func) in product( + (H5Group, ZarrGroup), + [ + # spmatrix + (sparse.csr_matrix, IOSpec("csr_matrix", "0.1.0"), write_csr), + (views.SparseCSRMatrixView, IOSpec("csr_matrix", "0.1.0"), write_csr), + (sparse.csc_matrix, IOSpec("csc_matrix", "0.1.0"), write_csc), + (views.SparseCSCMatrixView, IOSpec("csc_matrix", "0.1.0"), write_csc), + # sparray + (sparse.csr_array, IOSpec("csr_matrix", "0.1.0"), write_csr), + (views.SparseCSRArrayView, IOSpec("csr_matrix", "0.1.0"), write_csr), + (sparse.csc_array, IOSpec("csc_matrix", "0.1.0"), write_csc), + (views.SparseCSCArrayView, IOSpec("csc_matrix", "0.1.0"), write_csc), + # cupy spmatrix + (CupyCSRMatrix, IOSpec("csr_matrix", "0.1.0"), _to_cpu_mem_wrapper(write_csr)), + ( + views.CupySparseCSRView, + IOSpec("csr_matrix", "0.1.0"), + _to_cpu_mem_wrapper(write_csr), + ), + (CupyCSCMatrix, IOSpec("csc_matrix", "0.1.0"), _to_cpu_mem_wrapper(write_csc)), + ( + views.CupySparseCSCView, + IOSpec("csc_matrix", "0.1.0"), + _to_cpu_mem_wrapper(write_csc), + ), + ], +): + _REGISTRY.register_write(store_type, cls, spec)(func) + + +@_REGISTRY.register_write(H5Group, _CSRDataset, IOSpec("csr_matrix", "0.1.0")) +@_REGISTRY.register_write(H5Group, _CSCDataset, IOSpec("csc_matrix", "0.1.0")) +@_REGISTRY.register_write(ZarrGroup, _CSRDataset, IOSpec("csr_matrix", "0.1.0")) +@_REGISTRY.register_write(ZarrGroup, _CSCDataset, IOSpec("csc_matrix", "0.1.0")) +@suppress_autoshard_warning +def write_sparse_dataset( + f: GroupStorageType, + k: str, + elem: _CSCDataset | _CSRDataset, + *, + _writer: Writer, + dataset_kwargs: Mapping[str, Any] = MappingProxyType({}), +): + write_sparse_compressed( + f, + k, + elem._to_backed(), + _writer=_writer, + fmt=elem.format, + dataset_kwargs=dataset_kwargs, + ) + + +def write_cupy_dask(f, k, elem, _writer, dataset_kwargs=MappingProxyType({})): + _writer.write_elem( + f, + k, + elem.map_blocks(lambda x: x.get(), dtype=elem.dtype, meta=elem._meta.get()), + dataset_kwargs=dataset_kwargs, + ) + + +def write_dask_sparse( + f: GroupStorageType, + k: str, + elem: DaskArray, + *, + _writer: Writer, + dataset_kwargs: Mapping[str, Any] = MappingProxyType({}), +): + sparse_format = elem._meta.format + + def as_int64_indices(x): + x.indptr = x.indptr.astype(np.int64, copy=False) + x.indices = x.indices.astype(np.int64, copy=False) + return x + + if sparse_format == "csr": + axis = 0 + elif sparse_format == "csc": + axis = 1 + else: + msg = f"Cannot write dask sparse arrays with format {sparse_format}" + raise NotImplementedError(msg) + + def chunk_slice(start: int, stop: int) -> tuple[slice | None, slice | None]: + result = [slice(None), slice(None)] + result[axis] = slice(start, stop) + return tuple(result) + + axis_chunks = elem.chunks[axis] + chunk_start = 0 + chunk_stop = axis_chunks[0] + + _writer.write_elem( + f, + k, + as_int64_indices(elem[chunk_slice(chunk_start, chunk_stop)].compute()), + dataset_kwargs=dataset_kwargs, + ) + + disk_mtx = sparse_dataset(f[k]) + + for chunk_size in axis_chunks[1:]: + chunk_start = chunk_stop + chunk_stop += chunk_size + + disk_mtx.append(elem[chunk_slice(chunk_start, chunk_stop)].compute()) + + +for array_type, group_type in product( + [DaskArray, views.DaskArrayView], [H5Group, ZarrGroup] +): + for cupy_array_type, spec in [ + (CupyArray, IOSpec("array", "0.2.0")), + (CupyCSCMatrix, IOSpec("csc_matrix", "0.1.0")), + (CupyCSRMatrix, IOSpec("csr_matrix", "0.1.0")), + ]: + _REGISTRY.register_write(group_type, (array_type, cupy_array_type), spec)( + write_cupy_dask + ) + for scipy_sparse_type, spec in [ + (sparse.csr_matrix, IOSpec("csr_matrix", "0.1.0")), + (sparse.csc_matrix, IOSpec("csc_matrix", "0.1.0")), + ]: + _REGISTRY.register_write(group_type, (array_type, scipy_sparse_type), spec)( + write_dask_sparse + ) + + +@_REGISTRY.register_read(H5Group, IOSpec("csc_matrix", "0.1.0")) +@_REGISTRY.register_read(H5Group, IOSpec("csr_matrix", "0.1.0")) +@_REGISTRY.register_read(ZarrGroup, IOSpec("csc_matrix", "0.1.0")) +@_REGISTRY.register_read(ZarrGroup, IOSpec("csr_matrix", "0.1.0")) +def read_sparse(elem: GroupStorageType, *, _reader: Reader) -> CSMatrix | CSArray: + return sparse_dataset(elem).to_memory() + + +@_REGISTRY.register_read_partial(H5Group, IOSpec("csc_matrix", "0.1.0")) +@_REGISTRY.register_read_partial(H5Group, IOSpec("csr_matrix", "0.1.0")) +@_REGISTRY.register_read_partial(ZarrGroup, IOSpec("csc_matrix", "0.1.0")) +@_REGISTRY.register_read_partial(ZarrGroup, IOSpec("csr_matrix", "0.1.0")) +def read_sparse_partial(elem, *, items=None, indices=(slice(None), slice(None))): + return sparse_dataset(elem)[indices] + + +################# +# Awkward array # +################# + + +@_REGISTRY.register_write(H5Group, AwkArray, IOSpec("awkward-array", "0.1.0")) +@_REGISTRY.register_write(ZarrGroup, AwkArray, IOSpec("awkward-array", "0.1.0")) +@_REGISTRY.register_write( + H5Group, views.AwkwardArrayView, IOSpec("awkward-array", "0.1.0") +) +@_REGISTRY.register_write( + ZarrGroup, views.AwkwardArrayView, IOSpec("awkward-array", "0.1.0") +) +@suppress_autoshard_warning +def write_awkward( + f: GroupStorageType, + k: str, + v: views.AwkwardArrayView | AwkArray, + *, + _writer: Writer, + dataset_kwargs: Mapping[str, Any] = MappingProxyType({}), +): + from anndata.compat import awkward as ak + + group = f.require_group(k) + del k + if isinstance(v, views.AwkwardArrayView): + # copy to remove the view attributes + v = copy(v) + form, length, container = ak.to_buffers(ak.to_packed(v)) + group.attrs["length"] = length + group.attrs["form"] = form.to_json() + for k, v in container.items(): + _writer.write_elem(group, k, v, dataset_kwargs=dataset_kwargs) + + +@_REGISTRY.register_read(H5Group, IOSpec("awkward-array", "0.1.0")) +@_REGISTRY.register_read(ZarrGroup, IOSpec("awkward-array", "0.1.0")) +def read_awkward(elem: GroupStorageType, *, _reader: Reader) -> AwkArray: + from anndata.compat import awkward as ak + + form = _read_attr(elem.attrs, "form") + length = _read_attr(elem.attrs, "length") + container = {k: _reader.read_elem(elem[k]) for k in elem} + + return ak.from_buffers(form, int(length), container) + + +############## +# DataFrames # +############## + + +@_REGISTRY.register_write(H5Group, views.DataFrameView, IOSpec("dataframe", "0.2.0")) +@_REGISTRY.register_write(H5Group, pd.DataFrame, IOSpec("dataframe", "0.2.0")) +@_REGISTRY.register_write(ZarrGroup, views.DataFrameView, IOSpec("dataframe", "0.2.0")) +@_REGISTRY.register_write(ZarrGroup, pd.DataFrame, IOSpec("dataframe", "0.2.0")) +@suppress_autoshard_warning +def write_dataframe( + f: GroupStorageType, + key: str, + df: views.DataFrameView | pd.DataFrame, + *, + _writer: Writer, + dataset_kwargs: Mapping[str, Any] = MappingProxyType({}), +): + # Check arguments + for reserved in ("_index",): + if reserved in df.columns: + msg = f"{reserved!r} is a reserved name for dataframe columns." + raise ValueError(msg) + group = _require_group_write_dataframe(f, key, df) + if not df.columns.is_unique: + duplicates = list(df.columns[df.columns.duplicated()]) + msg = f"Found repeated column names: {duplicates}. Column names must be unique." + raise ValueError(msg) + col_names = [check_key(c) for c in df.columns] + group.attrs["column-order"] = col_names + + if df.index.name is not None: + if df.index.name in col_names and not pd.Series( + df.index, index=df.index + ).equals(df[df.index.name]): + msg = ( + f"DataFrame.index.name ({df.index.name!r}) is also used by a column " + "whose values are different. This is not supported. Please make sure " + "the values are the same, or use a different name." + ) + raise ValueError(msg) + index_name = df.index.name + else: + index_name = "_index" + group.attrs["_index"] = check_key(index_name) + + # ._values is "the best" array representation. It's the true array backing the + # object, where `.values` is always a np.ndarray and .array is always a pandas + # array. + _writer.write_elem( + group, index_name, df.index._values, dataset_kwargs=dataset_kwargs + ) + for colname, series in df.items(): + # TODO: this should write the "true" representation of the series (i.e. the underlying array or ndarray depending) + _writer.write_elem( + group, colname, series._values, dataset_kwargs=dataset_kwargs + ) + + +@_REGISTRY.register_read(H5Group, IOSpec("dataframe", "0.2.0")) +@_REGISTRY.register_read(ZarrGroup, IOSpec("dataframe", "0.2.0")) +def read_dataframe(elem: GroupStorageType, *, _reader: Reader) -> pd.DataFrame: + columns = list(_read_attr(elem.attrs, "column-order")) + idx_key = _read_attr(elem.attrs, "_index") + df = pd.DataFrame( + {k: _reader.read_elem(elem[k]) for k in columns}, + index=_reader.read_elem(elem[idx_key]), + columns=columns if columns else None, + ) + if idx_key != "_index": + df.index.name = idx_key + return df + + +# TODO: Figure out what indices is allowed to be at each element +@_REGISTRY.register_read_partial(H5Group, IOSpec("dataframe", "0.2.0")) +@_REGISTRY.register_read_partial(ZarrGroup, IOSpec("dataframe", "0.2.0")) +def read_dataframe_partial( + elem, *, items=None, indices=(slice(None, None), slice(None, None)) +): + if items is not None: + columns = [ + col for col in _read_attr(elem.attrs, "column-order") if col in items + ] + else: + columns = list(_read_attr(elem.attrs, "column-order")) + idx_key = _read_attr(elem.attrs, "_index") + df = pd.DataFrame( + {k: read_elem_partial(elem[k], indices=indices[0]) for k in columns}, + index=read_elem_partial(elem[idx_key], indices=indices[0]), + columns=columns if columns else None, + ) + if idx_key != "_index": + df.index.name = idx_key + return df + + +# Backwards compat dataframe reading + + +@_REGISTRY.register_read(H5Group, IOSpec("dataframe", "0.1.0")) +@_REGISTRY.register_read(ZarrGroup, IOSpec("dataframe", "0.1.0")) +def read_dataframe_0_1_0(elem: GroupStorageType, *, _reader: Reader) -> pd.DataFrame: + columns = _read_attr(elem.attrs, "column-order") + idx_key = _read_attr(elem.attrs, "_index") + df = pd.DataFrame( + {k: read_series(elem[k]) for k in columns}, + index=read_series(elem[idx_key]), + columns=columns if len(columns) else None, + ) + if idx_key != "_index": + df.index.name = idx_key + return df + + +def read_series(dataset: h5py.Dataset) -> np.ndarray | pd.Categorical: + # For reading older dataframes + if "categories" in dataset.attrs: + if isinstance(dataset, ZarrArray): + import zarr + + parent_name = dataset.name.rstrip(dataset.basename).strip("/") + parent = zarr.open(dataset.store, mode="r")[parent_name] + else: + parent = dataset.parent + categories_dset = parent[_read_attr(dataset.attrs, "categories")] + categories = read_elem(categories_dset) + ordered = bool(_read_attr(categories_dset.attrs, "ordered", default=False)) + return pd.Categorical.from_codes( + read_elem(dataset), categories, ordered=ordered + ) + else: + return read_elem(dataset) + + +@_REGISTRY.register_read_partial(H5Group, IOSpec("dataframe", "0.1.0")) +@_REGISTRY.register_read_partial(ZarrGroup, IOSpec("dataframe", "0.1.0")) +def read_partial_dataframe_0_1_0( + elem, *, items=None, indices=(slice(None), slice(None)) +): + items = slice(None) if items is None else list(items) + return read_elem(elem)[items].iloc[indices[0]] + + +############### +# Categorical # +############### + + +@_REGISTRY.register_write(H5Group, pd.Categorical, IOSpec("categorical", "0.2.0")) +@_REGISTRY.register_write(ZarrGroup, pd.Categorical, IOSpec("categorical", "0.2.0")) +@suppress_autoshard_warning +def write_categorical( + f: GroupStorageType, + k: str, + v: pd.Categorical, + *, + _writer: Writer, + dataset_kwargs: Mapping[str, Any] = MappingProxyType({}), +): + g = f.require_group(k) + g.attrs["ordered"] = bool(v.ordered) + + _writer.write_elem(g, "codes", v.codes, dataset_kwargs=dataset_kwargs) + _writer.write_elem( + g, + "categories", + v.categories.to_numpy(), + dataset_kwargs=dataset_kwargs, + ) + + +@_REGISTRY.register_read(H5Group, IOSpec("categorical", "0.2.0")) +@_REGISTRY.register_read(ZarrGroup, IOSpec("categorical", "0.2.0")) +def read_categorical(elem: GroupStorageType, *, _reader: Reader) -> pd.Categorical: + return pd.Categorical.from_codes( + codes=_reader.read_elem(elem["codes"]), + categories=_reader.read_elem(elem["categories"]), + ordered=bool(_read_attr(elem.attrs, "ordered")), + ) + + +@_REGISTRY.register_read_partial(H5Group, IOSpec("categorical", "0.2.0")) +@_REGISTRY.register_read_partial(ZarrGroup, IOSpec("categorical", "0.2.0")) +def read_partial_categorical(elem, *, items=None, indices=(slice(None),)): + return pd.Categorical.from_codes( + codes=read_elem_partial(elem["codes"], indices=indices), + categories=read_elem(elem["categories"]), + ordered=bool(_read_attr(elem.attrs, "ordered")), + ) + + +#################### +# Pandas nullables # +#################### + + +@_REGISTRY.register_write( + H5Group, pd.arrays.IntegerArray, IOSpec("nullable-integer", "0.1.0") +) +@_REGISTRY.register_write( + ZarrGroup, pd.arrays.IntegerArray, IOSpec("nullable-integer", "0.1.0") +) +@_REGISTRY.register_write( + H5Group, pd.arrays.BooleanArray, IOSpec("nullable-boolean", "0.1.0") +) +@_REGISTRY.register_write( + ZarrGroup, pd.arrays.BooleanArray, IOSpec("nullable-boolean", "0.1.0") +) +def write_nullable( + f: GroupStorageType, + k: str, + v: pd.arrays.IntegerArray + | pd.arrays.BooleanArray + | pd.arrays.StringArray + | pd.arrays.ArrowStringArray, + *, + _writer: Writer, + dataset_kwargs: Mapping[str, Any] = MappingProxyType({}), +) -> None: + if ( + isinstance(v, pd.arrays.StringArray | pd.arrays.ArrowStringArray) + and not settings.allow_write_nullable_strings + ): + msg = ( + "`anndata.settings.allow_write_nullable_strings` is False, " + "because writing of `pd.arrays.{StringArray,ArrowStringArray}` is new " + "and not supported in anndata < 0.11, still use by many people. " + "Opt-in to writing these arrays by toggling the setting to True." + ) + raise RuntimeError(msg) + g = f.require_group(k) + values = ( + v.to_numpy(na_value="") + if isinstance(v, pd.arrays.StringArray | pd.arrays.ArrowStringArray) + else v.to_numpy(na_value=0, dtype=v.dtype.numpy_dtype) + ) + _writer.write_elem(g, "values", values, dataset_kwargs=dataset_kwargs) + _writer.write_elem(g, "mask", v.isna(), dataset_kwargs=dataset_kwargs) + + +for store_type, array_type in product([H5Group, ZarrGroup], PANDAS_STRING_ARRAY_TYPES): + _REGISTRY.register_write( + store_type, array_type, IOSpec("nullable-string-array", "0.1.0") + )(write_nullable) + + +class _BaseMaskedArray(Protocol): + def __call__( + self, values: NDArray[np.number], /, *, mask: NDArray[np.bool_] + ) -> pd.api.extensions.ExtensionArray: ... + + +def _read_nullable( + elem: GroupStorageType, *, _reader: Reader, array_type: _BaseMaskedArray +) -> pd.api.extensions.ExtensionArray: + return array_type( + _reader.read_elem(elem["values"]), + mask=_reader.read_elem(elem["mask"]), + ) + + +_REGISTRY.register_read(H5Group, IOSpec("nullable-integer", "0.1.0"))( + read_nullable_integer := partial(_read_nullable, array_type=pd.arrays.IntegerArray) +) +_REGISTRY.register_read(ZarrGroup, IOSpec("nullable-integer", "0.1.0"))( + read_nullable_integer +) + +_REGISTRY.register_read(H5Group, IOSpec("nullable-boolean", "0.1.0"))( + read_nullable_boolean := partial(_read_nullable, array_type=pd.arrays.BooleanArray) +) +_REGISTRY.register_read(ZarrGroup, IOSpec("nullable-boolean", "0.1.0"))( + read_nullable_boolean +) + + +@_REGISTRY.register_read(H5Group, IOSpec("nullable-string-array", "0.1.0")) +@_REGISTRY.register_read(ZarrGroup, IOSpec("nullable-string-array", "0.1.0")) +def _read_nullable_string( + elem: GroupStorageType, *, _reader: Reader +) -> pd.api.extensions.ExtensionArray: + values = _reader.read_elem(elem["values"]) + mask = _reader.read_elem(elem["mask"]) + dtype = pd.StringDtype() + + arr = pd.array( + values.astype(NULLABLE_NUMPY_STRING_TYPE), + dtype=dtype, + ) + arr[mask] = pd.NA + return arr + + +########### +# Scalars # +########### + + +@_REGISTRY.register_read(H5Array, IOSpec("numeric-scalar", "0.2.0")) +@_REGISTRY.register_read(ZarrArray, IOSpec("numeric-scalar", "0.2.0")) +def read_scalar(elem: ArrayStorageType, *, _reader: Reader) -> np.number: + # TODO: `item` ensures the return is in fact a scalar (needed after zarr v3 which now returns a 1 elem array) + # https://github.com/zarr-developers/zarr-python/issues/2713 + return elem[()].item() + + +def _remove_scalar_compression_args(dataset_kwargs: Mapping[str, Any]) -> dict: + # Can’t compress scalars, error is thrown + dataset_kwargs = dict(dataset_kwargs) + for arg in ( + "compression", + "compression_opts", + "chunks", + "shuffle", + "fletcher32", + "scaleoffset", + "compressor", + ): + dataset_kwargs.pop(arg, None) + return dataset_kwargs + + +def write_scalar_zarr( + f: ZarrGroup, + key: str, + value, + *, + _writer: Writer, + dataset_kwargs: Mapping[str, Any] = MappingProxyType({}), +): + # these args are ignored in v2: https://zarr.readthedocs.io/en/v2.18.4/api/hierarchy.html#zarr.hierarchy.Group.create_dataset + # and error out in v3 + dataset_kwargs = _remove_scalar_compression_args(dataset_kwargs) + if is_zarr_v2(): + return f.create_dataset(key, data=np.array(value), shape=(), **dataset_kwargs) + else: + from numcodecs import VLenUTF8 + from zarr.core.dtype import VariableLengthUTF8 + + match f.metadata.zarr_format, value: + case 2, str(): + filters, dtype, fill_value = [VLenUTF8()], VariableLengthUTF8(), "" + case 3, str(): + filters, dtype, fill_value = None, VariableLengthUTF8(), None + case _, _: + filters, dtype, fill_value = None, np.array(value).dtype, None + a = f.create_array( + key, + shape=(), + dtype=dtype, + filters=filters, + fill_value=fill_value, + **dataset_kwargs, + ) + a[...] = np.array(value) + + +def write_hdf5_scalar( + f: H5Group, + key: str, + value, + *, + _writer: Writer, + dataset_kwargs: Mapping[str, Any] = MappingProxyType({}), +): + # Can’t compress scalars, error is thrown + dataset_kwargs = _remove_scalar_compression_args(dataset_kwargs) + f.create_dataset(key, data=np.array(value), **dataset_kwargs) + + +for numeric_scalar_type in [ + *(bool, np.bool_), + *(np.uint8, np.uint16, np.uint32, np.uint64), + *(int, np.int8, np.int16, np.int32, np.int64), + *(float, *np.floating.__subclasses__()), + *np.complexfloating.__subclasses__(), +]: + _REGISTRY.register_write( + H5Group, numeric_scalar_type, IOSpec("numeric-scalar", "0.2.0") + )(write_hdf5_scalar) + _REGISTRY.register_write( + ZarrGroup, numeric_scalar_type, IOSpec("numeric-scalar", "0.2.0") + )(write_scalar_zarr) + +_REGISTRY.register_write(ZarrGroup, str, IOSpec("string", "0.2.0"))(write_scalar_zarr) +_REGISTRY.register_write(ZarrGroup, np.str_, IOSpec("string", "0.2.0"))( + write_scalar_zarr +) + + +@_REGISTRY.register_read(H5Array, IOSpec("string", "0.2.0")) +def read_hdf5_string(elem: H5Array, *, _reader: Reader) -> str: + return elem.asstr()[()] + + +@_REGISTRY.register_read(ZarrArray, IOSpec("string", "0.2.0")) +def read_zarr_string(elem: ZarrArray, *, _reader: Reader) -> str: + return str(elem[()]) + + +_REGISTRY.register_read(H5Array, IOSpec("bytes", "0.2.0"))(read_scalar) +_REGISTRY.register_read(ZarrArray, IOSpec("bytes", "0.2.0"))(read_scalar) + + +@_REGISTRY.register_write(H5Group, np.str_, IOSpec("string", "0.2.0")) +@_REGISTRY.register_write(H5Group, str, IOSpec("string", "0.2.0")) +def write_string( + f: H5Group, + k: str, + v: np.str_ | str, + *, + _writer: Writer, + dataset_kwargs: Mapping[str, Any], +): + dataset_kwargs = dict(dataset_kwargs) + dataset_kwargs.pop("compression", None) + dataset_kwargs.pop("compression_opts", None) + f.create_dataset( + k, data=np.array(v, dtype=h5py.string_dtype(encoding="utf-8")), **dataset_kwargs + ) + + +# @_REGISTRY.register_write(np.bytes_, IOSpec("bytes", "0.2.0")) +# @_REGISTRY.register_write(bytes, IOSpec("bytes", "0.2.0")) +# def write_string(f, k, v, dataset_kwargs): +# if "compression" in dataset_kwargs: +# dataset_kwargs = dict(dataset_kwargs) +# dataset_kwargs.pop("compression") +# f.create_dataset(k, data=np.array(v), **dataset_kwargs) diff --git a/.venv/lib/python3.11/site-packages/anndata/_io/specs/registry.py b/.venv/lib/python3.11/site-packages/anndata/_io/specs/registry.py new file mode 100644 index 0000000000000000000000000000000000000000..0968ad2a31ca0be87df1e5c1422d719ad05532f5 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/anndata/_io/specs/registry.py @@ -0,0 +1,534 @@ +from __future__ import annotations + +import inspect +import warnings +from collections.abc import Mapping +from dataclasses import dataclass +from functools import partial, singledispatch, wraps +from types import MappingProxyType +from typing import TYPE_CHECKING, Generic, TypeVar + +from anndata._io.utils import report_read_key_on_error, report_write_key_on_error +from anndata._settings import settings +from anndata._types import Read, ReadLazy, _ReadInternal, _ReadLazyInternal +from anndata.compat import DaskArray, ZarrGroup, _read_attr, is_zarr_v2 + +if TYPE_CHECKING: + from collections.abc import Callable, Generator, Iterable + from typing import Any + + from anndata._types import ( + GroupStorageType, + ReadCallback, + StorageType, + Write, + WriteCallback, + _WriteInternal, + ) + from anndata.experimental.backed._lazy_arrays import CategoricalArray, MaskedArray + from anndata.typing import RWAble + + from ..._core.xarray import Dataset2D + + S = TypeVar("S") + T = TypeVar("T") + W = TypeVar("W", bound=_WriteInternal) + LazyDataStructures = DaskArray | Dataset2D | CategoricalArray | MaskedArray + + +# TODO: This probably should be replaced by a hashable Mapping due to conversion b/w "_" and "-" +# TODO: Should filetype be included in the IOSpec if it changes the encoding? Or does the intent that these things be "the same" overrule that? +@dataclass(frozen=True) +class IOSpec: + encoding_type: str + encoding_version: str + + +# TODO: Should this subclass from LookupError? +class IORegistryError(Exception): + @classmethod + def _from_write_parts( + cls, dest_type: type, typ: type | tuple[type, str], modifiers: frozenset[str] + ) -> IORegistryError: + msg = f"No method registered for writing {typ} into {dest_type}" + if modifiers: + msg += f" with {modifiers}" + return cls(msg) + + @classmethod + def _from_read_parts( + cls, + method: str, + registry: Mapping, + src_typ: type[StorageType], + spec: IOSpec, + ) -> IORegistryError: + # TODO: Improve error message if type exists, but version does not + msg = ( + f"No {method} method registered for {spec} from {src_typ}. " + "You may need to update your installation of anndata." + ) + return cls(msg) + + +def write_spec(spec: IOSpec): + def decorator(func: W) -> W: + @wraps(func) + def wrapper(g: GroupStorageType, k: str, *args, **kwargs): + result = func(g, k, *args, **kwargs) + g[k].attrs.setdefault("encoding-type", spec.encoding_type) + g[k].attrs.setdefault("encoding-version", spec.encoding_version) + return result + + return wrapper + + return decorator + + +_R = TypeVar("_R", _ReadInternal, _ReadLazyInternal) +R = TypeVar("R", Read, ReadLazy) + + +class IORegistry(Generic[_R, R]): + def __init__(self): + self.read: dict[tuple[type, IOSpec, frozenset[str]], _R] = {} + self.read_partial: dict[tuple[type, IOSpec, frozenset[str]], Callable] = {} + self.write: dict[ + tuple[type, type | tuple[type, str], frozenset[str]], _WriteInternal + ] = {} + self.write_specs: dict[type | tuple[type, str] | tuple[type, type], IOSpec] = {} + + def register_write( + self, + dest_type: type[S], + src_type: type | tuple[type, str], + spec: IOSpec | Mapping[str, str], + modifiers: Iterable[str] = frozenset(), + ) -> Callable[[_WriteInternal[S, T]], _WriteInternal[S, T]]: + spec = proc_spec(spec) + modifiers = frozenset(modifiers) + + # Record specification for src_type + if src_type in self.write_specs and (spec != self.write_specs[src_type]): + # First check for consistency + current_spec = self.write_specs[src_type] + msg = ( + "Cannot overwrite IO specifications. Attempted to overwrite encoding " + f"for {src_type} from {current_spec} to {spec}" + ) + raise TypeError(msg) + else: + self.write_specs[src_type] = spec + + def _register(func: _WriteInternal[S, T]) -> _WriteInternal[S, T]: + self.write[(dest_type, src_type, modifiers)] = write_spec(spec)(func) + return func + + return _register + + def get_write( + self, + dest_type: type, + src_type: type | tuple[type, str], + modifiers: frozenset[str] = frozenset(), + *, + writer: Writer, + ) -> Write: + import h5py + + if dest_type is h5py.File: + dest_type = h5py.Group + if (dest_type, src_type, modifiers) not in self.write: + raise IORegistryError._from_write_parts(dest_type, src_type, modifiers) + internal = self.write[(dest_type, src_type, modifiers)] + return partial(internal, _writer=writer) + + def has_write( + self, + dest_type: type, + src_type: type | tuple[type, str], + modifiers: frozenset[str], + ) -> bool: + return (dest_type, src_type, modifiers) in self.write + + def register_read( + self, + src_type: type, + spec: IOSpec | Mapping[str, str], + modifiers: Iterable[str] = frozenset(), + ) -> Callable[[_R], _R]: + spec = proc_spec(spec) + modifiers = frozenset(modifiers) + + def _register(func): + self.read[(src_type, spec, modifiers)] = func + return func + + return _register + + def get_read( + self, + src_type: type, + spec: IOSpec, + modifiers: frozenset[str] = frozenset(), + *, + reader: Reader, + ) -> R: + if (src_type, spec, modifiers) not in self.read: + raise IORegistryError._from_read_parts("read", self.read, src_type, spec) # noqa: EM101 + internal = self.read[(src_type, spec, modifiers)] + return partial(internal, _reader=reader) + + def has_read( + self, src_type: type, spec: IOSpec, modifiers: frozenset[str] = frozenset() + ) -> bool: + return (src_type, spec, modifiers) in self.read + + def register_read_partial( + self, + src_type: type, + spec: IOSpec | Mapping[str, str], + modifiers: Iterable[str] = frozenset(), + ): + spec = proc_spec(spec) + modifiers = frozenset(modifiers) + + def _register(func): + self.read_partial[(src_type, spec, modifiers)] = func + return func + + return _register + + def get_partial_read( + self, src_type: type, spec: IOSpec, modifiers: frozenset[str] = frozenset() + ): + if (src_type, spec, modifiers) in self.read_partial: + return self.read_partial[(src_type, spec, modifiers)] + name = "read_partial" + raise IORegistryError._from_read_parts(name, self.read_partial, src_type, spec) + + def get_spec(self, elem: Any) -> IOSpec: + if isinstance(elem, DaskArray): + if (typ_meta := (DaskArray, type(elem._meta))) in self.write_specs: + return self.write_specs[typ_meta] + elif ( + hasattr(elem, "dtype") + and (typ_kind := (type(elem), elem.dtype.kind)) in self.write_specs + ): + return self.write_specs[typ_kind] + return self.write_specs[type(elem)] + + +_REGISTRY: IORegistry[_ReadInternal, Read] = IORegistry() +_LAZY_REGISTRY: IORegistry[_ReadLazyInternal, ReadLazy] = IORegistry() + + +@singledispatch +def proc_spec(spec) -> IOSpec: + msg = f"proc_spec not defined for type: {type(spec)}." + raise NotImplementedError(msg) + + +@proc_spec.register(IOSpec) +def proc_spec_spec(spec: IOSpec) -> IOSpec: + return spec + + +@proc_spec.register(Mapping) +def proc_spec_mapping(spec: Mapping[str, str]) -> IOSpec: + return IOSpec(**{k.replace("-", "_"): v for k, v in spec.items()}) + + +def get_spec( + elem: StorageType, +) -> IOSpec: + return proc_spec({ + k: _read_attr(elem.attrs, k, "") for k in ["encoding-type", "encoding-version"] + }) + + +def _iter_patterns( + elem, +) -> Generator[tuple[type, type | str] | tuple[type, type, str], None, None]: + """Iterates over possible patterns for an element in order of precedence.""" + from anndata.compat import DaskArray + + t = type(elem) + + if isinstance(elem, DaskArray): + yield (t, type(elem._meta), elem.dtype.kind) + yield (t, type(elem._meta)) + if hasattr(elem, "dtype"): + yield (t, elem.dtype.kind) + yield t + + +class Reader: + def __init__( + self, registry: IORegistry, callback: ReadCallback | None = None + ) -> None: + self.registry = registry + self.callback = callback + + @report_read_key_on_error + def read_elem( + self, + elem: StorageType, + modifiers: frozenset[str] = frozenset(), + ) -> RWAble: + """Read an element from a store. See exported function for more details.""" + + iospec = get_spec(elem) + read_func: Read = self.registry.get_read( + type(elem), iospec, modifiers, reader=self + ) + if self.callback is None: + return read_func(elem) + return self.callback(read_func, elem.name, elem, iospec=iospec) + + +class LazyReader(Reader): + @report_read_key_on_error + def read_elem( + self, + elem: StorageType, + modifiers: frozenset[str] = frozenset(), + chunks: tuple[int, ...] | None = None, + **kwargs, + ) -> LazyDataStructures: + """Read a dask element from a store. See exported function for more details.""" + + iospec = get_spec(elem) + read_func: ReadLazy = self.registry.get_read( + type(elem), iospec, modifiers, reader=self + ) + if self.callback is not None: + msg = "Dask reading does not use a callback. Ignoring callback." + warnings.warn(msg, stacklevel=2) + read_params = inspect.signature(read_func).parameters + for kwarg in kwargs: + if kwarg not in read_params: + msg = ( + f"Keyword argument {kwarg} passed to read_elem_lazy are not supported by the " + "registered read function." + ) + raise ValueError(msg) + if "chunks" in read_params: + kwargs["chunks"] = chunks + return read_func(elem, **kwargs) + + +class Writer: + def __init__(self, registry: IORegistry, callback: WriteCallback | None = None): + self.registry = registry + self.callback = callback + + def find_write_func( + self, dest_type: type, elem: Any, modifiers: frozenset[str] + ) -> Write: + for pattern in _iter_patterns(elem): + if self.registry.has_write(dest_type, pattern, modifiers): + return self.registry.get_write( + dest_type, pattern, modifiers, writer=self + ) + # Raises IORegistryError + return self.registry.get_write(dest_type, type(elem), modifiers, writer=self) + + @report_write_key_on_error + def write_elem( + self, + store: GroupStorageType, + k: str, + elem: RWAble, + *, + dataset_kwargs: Mapping[str, Any] = MappingProxyType({}), + modifiers: frozenset[str] = frozenset(), + ): + from pathlib import PurePosixPath + + import h5py + + from anndata._io.zarr import is_group_consolidated + + # we allow stores to have a prefix like /uns which are then written to with keys like /uns/foo + is_zarr_group = isinstance(store, ZarrGroup) + if "/" in k.rsplit(store.name, maxsplit=1)[-1][1:]: + if is_zarr_group or settings.disallow_forward_slash_in_h5ad: + msg = f"Forward slashes are not allowed in keys in {type(store)}" + raise ValueError(msg) + else: + msg = "Forward slashes will be disallowed in h5 stores in the next minor release" + warnings.warn(msg, FutureWarning, stacklevel=2) + + if isinstance(store, h5py.File): + store = store["/"] + + dest_type = type(store) + + # Normalize k to absolute path + if (is_zarr_group and is_zarr_v2()) or ( + isinstance(store, h5py.Group) and not PurePosixPath(k).is_absolute() + ): + k = str(PurePosixPath(store.name) / k) + is_consolidated = is_group_consolidated(store) if is_zarr_group else False + if is_consolidated: + msg = "Cannot overwrite/edit a store with consolidated metadata" + raise ValueError(msg) + if k == "/": + if isinstance(store, ZarrGroup) and not is_zarr_v2(): + from zarr.core.sync import sync + + sync(store.store.clear()) + else: + store.clear() + elif k in store: + del store[k] + + write_func = self.find_write_func(dest_type, elem, modifiers) + + if self.callback is None: + return write_func(store, k, elem, dataset_kwargs=dataset_kwargs) + return self.callback( + write_func, + store, + k, + elem, + dataset_kwargs=dataset_kwargs, + iospec=self.registry.get_spec(elem), + ) + + +def read_elem(elem: StorageType) -> RWAble: + """ + Read an element from a store. + + Assumes that the element is encoded using the anndata encoding. This function will + determine the encoded type using the encoding metadata stored in elem's attributes. + + Params + ------ + elem + The stored element. + """ + return Reader(_REGISTRY).read_elem(elem) + + +def read_elem_lazy( + elem: StorageType, chunks: tuple[int, ...] | None = None, **kwargs +) -> LazyDataStructures: + """ + Read an element from a store lazily. + + Assumes that the element is encoded using the anndata encoding. This function will + determine the encoded type using the encoding metadata stored in elem's attributes. + + + Parameters + ---------- + elem + The stored element. + chunks + length `n`, the same `n` as the size of the underlying array. + Note that the minor axis dimension must match the shape for sparse. + Defaults to `(1000, adata.shape[1])` for CSR sparse, + `(adata.shape[0], 1000)` for CSC sparse, + and the on-disk chunking otherwise for dense. + Can use `-1` or `None` to indicate use of the size of the corresponding dimension. + + Returns + ------- + A "lazy" elem + + Examples + -------- + + Setting up our example: + + >>> from scanpy.datasets import pbmc3k + >>> import tempfile + >>> import anndata as ad + >>> import zarr + + >>> tmp_path = tempfile.gettempdir() + >>> zarr_path = tmp_path + "/adata.zarr" + + >>> adata = pbmc3k() + >>> adata.layers["dense"] = adata.X.toarray() + >>> adata.write_zarr(zarr_path) + + Reading a sparse matrix from a zarr store lazily, with custom chunk size and default: + + >>> g = zarr.open(zarr_path) + >>> adata.X = ad.experimental.read_elem_lazy(g["X"]) + >>> adata.X + dask.array + >>> adata.X = ad.experimental.read_elem_lazy(g["X"], chunks=(500, adata.shape[1])) + >>> adata.X + dask.array + + Reading a dense matrix from a zarr store lazily: + + >>> adata.layers["dense"] = ad.experimental.read_elem_lazy(g["layers/dense"]) + >>> adata.layers["dense"] + dask.array + + Making a new anndata object from on-disk, with custom chunks: + + >>> adata = ad.AnnData( + ... obs=ad.io.read_elem(g["obs"]), + ... var=ad.io.read_elem(g["var"]), + ... uns=ad.io.read_elem(g["uns"]), + ... obsm=ad.io.read_elem(g["obsm"]), + ... varm=ad.io.read_elem(g["varm"]), + ... ) + >>> adata.X = ad.experimental.read_elem_lazy(g["X"], chunks=(500, adata.shape[1])) + >>> adata.layers["dense"] = ad.experimental.read_elem_lazy(g["layers/dense"]) + + We also support using -1 and None as a chunk size to signify the reading the whole axis: + + >>> adata.X = ad.experimental.read_elem_lazy(g["X"], chunks=(500, -1)) + >>> adata.X = ad.experimental.read_elem_lazy(g["X"], chunks=(500, None)) + """ + return LazyReader(_LAZY_REGISTRY).read_elem(elem, chunks=chunks, **kwargs) + + +def write_elem( + store: GroupStorageType, + k: str, + elem: RWAble, + *, + dataset_kwargs: Mapping[str, Any] = MappingProxyType({}), +) -> None: + """ + Write an element to a storage group using anndata encoding. + + Params + ------ + store + The group to write to. + k + The key to write to in the group. Note that absolute paths will be written + from the root. + elem + The element to write. Typically an in-memory object, e.g. an AnnData, pandas + dataframe, scipy sparse matrix, etc. + dataset_kwargs + Keyword arguments to pass to the stores dataset creation function. + E.g. for zarr this would be `chunks`, `compressor`. + """ + Writer(_REGISTRY).write_elem(store, k, elem, dataset_kwargs=dataset_kwargs) + + +# TODO: If all items would be read, just call normal read method +def read_elem_partial( + elem, + *, + items=None, + indices=(slice(None), slice(None)), + modifiers: frozenset[str] = frozenset(), +): + """Read part of an element from an on disk store.""" + read_partial = _REGISTRY.get_partial_read( + type(elem), get_spec(elem), frozenset(modifiers) + ) + return read_partial(elem, items=items, indices=indices) diff --git a/.venv/lib/python3.11/site-packages/anndata/_io/utils.py b/.venv/lib/python3.11/site-packages/anndata/_io/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..100792b7bf409be6b669307efc6ecea6247a260d --- /dev/null +++ b/.venv/lib/python3.11/site-packages/anndata/_io/utils.py @@ -0,0 +1,351 @@ +from __future__ import annotations + +from collections.abc import Callable +from functools import WRAPPER_ASSIGNMENTS, cache, wraps +from itertools import pairwise +from typing import TYPE_CHECKING, Literal, cast +from warnings import warn + +import numpy as np +import pandas as pd + +from .._core.sparse_dataset import BaseCompressedSparseDataset + +if TYPE_CHECKING: + from collections.abc import Callable, Mapping + from typing import Any, Literal + + from pandas.core.dtypes.dtypes import BaseMaskedDtype + + from .._types import StorageType, _WriteInternal + from ..compat import H5Group, ZarrGroup + from ..typing import RWAble + from .specs.registry import Writer + + Storage = StorageType | BaseCompressedSparseDataset + + +# ------------------------------------------------------------------------------- +# Type conversion +# ------------------------------------------------------------------------------- + + +# Could be numba’d if it returned tuples instead of slices +def idx_chunks_along_axis(shape: tuple, axis: int, chunk_size: int): + """\ + Gives indexer tuples chunked along an axis. + + Params + ------ + shape + Shape of array to be chunked + axis + Axis to chunk along + chunk_size + Size of chunk along axis + + Returns + ------- + An iterator of tuples for indexing into an array of passed shape. + """ + total = shape[axis] + cur = 0 + mutable_idx = [slice(None) for i in range(len(shape))] + while cur + chunk_size < total: + mutable_idx[axis] = slice(cur, cur + chunk_size) + yield tuple(mutable_idx) + cur += chunk_size + mutable_idx[axis] = slice(cur, None) + yield tuple(mutable_idx) + + +def is_float(string): + """\ + Check whether string is float. + + See also + -------- + http://stackoverflow.com/questions/736043/checking-if-a-string-can-be-converted-to-float-in-python + """ + try: + float(string) + return True + except ValueError: + return False + + +def is_int(string): + """Check whether string is integer.""" + try: + int(string) + return True + except ValueError: + return False + + +def convert_bool(string): + """Check whether string is boolean.""" + if string == "True": + return True, True + elif string == "False": + return True, False + else: + return False, False + + +def convert_string(string): + """Convert string to int, float or bool.""" + if is_int(string): + return int(string) + elif is_float(string): + return float(string) + elif convert_bool(string)[0]: + return convert_bool(string)[1] + elif string == "None": + return None + else: + return string + + +def check_key(key): + """Checks that passed value is a valid h5py key. + + Should convert it if there is an obvious conversion path, error otherwise. + """ + typ = type(key) + if issubclass(typ, str): + return str(key) + # TODO: Should I try to decode bytes? It's what h5py would do, + # but it will be read out as a str. + # elif issubclass(typ, bytes): + # return key + else: + msg = f"{key} of type {typ} is an invalid key. Should be str." + raise TypeError(msg) + + +@cache +def pandas_nullable_dtype(dtype: np.dtype) -> BaseMaskedDtype: + """Infer nullable dtype from numpy dtype. + + There is no public pandas API for this, so this is the cleanest way. + See + """ + try: + from pandas.core.dtypes.dtypes import BaseMaskedDtype + except ImportError: + pass + else: + return BaseMaskedDtype.from_numpy_dtype(dtype) + + match dtype.kind: + case "b": + array_type = pd.arrays.BooleanArray + case "i" | "u": + array_type = pd.arrays.IntegerArray + case _: + raise NotImplementedError + return array_type(np.ones(1, dtype), np.ones(1, bool)).dtype + + +# ------------------------------------------------------------------------------- +# Generic functions +# ------------------------------------------------------------------------------- + + +def read_attribute(*args, **kwargs): + from .specs import read_elem + + msg = "This internal function has been deprecated, please use read_elem instead" + warn(msg, FutureWarning, stacklevel=2) + return read_elem(*args, **kwargs) + + +def write_attribute(*args, **kwargs): + from .specs import write_elem + + msg = "This internal function has been deprecated, please use write_elem instead" + warn(msg, FutureWarning, stacklevel=2) + return write_elem(*args, **kwargs) + + +# ------------------------------------------------------------------------------- +# Errors handling +# ------------------------------------------------------------------------------- +# TODO: Is there a consistent way to do this which just modifies the previously +# thrown error? Could do a warning? + + +class AnnDataReadError(OSError): + """Error caused while trying to read in AnnData.""" + + +def _get_display_path(store: Storage) -> str: + """Return an absolute path of an element (always starts with “/”).""" + if isinstance(store, BaseCompressedSparseDataset): + store = store.group + path = store.name or "??" # can be None + return f"/{path.removeprefix('/')}" + + +def add_key_note( + e: BaseException, store: Storage, path: str, key: str, op: Literal["read", "writ"] +) -> None: + if any( + f"Error raised while {op}ing key" in note + for note in getattr(e, "__notes__", []) + ): + return + + dir = "to" if op == "writ" else "from" + msg = f"Error raised while {op}ing key {key!r} of {type(store)} {dir} {path}" + e.add_note(msg) + + +def report_read_key_on_error(func): + """\ + A decorator for hdf5/zarr element reading which makes keys involved in errors get reported. + + Example + ------- + >>> import zarr + >>> import numpy as np + >>> @report_read_key_on_error + ... def read_arr(group): + ... raise NotImplementedError() + >>> z = zarr.open("tmp.zarr", mode="w") + >>> z["X"] = np.array([1, 2, 3]) + >>> read_arr(z["X"]) # doctest: +SKIP + """ + + @wraps(func) + def func_wrapper(*args, **kwargs): + from anndata._io.specs import Reader + + # Figure out signature (method vs function) by going through args + for arg in args: + if not isinstance(arg, Reader): + store = cast("Storage", arg) + break + else: + msg = "No element found in args." + raise ValueError(msg) + try: + return func(*args, **kwargs) + except Exception as e: + path, key = _get_display_path(store).rsplit("/", 1) + add_key_note(e, store, path or "/", key, "read") + raise + + return func_wrapper + + +def report_write_key_on_error(func): + """\ + A decorator for hdf5/zarr element writing which makes keys involved in errors get reported. + + Example + ------- + >>> import zarr + >>> @report_write_key_on_error + ... def write_arr(group, key, val): + ... raise NotImplementedError() + >>> z = zarr.open("tmp.zarr", mode="w") + >>> X = [1, 2, 3] + >>> write_arr(z, "X", X) # doctest: +SKIP + """ + + @wraps(func) + def func_wrapper(*args, **kwargs): + from anndata._io.specs import Writer + + # Figure out signature (method vs function) by going through args + for arg, _key in pairwise(args): + key = _key + if not isinstance(arg, Writer): + store = cast("Storage", arg) + break + else: + msg = "No element found in args." + raise ValueError(msg) + try: + return func(*args, **kwargs) + except Exception as e: + path = _get_display_path(store) + add_key_note(e, store, path, key, "writ") + raise + + return func_wrapper + + +# ------------------------------------------------------------------------------- +# Common h5ad/zarr stuff +# ------------------------------------------------------------------------------- + + +def _read_legacy_raw( + f: ZarrGroup | H5Group, + modern_raw, # TODO: type + read_df: Callable, + read_attr: Callable, + *, + attrs=("X", "var", "varm"), +) -> dict: + """\ + Backwards compat for reading legacy raw. + Makes sure that no modern raw group coexists with legacy raw.* groups. + """ + if modern_raw: + if any(k.startswith("raw.") for k in f): + what = f"File {f.filename}" if hasattr(f, "filename") else "Store" + msg = f"{what} has both legacy and current raw formats." + raise ValueError(msg) + return modern_raw + + raw = {} + if "X" in attrs and "raw.X" in f: + raw["X"] = read_attr(f["raw.X"]) + if "var" in attrs and "raw.var" in f: + raw["var"] = read_df(f["raw.var"]) # Backwards compat + if "varm" in attrs and "raw.varm" in f: + raw["varm"] = read_attr(f["raw.varm"]) + return raw + + +def zero_dim_array_as_scalar(func: _WriteInternal) -> _WriteInternal: + """\ + A decorator for write_elem implementations of arrays where zero-dimensional arrays need special handling. + """ + + @wraps(func, assigned=(*WRAPPER_ASSIGNMENTS, "__defaults__", "__kwdefaults__")) + def func_wrapper( + f: StorageType, + k: str, + elem: RWAble, + *, + _writer: Writer, + dataset_kwargs: Mapping[str, Any], + ): + if elem.shape == (): + _writer.write_elem(f, k, elem[()], dataset_kwargs=dataset_kwargs) + else: + func(f, k, elem, _writer=_writer, dataset_kwargs=dataset_kwargs) + + return func_wrapper + + +def no_write_dataset_2d(write): + def raise_error_if_dataset_2d_present(store, adata, *args, **kwargs): + from anndata.experimental.backed._compat import has_dataset_2d + + if has_dataset_2d(adata): + msg = ( + "Writing AnnData objects with a Dataset2D not supported yet. " + "Please use `ds.to_memory` to bring the dataset into memory. " + "Note that if you have generated this object by concatenating several `AnnData` objects" + "the original types may be lost." + ) + raise NotImplementedError(msg) + return write(store, adata, *args, **kwargs) + + return raise_error_if_dataset_2d_present diff --git a/.venv/lib/python3.11/site-packages/anndata/_io/write.py b/.venv/lib/python3.11/site-packages/anndata/_io/write.py new file mode 100644 index 0000000000000000000000000000000000000000..a4e07e64bf1aeff2817bd737cdb7a5b446b5c0d7 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/anndata/_io/write.py @@ -0,0 +1,151 @@ +from __future__ import annotations + +import math +import warnings +from os import fspath +from pathlib import Path +from typing import TYPE_CHECKING + +import numpy as np +import pandas as pd +from scipy.sparse import issparse + +from anndata._io.utils import no_write_dataset_2d + +from .._warnings import WriteWarning +from ..compat import old_positionals +from ..logging import get_logger + +if TYPE_CHECKING: + from os import PathLike + + from .. import AnnData + +logger = get_logger(__name__) + + +@no_write_dataset_2d +@old_positionals("skip_data", "sep") +def write_csvs( + dirname: PathLike[str] | str, + adata: AnnData, + *, + skip_data: bool = True, + sep: str = ",", +): + """See :meth:`~anndata.AnnData.write_csvs`.""" + dirname = Path(dirname) + if dirname.suffix == ".csv": + dirname = dirname.with_suffix("") + logger.info(f"writing .csv files to {dirname}") + if not dirname.is_dir(): + dirname.mkdir(parents=True, exist_ok=True) + dir_uns = dirname / "uns" + if not dir_uns.is_dir(): + dir_uns.mkdir(parents=True, exist_ok=True) + d = dict( + obs=adata._obs, + var=adata._var, + obsm=adata.obsm.to_df(), + varm=adata.varm.to_df(), + ) + if not skip_data: + d["X"] = pd.DataFrame(adata.X.toarray() if issparse(adata.X) else adata.X) + d_write = {**d, **adata._uns} + not_yet_raised_sparse_warning = True + for key, value in d_write.items(): + if issparse(value): + if not_yet_raised_sparse_warning: + msg = "Omitting to write sparse annotation." + warnings.warn(msg, WriteWarning, stacklevel=2) + not_yet_raised_sparse_warning = False + continue + filename = dirname + if key not in {"X", "var", "obs", "obsm", "varm"}: + filename = dir_uns + filename /= f"{key}.csv" + df = value + if not isinstance(value, pd.DataFrame): + value = np.array(value) + if np.ndim(value) == 0: + value = value[None] + try: + df = pd.DataFrame(value) + except Exception as e: # noqa: BLE001 + msg = f"Omitting to write {key!r} of type {type(e)}." + warnings.warn(msg, WriteWarning, stacklevel=2) + continue + df.to_csv( + filename, + sep=sep, + header=key in {"obs", "var", "obsm", "varm"}, + index=key in {"obs", "var"}, + ) + + +@no_write_dataset_2d +@old_positionals("write_obsm_varm") +def write_loom( + filename: PathLike[str] | str, adata: AnnData, *, write_obsm_varm: bool = False +) -> None: + """See :meth:`~anndata.AnnData.write_loom`.""" + filename = Path(filename) + row_attrs = {k: np.array(v) for k, v in adata.var.to_dict("list").items()} + row_names = adata.var_names + row_dim = row_names.name if row_names.name is not None else "var_names" + row_attrs[row_dim] = row_names.values + col_attrs = {k: np.array(v) for k, v in adata.obs.to_dict("list").items()} + col_names = adata.obs_names + col_dim = col_names.name if col_names.name is not None else "obs_names" + col_attrs[col_dim] = col_names.values + + if adata.X is None: + msg = "loompy does not accept empty matrices as data" + raise ValueError(msg) + + if write_obsm_varm: + col_attrs.update(adata.obsm) + row_attrs.update(adata.varm) + elif len(adata.obsm.keys()) > 0 or len(adata.varm.keys()) > 0: + logger.warning( + f"The loom file will lack these fields:\n" + f"{adata.obsm.keys() | adata.varm.keys()}\n" + f"Use write_obsm_varm=True to export multi-dimensional annotations" + ) + + layers = {"": adata.X.T} + for key, layer in adata.layers.items(): + layers[key] = layer.T + + from loompy import create + + if filename.exists(): + filename.unlink() + create(fspath(filename), layers, row_attrs=row_attrs, col_attrs=col_attrs) + + +def _get_chunk_indices(za): + # TODO: does zarr provide code for this? + """\ + Return all the indices (coordinates) for the chunks in a zarr array, + even empty ones. + """ + return [ + (i, j) + for i in range(math.ceil(float(za.shape[0]) / za.chunks[0])) + for j in range(math.ceil(float(za.shape[1]) / za.chunks[1])) + ] + + +def _write_in_zarr_chunks(za, key, value): + if key != "X": + za[:] = value # don’t chunk metadata + else: + for ci in _get_chunk_indices(za): + s0, e0 = za.chunks[0] * ci[0], za.chunks[0] * (ci[0] + 1) + s1, e1 = za.chunks[1] * ci[1], za.chunks[1] * (ci[1] + 1) + print(ci, s0, e1, s1, e1) + if issparse(value): + za[s0:e0, s1:e1] = value[s0:e0, s1:e1].todense() + else: + za[s0:e0, s1:e1] = value[s0:e0, s1:e1] diff --git a/.venv/lib/python3.11/site-packages/anndata/_io/zarr.py b/.venv/lib/python3.11/site-packages/anndata/_io/zarr.py new file mode 100644 index 0000000000000000000000000000000000000000..3c36593e4bede7c27b6bc43dc5d96b0d6e96d1a5 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/anndata/_io/zarr.py @@ -0,0 +1,170 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, TypeVar +from warnings import warn + +import numpy as np +import pandas as pd +import zarr +from scipy import sparse + +from .._core.anndata import AnnData +from .._settings import settings +from .._warnings import OldFormatWarning +from ..compat import _clean_uns, _from_fixed_length_strings, is_zarr_v2 +from ..experimental import read_dispatched, write_dispatched +from .specs import read_elem +from .utils import _read_legacy_raw, no_write_dataset_2d, report_read_key_on_error + +if TYPE_CHECKING: + from collections.abc import MutableMapping + from os import PathLike + + from zarr.core.common import AccessModeLiteral + from zarr.storage import StoreLike + +T = TypeVar("T") + + +@no_write_dataset_2d +def write_zarr( + store: StoreLike, + adata: AnnData, + *, + chunks: tuple[int, ...] | None = None, + convert_strings_to_categoricals: bool = True, + **ds_kwargs, +) -> None: + """See :meth:`~anndata.AnnData.write_zarr`.""" + if convert_strings_to_categoricals: + adata.strings_to_categoricals() + if adata.raw is not None: + adata.strings_to_categoricals(adata.raw.var) + # TODO: Use spec writing system for this + f = open_write_group(store) + f.attrs.setdefault("encoding-type", "anndata") + f.attrs.setdefault("encoding-version", "0.1.0") + + def callback( + write_func, store, elem_name: str, elem, *, dataset_kwargs, iospec + ) -> None: + if ( + chunks is not None + and not isinstance(elem, sparse.spmatrix) + and elem_name.lstrip("/") == "X" + ): + dataset_kwargs = dict(dataset_kwargs, chunks=chunks) + write_func(store, elem_name, elem, dataset_kwargs=dataset_kwargs) + + write_dispatched(f, "/", adata, callback=callback, dataset_kwargs=ds_kwargs) + if is_zarr_v2(): + zarr.convenience.consolidate_metadata(f.store) + else: + zarr.consolidate_metadata(f.store) + + +def read_zarr(store: PathLike[str] | str | MutableMapping | zarr.Group) -> AnnData: + """\ + Read from a hierarchical Zarr array store. + + Parameters + ---------- + store + The filename, a :class:`~typing.MutableMapping`, or a Zarr storage class. + """ + f = store if isinstance(store, zarr.Group) else zarr.open(store, mode="r") + + # Read with handling for backwards compat + def callback(func, elem_name: str, elem, iospec): + if iospec.encoding_type == "anndata" or elem_name.endswith("/"): + return AnnData(**{ + k: read_dispatched(v, callback) + for k, v in dict(elem).items() + if not k.startswith("raw.") + }) + elif elem_name.startswith("/raw."): + return None + elif elem_name in {"/obs", "/var"}: + return read_dataframe(elem) + elif elem_name == "/raw": + # Backwards compat + return _read_legacy_raw(f, func(elem), read_dataframe, func) + return func(elem) + + adata = read_dispatched(f, callback=callback) + + # Backwards compat (should figure out which version) + if "raw.X" in f: + raw = AnnData(**_read_legacy_raw(f, adata.raw, read_dataframe, read_elem)) + raw.obs_names = adata.obs_names + adata.raw = raw + + # Backwards compat for <0.7 + if isinstance(f["obs"], zarr.Array): + _clean_uns(adata) + + return adata + + +@report_read_key_on_error +def read_dataset(dataset: zarr.Array): + """Legacy method for reading datasets without encoding_type.""" + value = dataset[...] + if not hasattr(value, "dtype"): + return value + elif isinstance(value.dtype, str): + pass + elif issubclass(value.dtype.type, np.bytes_): + value = value.astype(str).astype(object) # bytestring -> unicode -> str + elif len(value.dtype.descr) > 1: # Compound dtype + # For backwards compat, now strings are written as variable length + value = _from_fixed_length_strings(value) + if value.shape == () and not np.isscalar(value): + value = value[()] + return value + + +@report_read_key_on_error +def read_dataframe_legacy(dataset: zarr.Array) -> pd.DataFrame: + """Reads old format of dataframes""" + # NOTE: Likely that categoricals need to be removed from uns + msg = ( + f"'{dataset.name}' was written with a very old version of AnnData. " + "Consider rewriting it." + ) + warn(msg, OldFormatWarning, stacklevel=3) + df = pd.DataFrame(_from_fixed_length_strings(dataset[()])) + df.set_index(df.columns[0], inplace=True) + return df + + +@report_read_key_on_error +def read_dataframe(group: zarr.Group | zarr.Array) -> pd.DataFrame: + # Fast paths + if isinstance(group, zarr.Array): + return read_dataframe_legacy(group) + else: + return read_elem(group) + + +def open_write_group( + store: StoreLike, *, mode: AccessModeLiteral = "w", **kwargs +) -> zarr.Group: + if "zarr_format" not in kwargs: + if settings.zarr_write_format == 2 or is_zarr_v2(): + msg = "Writing zarr v2 data will no longer be the default in the next minor release. v3 data will be written by default. If you are explicitly setting this configuration, consider migrating to the zarr v3 file format." + warn(msg, UserWarning, stacklevel=2) + if not is_zarr_v2(): + kwargs["zarr_format"] = settings.zarr_write_format + return zarr.open_group(store, mode=mode, **kwargs) + + +def is_group_consolidated(group: zarr.Group) -> bool: + if not isinstance(group, zarr.Group): + msg = f"Expected zarr.Group, got {type(group)}" + raise TypeError(msg) + if is_zarr_v2(): + from zarr.storage import ConsolidatedMetadataStore + + return isinstance(group.store, ConsolidatedMetadataStore) + return group.metadata.consolidated_metadata is not None diff --git a/.venv/lib/python3.11/site-packages/anndata/_settings.py b/.venv/lib/python3.11/site-packages/anndata/_settings.py new file mode 100644 index 0000000000000000000000000000000000000000..1940c7c1f8264bcba1e4383c0ad42da80262b91a --- /dev/null +++ b/.venv/lib/python3.11/site-packages/anndata/_settings.py @@ -0,0 +1,533 @@ +from __future__ import annotations + +import inspect +import os +import textwrap +import warnings +from collections.abc import Iterable +from contextlib import contextmanager +from dataclasses import dataclass, field, fields +from enum import Enum +from functools import partial +from inspect import Parameter, signature +from types import GenericAlias, NoneType +from typing import TYPE_CHECKING, Generic, NamedTuple, TypeVar, cast + +from .compat import old_positionals + +if TYPE_CHECKING: + from collections.abc import Callable, Sequence + from typing import Any, Self, TypeGuard + +T = TypeVar("T") + + +class DeprecatedOption(NamedTuple): + option: str + message: str | None + removal_version: str | None + + +def _is_plain_type(obj: object) -> TypeGuard[type]: + return isinstance(obj, type) and not isinstance(obj, GenericAlias) + + +def describe(self: RegisteredOption, *, as_rst: bool = False) -> str: + type_str = self.type.__name__ if _is_plain_type(self.type) else str(self.type) + if as_rst: + default_str = repr(self.default_value).replace("\\", "\\\\") + doc = f"""\ + .. attribute:: settings.{self.option} + :type: {type_str} + :value: {default_str} + + {self.description} + """ + else: + doc = f"""\ + {self.option}: `{type_str}` + {self.description} (default: `{self.default_value!r}`). + """ + return textwrap.dedent(doc) + + +class RegisteredOption(NamedTuple, Generic[T]): + option: str + default_value: T + description: str + validate: Callable[[T, SettingsManager], None] + type: object + + describe = describe + + +def check_and_get_environ_var( + key: str, + default_value: str, + allowed_values: Sequence[str] | None = None, + cast: Callable[[Any], T] | type[Enum] = lambda x: x, +) -> T: + """Get the environment variable and return it is a (potentially) non-string, usable value. + + Parameters + ---------- + key + The environment variable name. + default_value + The default value for `os.environ.get`. + allowed_values + Allowable string values., by default None + cast + Casting from the string to a (potentially different) python object, by default lambdax:x + + Returns + ------- + The casted value. + """ + environ_value_or_default_value = os.environ.get(key, default_value) + if ( + allowed_values is not None + and environ_value_or_default_value not in allowed_values + ): + msg = ( + f"Value {environ_value_or_default_value!r} is not in allowed {allowed_values} for environment variable {key}. " + f"Default {default_value} will be used." + ) + warnings.warn(msg, UserWarning, stacklevel=3) + environ_value_or_default_value = default_value + return ( + cast(environ_value_or_default_value) + if not isinstance(cast, type(Enum)) + else cast[environ_value_or_default_value] + ) + + +def check_and_get_bool(option: str, default_value: bool) -> bool: # noqa: FBT001 + return check_and_get_environ_var( + f"ANNDATA_{option.upper()}", + str(int(default_value)), + ["0", "1"], + lambda x: bool(int(x)), + ) + + +def check_and_get_bool_or_none(option: str, default_value: bool | None) -> bool | None: # noqa: FBT001 + return check_and_get_environ_var( + f"ANNDATA_{option.upper()}", + "" if default_value is None else str(int(default_value)), + ["0", "1", ""], + lambda x: None if x == "" else bool(int(x)), + ) + + +def check_and_get_int(option: str, default_value: int) -> int: + return check_and_get_environ_var( + f"ANNDATA_{option.upper()}", + str(int(default_value)), + None, + lambda x: int(x), + ) + + +_docstring = """ +This manager allows users to customize settings for the anndata package. +Settings here will generally be for advanced use-cases and should be used with caution. + +The following options are available: + +{options_description} + +For setting an option please use :func:`~anndata.settings.override` (local) or set the above attributes directly (global) i.e., `anndata.settings.my_setting = foo`. +For assignment by environment variable, use the variable name in all caps with `ANNDATA_` as the prefix before import of :mod:`anndata`. +For boolean environment variable setting, use 1 for `True` and 0 for `False`. +""" + + +@dataclass +class SettingsManager: + _registered_options: dict[str, RegisteredOption] = field(default_factory=dict) + _deprecated_options: dict[str, DeprecatedOption] = field(default_factory=dict) + _config: dict[str, object] = field(default_factory=dict) + __doc_tmpl__: str = _docstring + + def describe( + self, + option: str | Iterable[str] | None = None, + *, + should_print_description: bool = True, + as_rst: bool = False, + ) -> str: + """Print and/or return a (string) description of the option(s). + + Parameters + ---------- + option + Option(s) to be described, by default None (i.e., do all option) + should_print_description + Whether or not to print the description in addition to returning it. + + Returns + ------- + The description. + """ + describe = partial( + self.describe, + should_print_description=should_print_description, + as_rst=as_rst, + ) + if option is None: + return describe(self._registered_options.keys()) + if isinstance(option, Iterable) and not isinstance(option, str): + return "\n".join([describe(k) for k in option]) + registered_option = self._registered_options[option] + doc = registered_option.describe(as_rst=as_rst).rstrip("\n") + if option in self._deprecated_options: + opt = self._deprecated_options[option] + if opt.message is not None: + doc += f" *{opt.message}" + doc += f" {option} will be removed in {opt.removal_version}.*" + if should_print_description: + print(doc) + return doc + + def deprecate( + self, option: str, removal_version: str, message: str | None = None + ) -> None: + """Deprecate options with a message at a version. + + Parameters + ---------- + option + Which option should be deprecated. + removal_version + The version targeted for removal. + message + A custom message. + """ + self._deprecated_options[option] = DeprecatedOption( + option, message, removal_version + ) + + @old_positionals("default_value", "description", "validate", "option_type") + def register( + self, + option: str, + *, + default_value: T, + description: str, + validate: Callable[[T, Self], None], + option_type: object | None = None, + get_from_env: Callable[[str, T], T] = lambda x, y: y, + ) -> None: + """Register an option so it can be set/described etc. by end-users + + Parameters + ---------- + option + Option to be set. + default_value + Default value with which to set the option. + description + Description to be used in the docstring. + validate + A function which raises a `ValueError` or `TypeError` if the value is invalid. + option_type + Optional override for the option type to be displayed. Otherwise `type(default_value)`. + get_from_env + An optional function which takes as arguments the name of the option and a default value and returns the value from the environment variable `ANNDATA_CAPS_OPTION` (or default if not present). + Default behavior is to return `default_value` without checking the environment. + """ + try: + validate(default_value, self) + except (ValueError, TypeError) as e: + e.add_note(f"for option {option!r}") + raise e + option_type = type(default_value) if option_type is None else option_type + self._registered_options[option] = RegisteredOption( + option, default_value, description, validate, option_type + ) + self._config[option] = get_from_env(option, default_value) + self._update_override_function_for_new_option(option) + + def _update_override_function_for_new_option( + self, + option: str, + ): + """This function updates the keyword arguments, docstring, and annotations of the `SettingsManager.override` function as the `SettingsManager.register` method is called. + + Parameters + ---------- + option + The option being registered for which the override function needs updating. + """ + option_type = self._registered_options[option].type + # Update annotations for type checking. + self.override.__annotations__[option] = option_type + # __signature__ needs to be updated for tab autocompletion in IPython. + # See https://github.com/ipython/ipython/issues/11624 for inspiration. + self.override.__func__.__signature__ = signature(self.override).replace( + parameters=[ + Parameter(name="self", kind=Parameter.POSITIONAL_ONLY), + *[ + Parameter( + name=k, + annotation=option_type, + kind=Parameter.KEYWORD_ONLY, + ) + for k in self._registered_options + ], + ] + ) + # Update docstring for `SettingsManager.override` as well. + doc = cast("str", self.override.__doc__) + insert_index = doc.find("\n Yields") + option_docstring = "\t" + "\t".join( + self.describe(option, should_print_description=False).splitlines( + keepends=True + ) + ) + self.override.__func__.__doc__ = ( + f"{doc[:insert_index]}\n{option_docstring}{doc[insert_index:]}" + ) + + def __setattr__(self, option: str, val: object) -> None: + """ + Set an option to a value. To see the allowed option to be set and their description, + use describe_option. + + Parameters + ---------- + option + Option to be set. + val + Value with which to set the option. + + Raises + ------ + AttributeError + If the option has not been registered, this function will raise an error. + """ + if option in {f.name for f in fields(self)}: + return super().__setattr__(option, val) + elif option not in self._registered_options: + msg = ( + f"{option} is not an available option for anndata. " + "Please open an issue if you believe this is a mistake." + ) + raise AttributeError(msg) + registered_option = self._registered_options[option] + registered_option.validate(val, self) + self._config[option] = val + + def __getattr__(self, option: str) -> object: + """ + Gets the option's value. + + Parameters + ---------- + option + Option to be got. + + Returns + ------- + Value of the option. + """ + if option in self._deprecated_options: + deprecated = self._deprecated_options[option] + msg = f"{option!r} will be removed in {deprecated.removal_version}. {deprecated.message}" + warnings.warn(msg, FutureWarning, stacklevel=2) + if option in self._config: + return self._config[option] + msg = f"{option} not found." + raise AttributeError(msg) + + def __dir__(self) -> Iterable[str]: + return sorted((*super().__dir__(), *self._config.keys())) + + def reset(self, option: Iterable[str] | str) -> None: + """ + Resets option(s) to its (their) default value(s). + + Parameters + ---------- + option + The option(s) to be reset. + """ + if isinstance(option, Iterable) and not isinstance(option, str): + for opt in option: + self.reset(opt) + else: + self._config[option] = self._registered_options[option].default_value + + @contextmanager + def override(self, **overrides): + """ + Provides local override via keyword arguments as a context manager. + + Parameters + ---------- + + Yields + ------ + None + """ + restore = {a: getattr(self, a) for a in overrides} + try: + # Preserve order so that settings that depend on each other can be overridden together i.e., always override zarr version before sharding. + # Otherwise an error would be raised setting sharding before zarr version if the zarr version is 2. + for k in self._config: + if k in overrides: + setattr(self, k, overrides.get(k)) + yield None + finally: + # In the try block, we went in the forward order i.e., zarr version before sharding, but in the reset here, we go in the reverse order i.e., sharding before zarr version. + # Otherwise an error would be raised if we reversed the zarr version first and it was 3 previously. + for k in reversed(self._config.keys()): + if k in restore: + setattr(self, k, restore.get(k)) + + def __repr__(self) -> str: + params = "".join(f"\t{k}={v!r},\n" for k, v in self._config.items()) + return f"{type(self).__name__}(\n{params}\n)" + + @property + def __doc__(self): + in_sphinx = any("/sphinx/" in frame.filename for frame in inspect.stack()) + options_description = self.describe( + should_print_description=False, as_rst=in_sphinx + ) + return self.__doc_tmpl__.format( + options_description=options_description, + ) + + +settings = SettingsManager() + +################################################################################## +# PLACE REGISTERED SETTINGS HERE SO THEY CAN BE PICKED UP FOR DOCSTRING CREATION # +################################################################################## +V = TypeVar("V") + + +def gen_validator(_type: type[V]) -> Callable[[V], None]: + def validate_type(val: V, settings: SettingsManager) -> None: + if not isinstance(val, _type): + msg = f"{val} not valid {_type}" + raise TypeError(msg) + + return validate_type + + +validate_bool = gen_validator(bool) +validate_int = gen_validator(int) + + +settings.register( + "remove_unused_categories", + default_value=True, + description="Whether or not to remove unused categories with :class:`~pandas.Categorical`.", + validate=validate_bool, + get_from_env=check_and_get_bool, +) + +settings.register( + "check_uniqueness", + default_value=True, + description=( + "Whether or not to check uniqueness of the `obs` indices on `__init__` of :class:`~anndata.AnnData`." + ), + validate=validate_bool, + get_from_env=check_and_get_bool, +) + +settings.register( + "allow_write_nullable_strings", + default_value=False, + description="Whether or not to allow writing of `pd.arrays.{StringArray,ArrowStringArray}`.", + validate=validate_bool, + get_from_env=check_and_get_bool, +) + + +def validate_zarr_write_format(format: int, settings: SettingsManager): + validate_int(format, settings) + if format not in {2, 3}: + msg = "non-v2 zarr on-disk format not supported" + raise ValueError(msg) + + +settings.register( + "zarr_write_format", + default_value=2, + description="Which version of zarr to write to when anndata must internally open a write-able zarr group.", + validate=validate_zarr_write_format, + get_from_env=lambda name, default: check_and_get_environ_var( + f"ANNDATA_{name.upper()}", + str(default), + ["2", "3"], + lambda x: int(x), + ), +) + + +def validate_sparse_settings(val: Any, settings: SettingsManager) -> None: + validate_bool(val, settings) + + +settings.register( + "use_sparse_array_on_read", + default_value=False, + description="Whether or not to use :class:`scipy.sparse.sparray` as the default class when reading in data", + validate=validate_bool, + get_from_env=check_and_get_bool, +) + +settings.register( + "min_rows_for_chunked_h5_copy", + default_value=1000, + description="Minimum number of rows at a time to copy when writing out an H5 Dataset to a new location", + validate=validate_int, + get_from_env=check_and_get_int, +) + +settings.register( + "disallow_forward_slash_in_h5ad", + default_value=False, + description="Whether or not to disallow the `/` character in keys for h5ad files", + validate=validate_bool, + get_from_env=check_and_get_bool, +) + +settings.register( + "write_csr_csc_indices_with_min_possible_dtype", + default_value=False, + description="Write a csr or csc matrix with the minimum possible data type for `indices`, always unsigned integer.", + validate=validate_bool, + get_from_env=check_and_get_bool, +) + +settings.register( + "auto_shard_zarr_v3", + default_value=None, + description="Whether or not to use zarr's auto computation of sharding for v3. For v2 this setting will be ignored. The setting will apply to all calls to anndata's writing mechanism (write_zarr / write_elem) and will **not** override any user-defined kwargs for shards.", + validate=gen_validator((bool, NoneType)), + option_type=bool | None, + get_from_env=check_and_get_bool_or_none, +) + + +settings.register( + "copy_on_write_X", + default_value=False, + description=( + "Whether to copy-on-write X. " + "Currently `my_adata_view[subset].X = value` will write back to the original AnnData object at the `subset` location. " + "`X` is the only element where this behavior is implemented though." + ), + validate=validate_bool, + get_from_env=check_and_get_bool, +) + + +################################################################################## +################################################################################## diff --git a/.venv/lib/python3.11/site-packages/anndata/_settings.pyi b/.venv/lib/python3.11/site-packages/anndata/_settings.pyi new file mode 100644 index 0000000000000000000000000000000000000000..77d99034d9db31e14a62edadee152bc8c919aa70 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/anndata/_settings.pyi @@ -0,0 +1,53 @@ +from collections.abc import Callable as Callable +from collections.abc import Generator, Iterable +from contextlib import contextmanager +from dataclasses import dataclass +from typing import Literal, Self, TypeVar + +_T = TypeVar("_T") + +@dataclass +class SettingsManager: + __doc_tmpl__: str = ... + def describe( + self, + option: str | Iterable[str] | None = None, + *, + should_print_description: bool = True, + as_rst: bool = False, + ) -> str: ... + def deprecate( + self, option: str, removal_version: str, message: str | None = None + ) -> None: ... + def register( + self, + option: str, + *, + default_value: _T, + description: str, + validate: Callable[[_T, Self], None], + option_type: object | None = None, + get_from_env: Callable[[str, _T], _T] = ..., + ) -> None: ... + def __setattr__(self, option: str, val: object) -> None: ... + def __getattr__(self, option: str) -> object: ... + def __dir__(self) -> Iterable[str]: ... + def reset(self, option: Iterable[str] | str) -> None: ... + @contextmanager + def override(self, **overrides) -> Generator[None]: ... + @property + def __doc__(self): ... + +class _AnnDataSettingsManager(SettingsManager): + remove_unused_categories: bool = True + check_uniqueness: bool = True + allow_write_nullable_strings: bool = False + copy_on_write_X: bool = False + zarr_write_format: Literal[2, 3] = 2 + use_sparse_array_on_read: bool = False + min_rows_for_chunked_h5_copy: int = 1000 + disallow_forward_slash_in_h5ad: bool = False + write_csr_csc_indices_with_min_possible_dtype: bool = False + auto_shard_zarr_v3: bool | None = None + +settings: _AnnDataSettingsManager diff --git a/.venv/lib/python3.11/site-packages/anndata/_types.py b/.venv/lib/python3.11/site-packages/anndata/_types.py new file mode 100644 index 0000000000000000000000000000000000000000..7b52e1ab47190f992e663cfb02ebc672c5f343aa --- /dev/null +++ b/.venv/lib/python3.11/site-packages/anndata/_types.py @@ -0,0 +1,225 @@ +""" +Defines some useful types for this library. Should probably be cleaned up before thinking about exporting. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Literal, Protocol, TypeVar + +from . import typing +from .compat import H5Array, H5Group, ZarrArray, ZarrGroup + +if TYPE_CHECKING: + from collections.abc import Mapping + from typing import Any, TypeAlias + + from anndata._core.xarray import Dataset2D + + from ._io.specs.registry import ( + IOSpec, + LazyDataStructures, + LazyReader, + Reader, + Writer, + ) + + +__all__ = [ + "AnnDataElem", + "ArrayStorageType", + "Dataset2DIlocIndexer", + "GroupStorageType", + "Read", + "ReadCallback", + "ReadLazy", + "StorageType", + "Write", + "WriteCallback", + "_ReadInternal", + "_ReadLazyInternal", + "_WriteInternal", +] + +ArrayStorageType: TypeAlias = ZarrArray | H5Array +GroupStorageType: TypeAlias = ZarrGroup | H5Group +StorageType: TypeAlias = ArrayStorageType | GroupStorageType + +# NOTE: If you change these, be sure to update `autodoc_type_aliases` in docs/conf.py! +RWAble_contra = TypeVar("RWAble_contra", bound=typing.RWAble, contravariant=True) +RWAble_co = TypeVar("RWAble_co", bound=typing.RWAble, covariant=True) +RWAble = TypeVar("RWAble", bound=typing.RWAble) + +S_co = TypeVar("S_co", covariant=True, bound=StorageType) +S_contra = TypeVar("S_contra", contravariant=True, bound=StorageType) + + +class Dataset2DIlocIndexer(Protocol): + def __getitem__(self, idx: Any, /) -> Dataset2D: ... + + +class _ReadInternal(Protocol[S_contra, RWAble_co]): + def __call__(self, elem: S_contra, /, *, _reader: Reader) -> RWAble_co: ... + + +class _ReadLazyInternal(Protocol[S_contra]): + def __call__( + self, + elem: S_contra, + /, + *, + _reader: LazyReader, + chunks: tuple[int, ...] | None = None, + ) -> LazyDataStructures: ... + + +class Read(Protocol[S_contra, RWAble_co]): + def __call__(self, elem: S_contra, /) -> RWAble_co: + """Low-level reading function for an element. + + Parameters + ---------- + elem + The element to read from. + Returns + ------- + The element read from the store. + """ + ... + + +class ReadLazy(Protocol[S_contra]): + def __call__( + self, elem: S_contra, /, *, chunks: tuple[int, ...] | None = None + ) -> LazyDataStructures: + """Low-level reading function for a lazy element. + + Parameters + ---------- + elem + The element to read from. + chunks + The chunk size to be used. + Returns + ------- + The lazy element read from the store. + """ + ... + + +class _WriteInternal(Protocol[S_contra, RWAble_contra]): + def __call__( + self, + f: S_contra, + k: str, + v: RWAble_contra, + /, + *, + _writer: Writer, + dataset_kwargs: Mapping[str, Any], + ) -> None: ... + + +class Write(Protocol[RWAble_contra]): + def __call__( + self, + f: StorageType, + k: str, + v: RWAble_contra, + /, + *, + dataset_kwargs: Mapping[str, Any], + ) -> None: + """Low-level writing function for an element. + + Parameters + ---------- + f + The store to which `elem` should be written. + k + The key to read in from the group. + v + The element to write out. + dataset_kwargs + Keyword arguments to be passed to a library-level io function, like `chunks` for :mod:`zarr`. + """ + ... + + +class ReadCallback(Protocol[S_co, RWAble]): + def __call__( + self, + /, + read_func: Read[S_co, RWAble], + elem_name: str, + elem: StorageType, + *, + iospec: IOSpec, + ) -> RWAble: + """ + Callback used in :func:`anndata.experimental.read_dispatched` to customize reading an element from a store. + + Params + ------ + read_func + :func:`anndata.io.read_elem` function to call to read the current element given the ``iospec``. + elem_name + The key to read in from the group. + elem + The element to read from. + iospec + Internal AnnData encoding specification for the element. + + Returns + ------- + The element read from the store. + """ + ... + + +class WriteCallback(Protocol[RWAble]): + def __call__( + self, + /, + write_func: Write[RWAble], + store: StorageType, + elem_name: str, + elem: RWAble, + *, + iospec: IOSpec, + dataset_kwargs: Mapping[str, Any], + ) -> None: + """ + Callback used in :func:`anndata.experimental.write_dispatched` to customize writing an element to a store. + + Params + ------ + write_func + :func:`anndata.io.write_elem` function to call to read the current element given the ``iospec``. + store + The store to which `elem` should be written. + elem_name + The key to write out to the group. + elem + The element to write out. + iospec + Internal AnnData encoding specification for the element. + dataset_kwargs + Keyword arguments to be passed to a library-level io function, like `chunks` for :mod:`zarr`. + """ + ... + + +AnnDataElem = Literal[ + "obs", + "var", + "obsm", + "varm", + "obsp", + "varp", + "layers", + "X", + "raw", + "uns", +] + +Join_T = Literal["inner", "outer"] diff --git a/.venv/lib/python3.11/site-packages/anndata/_warnings.py b/.venv/lib/python3.11/site-packages/anndata/_warnings.py new file mode 100644 index 0000000000000000000000000000000000000000..786c79a0a2bc81ec4b654ce9c852ae7256b03989 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/anndata/_warnings.py @@ -0,0 +1,26 @@ +from __future__ import annotations + + +class WriteWarning(UserWarning): + pass + + +class OldFormatWarning(PendingDeprecationWarning): + """Raised when a file in an old file format is read.""" + + +class ImplicitModificationWarning(UserWarning): + """\ + Raised whenever initializing an object or assigning a property changes + the type of a part of a parameter or the value being assigned. + + Examples + ======== + >>> import pandas as pd + >>> adata = AnnData(obs=pd.DataFrame(index=[0, 1, 2])) # doctest: +SKIP + ImplicitModificationWarning: Transforming to str index. + """ + + +class ExperimentalFeatureWarning(Warning): + """Raised when an unstable experimental feature is used.""" diff --git a/.venv/lib/python3.11/site-packages/anndata/abc.py b/.venv/lib/python3.11/site-packages/anndata/abc.py new file mode 100644 index 0000000000000000000000000000000000000000..1dd69ae0d0c376b69030c4d988f3c2129b4c0200 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/anndata/abc.py @@ -0,0 +1,76 @@ +from __future__ import annotations + +from abc import ABC, abstractmethod +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from typing import ClassVar, Literal + + import numpy as np + + from .compat import CSArray, CSMatrix, Index + + +__all__ = ["CSCDataset", "CSRDataset"] + + +class _AbstractCSDataset(ABC): + """Base for the public API for CSRDataset/CSCDataset.""" + + format: ClassVar[Literal["csr", "csc"]] + """The format of the sparse matrix.""" + + shape: tuple[int, int] + """Shape of the matrix.""" + + dtype: np.dtype + """The :class:`numpy.dtype` of the `data` attribute of the sparse matrix.""" + + backend: Literal["zarr", "hdf5"] + """Which file type is used on-disk.""" + + @abstractmethod + def __getitem__(self, index: Index) -> float | CSMatrix | CSArray: + """Load a slice or an element from the sparse dataset into memory. + + Parameters + ---------- + index + Index to load. + + Returns + ------- + The desired data read off disk. + """ + + @abstractmethod + def to_memory(self) -> CSMatrix | CSArray: + """Load the sparse dataset into memory. + + Returns + ------- + The in-memory representation of the sparse dataset. + """ + + +_sparse_dataset_doc = """\ +On disk {format} sparse matrix. + +Analogous to :class:`h5py.Dataset` or :class:`zarr.Array`, but for sparse matrices. +""" + + +class CSRDataset(_AbstractCSDataset, ABC): + __doc__ = _sparse_dataset_doc.format(format="CSR") + format = "csr" + + +class CSCDataset(_AbstractCSDataset, ABC): + __doc__ = _sparse_dataset_doc.format(format="CSC") + format = "csc" + + +for cls in (CSRDataset, CSCDataset): + # So that Sphinx doesn’t interpret these as inherited + cls.__getitem__ = _AbstractCSDataset.__getitem__ + cls.to_memory = _AbstractCSDataset.to_memory diff --git a/.venv/lib/python3.11/site-packages/anndata/compat/__init__.py b/.venv/lib/python3.11/site-packages/anndata/compat/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..79a8ecae20d7687df0f842915db409c3bd2815cd --- /dev/null +++ b/.venv/lib/python3.11/site-packages/anndata/compat/__init__.py @@ -0,0 +1,505 @@ +from __future__ import annotations + +from codecs import decode +from collections.abc import Mapping, Sequence +from enum import Enum, auto +from functools import cache, partial, singledispatch +from importlib.metadata import version +from importlib.util import find_spec +from types import EllipsisType +from typing import TYPE_CHECKING, TypeVar, overload +from warnings import warn + +import h5py +import numpy as np +import pandas as pd +import scipy +from numpy.typing import NDArray +from packaging.version import Version +from zarr import Array as ZarrArray # noqa: F401 +from zarr import Group as ZarrGroup + +if TYPE_CHECKING: + from typing import Any, TypeAlias + + +############################# +# scipy sparse array comapt # +############################# + + +CSMatrix = scipy.sparse.csr_matrix | scipy.sparse.csc_matrix +CSArray = scipy.sparse.csr_array | scipy.sparse.csc_array + + +class Empty(Enum): + TOKEN = auto() + + +Index1DNorm = slice | NDArray[np.bool_] | NDArray[np.integer] +# TODO: pd.Index[???] +Index1D = ( + # 0D index + int + | str + | np.int64 + # normalized 1D idex + | Index1DNorm + # different containers for mask, obs/varnames, or numerical index + | Sequence[int] + | Sequence[str] + | Sequence[bool] + | pd.Series # bool, int, str + | pd.Index + | pd.api.extensions.ExtensionArray # bool | int | str + | NDArray[np.str_] + | np.matrix # bool + | CSMatrix # bool + | CSArray # bool +) +IndexRest = Index1D | EllipsisType +Index: TypeAlias = ( + IndexRest + | tuple[Index1D, IndexRest] + | tuple[IndexRest, Index1D] + | tuple[Index1D, Index1D, EllipsisType] + | tuple[EllipsisType, Index1D, Index1D] + | tuple[Index1D, EllipsisType, Index1D] + | CSMatrix + | CSArray +) +H5Group = h5py.Group +H5Array = h5py.Dataset +H5File = h5py.File + +# h5py recommends using .astype("T") over .asstr() when using numpy ≥2 +if TYPE_CHECKING: + from h5py._hl.dataset import AsStrView as H5AsStrView + from h5py._hl.dataset import AsTypeView as H5AsTypeView +else: + try: + try: + from h5py._hl.dataset import AsStrView as H5AsStrView + from h5py._hl.dataset import AsTypeView as H5AsTypeView + except ImportError: + # h5py 3.11 uses AsStrWrapper/AstypeWrapper (lowercase 't') + from h5py._hl.dataset import AsStrWrapper as H5AsStrView + from h5py._hl.dataset import AstypeWrapper as H5AsTypeView + except ImportError: # pragma: no cover + warn("AsTypeView changed import location", DeprecationWarning, stacklevel=1) + _ds = h5py.File.in_memory().create_dataset("x", shape=(), dtype="S1") + H5AsStrView = type(_ds.asstr()) + H5AsTypeView = type(_ds.astype("U1")) + del _ds + + +############################# +# Optional deps +############################# +@cache +def is_zarr_v2() -> bool: + return Version(version("zarr")) < Version("3.0.0") + + +if is_zarr_v2(): + msg = "anndata will no longer support zarr v2 in the near future. Please prepare to upgrade to zarr>=3." + warn(msg, DeprecationWarning, stacklevel=2) + + +if find_spec("awkward") or TYPE_CHECKING: + import awkward # noqa: F401 + from awkward import Array as AwkArray +else: + + class AwkArray: + @staticmethod + def __repr__(): + return "mock awkward.highlevel.Array" + + +if find_spec("zappy") or TYPE_CHECKING: + from zappy.base import ZappyArray +else: + + class ZappyArray: + @staticmethod + def __repr__(): + return "mock zappy.base.ZappyArray" + + +if TYPE_CHECKING: + # type checkers are confused and can only see …core.Array + from dask.array.core import Array as DaskArray +elif find_spec("dask"): + from dask.array import Array as DaskArray +else: + + class DaskArray: + @staticmethod + def __repr__(): + return "mock dask.array.core.Array" + + +if find_spec("xarray") or TYPE_CHECKING: + import xarray + from xarray import DataArray as XDataArray + from xarray import Dataset as XDataset + from xarray import Variable as XVariable + from xarray.backends import BackendArray as XBackendArray + from xarray.backends.zarr import ZarrArrayWrapper as XZarrArrayWrapper +else: + xarray = None + XDataArray = type("DataArray", (), dict(__module__="xarray")) + XDataset = type("Dataset", (), dict(__module__="xarray")) + XVariable = type("Variable", (), dict(__module__="xarray")) + XBackendArray = type("BackendArray", (), dict(__module__="xarray.backends")) + XZarrArrayWrapper = type( + "ZarrArrayWrapper", (), dict(__module__="xarray.backends.zarr") + ) + + +# https://github.com/scverse/anndata/issues/1749 +def is_cupy_importable() -> bool: + try: + import cupy # noqa: F401 + except ImportError: + return False + return True + + +if is_cupy_importable() or TYPE_CHECKING: + from cupy import ndarray as CupyArray + from cupyx.scipy.sparse import csc_matrix as CupyCSCMatrix + from cupyx.scipy.sparse import csr_matrix as CupyCSRMatrix + from cupyx.scipy.sparse import spmatrix as CupySparseMatrix + + try: + import dask.array as da + except ImportError: + pass + else: + da.register_chunk_type(CupyCSRMatrix) + da.register_chunk_type(CupyCSCMatrix) +else: + + class CupySparseMatrix: + @staticmethod + def __repr__(): + return "mock cupyx.scipy.sparse.spmatrix" + + class CupyCSRMatrix: + @staticmethod + def __repr__(): + return "mock cupyx.scipy.sparse.csr_matrix" + + class CupyCSCMatrix: + @staticmethod + def __repr__(): + return "mock cupyx.scipy.sparse.csc_matrix" + + class CupyArray: + @staticmethod + def __repr__(): + return "mock cupy.ndarray" + + +if find_spec("legacy_api_wrap") or TYPE_CHECKING: + from legacy_api_wrap import legacy_api # noqa: TID251 + + old_positionals = partial(legacy_api, category=FutureWarning) +else: + + def old_positionals(*old_positionals): + return lambda func: func + + +############################# +# IO helpers +############################# + +NUMPY_2 = Version(version("numpy")) >= Version("2") + +NULLABLE_NUMPY_STRING_TYPE = ( + np.dtypes.StringDType(na_object=pd.NA) if NUMPY_2 else np.dtype("O") +) + +PANDAS_SUPPORTS_NA_VALUE = Version(version("pandas")) >= Version("2.3") + + +PANDAS_STRING_ARRAY_TYPES: list[type[pd.api.extensions.ExtensionArray]] = [ + pd.arrays.StringArray, + pd.arrays.ArrowStringArray, +] +# these are removed in favor of the above classes: https://github.com/pandas-dev/pandas/pull/62149 +try: + from pandas.core.arrays.string_ import StringArrayNumpySemantics +except ImportError: + pass +else: + PANDAS_STRING_ARRAY_TYPES += [StringArrayNumpySemantics] +try: + from pandas.core.arrays.string_arrow import ArrowStringArrayNumpySemantics +except ImportError: + pass +else: + PANDAS_STRING_ARRAY_TYPES += [ArrowStringArrayNumpySemantics] + + +@overload +def pandas_as_str(a: pd.Index[Any]) -> pd.Index[str]: ... +@overload +def pandas_as_str(a: pd.Series[Any]) -> pd.Series[str]: ... + + +def pandas_as_str(a: pd.Index | pd.Series) -> pd.Index[str] | pd.Series[str]: + """Convert to fitting dtype, maintaining NA semantics if possible. + + This is `"str"` when `pd.options.future.infer_string` is `True` (e.g. in Pandas 3+), and `"object"` otherwise. + """ + if not pd.options.future.infer_string: + return a.astype(str) + if a.array.dtype == "string": # any `pd.StringDtype` + return a + if PANDAS_SUPPORTS_NA_VALUE: + dtype = pd.StringDtype(na_value=a.array.dtype.na_value) + elif a.array.dtype.na_value is pd.NA: + dtype = pd.StringDtype() # NA semantics + elif a.array.dtype.na_value is np.nan and find_spec("pyarrow"): # noqa: PLW0177 + # on pandas 2.2, this is the only way to get `np.nan` semantics + dtype = pd.StringDtype("pyarrow_numpy") + else: + msg = ( + f"Converting an array with `dtype.na_value={a.array.dtype.na_value}` to a string array requires pyarrow or pandas>=2.3. " + "Converting to `pd.NA` semantics instead." + ) + warn(msg, UserWarning, stacklevel=2) + dtype = pd.StringDtype() # NA semantics + return a.astype(dtype) + + +V = TypeVar("V") +T = TypeVar("T") + + +@overload +def _read_attr( + attrs: Mapping[str, V], name: str, default: Empty = Empty.TOKEN +) -> V: ... + + +@overload +def _read_attr(attrs: Mapping[str, V], name: str, default: T) -> V | T: ... + + +@singledispatch +def _read_attr( + attrs: Mapping[str, V], name: str, default: T | Empty = Empty.TOKEN +) -> V | T: + if default is Empty.TOKEN: + return attrs[name] + else: + return attrs.get(name, default=default) + + +@_read_attr.register(h5py.AttributeManager) +def _read_attr_hdf5( + attrs: h5py.AttributeManager, name: str, default: T | Empty = Empty.TOKEN +) -> str | T: + """ + Read an HDF5 attribute and perform all necessary conversions. + + At the moment, this only implements conversions for string attributes, other types + are passed through. String conversion is needed compatibility with other languages. + For example Julia's HDF5.jl writes string attributes as fixed-size strings, which + are read as bytes by h5py. + """ + if name not in attrs and default is not Empty.TOKEN: + return default + attr = attrs[name] + attr_id = attrs.get_id(name) + dtype = h5py.check_string_dtype(attr_id.dtype) + if dtype is None or dtype.length is None: # variable-length string, no problem + return attr + elif len(attr_id.shape) == 0: # Python bytestring + return attr.decode("utf-8") + else: # NumPy array + return [decode(s, "utf-8") for s in attr] + + +def _from_fixed_length_strings(value): + """\ + Convert from fixed length strings to unicode. + + For backwards compatibility with older h5ad and zarr files. + """ + new_dtype = [] + for dt in value.dtype.descr: + dt_list = list(dt) + dt_type = dt[1] + # could probably match better + is_annotated = isinstance(dt_type, tuple) + if is_annotated: + dt_type = dt_type[0] + # Fixing issue introduced with h5py v2.10.0, see: + # https://github.com/h5py/h5py/issues/1307 + if issubclass(np.dtype(dt_type).type, np.bytes_): + dt_list[1] = f"U{int(dt_type[2:])}" + elif is_annotated or np.issubdtype(np.dtype(dt_type), np.str_): + dt_list[1] = "O" # Assumption that it’s a vlen str + new_dtype.append(tuple(dt_list)) + return value.astype(new_dtype) + + +def _decode_structured_array( + arr: np.ndarray, *, dtype: np.dtype | None = None, copy: bool = False +) -> np.ndarray: + """ + h5py 3.0 now reads all strings as bytes. There is a helper method which can convert these to strings, + but there isn't anything for fields of structured dtypes. + + Params + ------ + arr + An array with structured dtype + dtype + dtype of the array. This is checked for h5py string data types. + Passing this is allowed for cases where array may have been processed by another function before hand. + """ + if copy: + arr = arr.copy() + if dtype is None: + dtype = arr.dtype + # codecs.decode is 2x slower than this lambda, go figure + decode = np.frompyfunc(lambda x: x.decode("utf-8"), 1, 1) + for k, (dt, _) in dtype.fields.items(): + check = h5py.check_string_dtype(dt) + if check is not None and check.encoding == "utf-8": + decode(arr[k], out=arr[k]) + return arr + + +def _to_fixed_length_strings(value: np.ndarray) -> np.ndarray: + """\ + Convert variable length strings to fixed length. + + Formerly a workaround for + https://github.com/zarr-developers/zarr-python/pull/422, + resolved in https://github.com/zarr-developers/zarr-python/pull/813. + + But if we didn't do this conversion, we would have to use a special codec in v2 + for objects and v3 doesn't support objects at all. So we leave this function as-is. + """ + new_dtype = [] + for dt_name, (dt_type, dt_offset) in value.dtype.fields.items(): + if dt_type.kind == "O": + # Assuming the objects are str + size = max(len(x.encode()) for x in value.getfield("O", dt_offset)) + new_dtype.append((dt_name, ("U", size))) + else: + new_dtype.append((dt_name, dt_type)) + return value.astype(new_dtype) + + +Group_T = TypeVar("Group_T", bound=ZarrGroup | h5py.Group) + + +# TODO: This is a workaround for https://github.com/scverse/anndata/issues/874 +# See https://github.com/h5py/h5py/pull/2311#issuecomment-1734102238 for why this is done this way. +def _require_group_write_dataframe( + f: Group_T, name: str, df: pd.DataFrame, *args, **kwargs +) -> Group_T: + if len(df.columns) > 5_000 and isinstance(f, H5Group): + # actually 64kb is the limit, but this should be a conservative estimate + return f.create_group(name, *args, track_order=True, **kwargs) + return f.require_group(name, *args, **kwargs) + + +############################# +# Dealing with uns +############################# + + +def _clean_uns(adata: AnnData): # noqa: F821 + """ + Compat function for when categorical keys were stored in uns. + This used to be buggy because when storing categorical columns in obs and var with + the same column name, only one `_categories` is retained. + """ + k_to_delete = set() + for cats_name, cats in adata.uns.items(): + if not cats_name.endswith("_categories"): + continue + name = cats_name.replace("_categories", "") + # fix categories with a single category + if isinstance(cats, str | int): + cats = [cats] + for ann in [adata.obs, adata.var]: + if name not in ann: + continue + codes: np.ndarray = ann[name].values + # hack to maybe find the axis the categories were for + if not np.all(codes < len(cats)): + continue + ann[name] = pd.Categorical.from_codes(codes, cats) + k_to_delete.add(cats_name) + for cats_name in k_to_delete: + del adata.uns[cats_name] + + +def _move_adj_mtx(d): + """ + Read-time fix for moving adjacency matrices from uns to obsp + """ + n = d.get("uns", {}).get("neighbors", {}) + obsp = d.setdefault("obsp", {}) + + for k in ("distances", "connectivities"): + if ( + (k in n) + and isinstance(n[k], scipy.sparse.spmatrix | np.ndarray) + and len(n[k].shape) == 2 + ): + msg = ( + f"Moving element from .uns['neighbors'][{k!r}] to .obsp[{k!r}].\n\n" + "This is where adjacency matrices should go now." + ) + # 5: caller -> 4: legacy_api_wrap -> 3: `AnnData.__init__` -> 2: `_init_as_actual` → 1: here + warn(msg, FutureWarning, stacklevel=5) + obsp[k] = n.pop(k) + + +def _find_sparse_matrices(d: Mapping, n: int, keys: tuple, paths: list): + """Find paths to sparse matrices with shape (n, n).""" + for k, v in d.items(): + if isinstance(v, Mapping): + _find_sparse_matrices(v, n, (*keys, k), paths) + elif scipy.sparse.issparse(v) and v.shape == (n, n): + paths.append((*keys, k)) + return paths + + +def _transpose_by_block(dask_array: DaskArray) -> DaskArray: + import dask.array as da + + b = dask_array.blocks + b_raveled = b.ravel() + block_layout = np.zeros(b.shape, dtype=object) + + for i in range(block_layout.size): + block_layout.flat[i] = b_raveled[i].map_blocks( + lambda x: x.T, chunks=b_raveled[i].chunks[::-1] + ) + + return da.block(block_layout.T.tolist()) + + +def _safe_transpose(x): + """Safely transpose x + + This is a workaround for: https://github.com/scipy/scipy/issues/19161 + """ + + if isinstance(x, DaskArray) and scipy.sparse.issparse(x._meta): + return _transpose_by_block(x) + else: + return x.T diff --git a/.venv/lib/python3.11/site-packages/anndata/compat/__pycache__/__init__.cpython-311.pyc b/.venv/lib/python3.11/site-packages/anndata/compat/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..47b3ffeed340f0ffd1d1f07a0576f72df97de0fa Binary files /dev/null and b/.venv/lib/python3.11/site-packages/anndata/compat/__pycache__/__init__.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/anndata/experimental/__init__.py b/.venv/lib/python3.11/site-packages/anndata/experimental/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1271ac9b579c10ee8b21ff6453649829fc468216 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/anndata/experimental/__init__.py @@ -0,0 +1,68 @@ +from __future__ import annotations + +from types import MappingProxyType +from typing import TYPE_CHECKING + +from .._io.specs import IOSpec, read_elem_lazy +from .._types import ( + Dataset2DIlocIndexer, + Read, + ReadCallback, + StorageType, + Write, + WriteCallback, +) +from ..utils import module_get_attr_redirect +from ._dispatch_io import read_dispatched, write_dispatched +from .backed import read_lazy +from .merge import concat_on_disk +from .multi_files import AnnCollection + +if TYPE_CHECKING: + from typing import Any + + from .pytorch import AnnLoader + +# Map old name in `anndata.experimental` to new name in `anndata` +_DEPRECATED = MappingProxyType( + dict( + (kv if isinstance(kv, tuple) else (kv, kv)) + for kv in ( + ("CSRDataset", "abc.CSRDataset"), + ("CSCDataset", "abc.CSCDataset"), + ("sparse_dataset", "io.sparse_dataset"), + ("read_elem", "io.read_elem"), + ("write_elem", "io.write_elem"), + ("RWAble", "typing.AxisStorable"), + ("InMemoryElem", "typing.RWAble"), + ) + ) +) + + +def __getattr__(attr_name: str) -> Any: + if attr_name == "AnnLoader": + from .pytorch import AnnLoader + + return AnnLoader + return module_get_attr_redirect( + attr_name, deprecated_mapping=_DEPRECATED, old_module_path="experimental" + ) + + +__all__ = [ + "AnnCollection", + "AnnLoader", + "Dataset2DIlocIndexer", + "IOSpec", + "Read", + "ReadCallback", + "StorageType", + "Write", + "WriteCallback", + "concat_on_disk", + "read_dispatched", + "read_elem_lazy", + "read_lazy", + "write_dispatched", +] diff --git a/.venv/lib/python3.11/site-packages/anndata/experimental/__pycache__/__init__.cpython-311.pyc b/.venv/lib/python3.11/site-packages/anndata/experimental/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1bc34b66562e7feae22dc53f0f5e55d1bbdbe33c Binary files /dev/null and b/.venv/lib/python3.11/site-packages/anndata/experimental/__pycache__/__init__.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/anndata/experimental/__pycache__/_dispatch_io.cpython-311.pyc b/.venv/lib/python3.11/site-packages/anndata/experimental/__pycache__/_dispatch_io.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1f4b2cde1a5b7b4c028af37e3444edcb6018c28b Binary files /dev/null and b/.venv/lib/python3.11/site-packages/anndata/experimental/__pycache__/_dispatch_io.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/anndata/experimental/__pycache__/merge.cpython-311.pyc b/.venv/lib/python3.11/site-packages/anndata/experimental/__pycache__/merge.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d3ae028f27a351b4a4181f1be2cfe6073cf366d6 Binary files /dev/null and b/.venv/lib/python3.11/site-packages/anndata/experimental/__pycache__/merge.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/anndata/experimental/_dispatch_io.py b/.venv/lib/python3.11/site-packages/anndata/experimental/_dispatch_io.py new file mode 100644 index 0000000000000000000000000000000000000000..35c0e89af4d9cedbd9728c6b7fae2b39985b5495 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/anndata/experimental/_dispatch_io.py @@ -0,0 +1,74 @@ +from __future__ import annotations + +from types import MappingProxyType +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from collections.abc import Mapping + from typing import Any + + from anndata._types import ( + GroupStorageType, + ReadCallback, + StorageType, + WriteCallback, + ) + from anndata.typing import RWAble + + +def read_dispatched(elem: StorageType, callback: ReadCallback) -> RWAble: + """ + Read elem, calling the callback at each sub-element. + + Params + ------ + elem + Storage container (e.g. `h5py.Group`, `zarr.Group`). + This must have anndata element specifications. + callback + Function to call at each anndata encoded element. + + See Also + -------- + :doc:`/tutorials/notebooks/{read,write}_dispatched` + """ + from anndata._io.specs import _REGISTRY, Reader + + reader = Reader(_REGISTRY, callback=callback) + + return reader.read_elem(elem) + + +def write_dispatched( + store: GroupStorageType, + key: str, + elem: RWAble, + callback: WriteCallback, + *, + dataset_kwargs: Mapping[str, Any] = MappingProxyType({}), +) -> None: + """ + Write elem to store, recursively calling callback at each sub-element. + + Params + ------ + store + Storage container to be written to. + key + Key to write element to. To write to the root group, use "/". + elem + The element to write. Probably an AnnData. + callback + Function called when writing each element. + dataset_kwargs + Keyword arguments to pass to the dataset creation function. + + See Also + -------- + :doc:`/tutorials/notebooks/{read,write}_dispatched` + """ + from anndata._io.specs import _REGISTRY, Writer + + writer = Writer(_REGISTRY, callback=callback) + + writer.write_elem(store, key, elem, dataset_kwargs=dataset_kwargs) diff --git a/.venv/lib/python3.11/site-packages/anndata/experimental/backed/__init__.py b/.venv/lib/python3.11/site-packages/anndata/experimental/backed/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..97bb774a00563162ecbada0831df868e706657b0 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/anndata/experimental/backed/__init__.py @@ -0,0 +1,7 @@ +from __future__ import annotations + +from ..._core.xarray import Dataset2D +from ._io import read_lazy +from ._lazy_arrays import CategoricalArray, MaskedArray + +__all__ = ["CategoricalArray", "Dataset2D", "MaskedArray", "read_lazy"] diff --git a/.venv/lib/python3.11/site-packages/anndata/experimental/backed/__pycache__/__init__.cpython-311.pyc b/.venv/lib/python3.11/site-packages/anndata/experimental/backed/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2114d7172078a0f8b1ac35062f650db54b627900 Binary files /dev/null and b/.venv/lib/python3.11/site-packages/anndata/experimental/backed/__pycache__/__init__.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/anndata/experimental/backed/__pycache__/_compat.cpython-311.pyc b/.venv/lib/python3.11/site-packages/anndata/experimental/backed/__pycache__/_compat.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..231c3382584dc92031b6ca222451a8e2c8e69ca9 Binary files /dev/null and b/.venv/lib/python3.11/site-packages/anndata/experimental/backed/__pycache__/_compat.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/anndata/experimental/backed/__pycache__/_io.cpython-311.pyc b/.venv/lib/python3.11/site-packages/anndata/experimental/backed/__pycache__/_io.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a10785cc1442108eb0da0e1a2310df62470c68a3 Binary files /dev/null and b/.venv/lib/python3.11/site-packages/anndata/experimental/backed/__pycache__/_io.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/anndata/experimental/backed/__pycache__/_lazy_arrays.cpython-311.pyc b/.venv/lib/python3.11/site-packages/anndata/experimental/backed/__pycache__/_lazy_arrays.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf018c1014144f55d8dee6eb48f13bf8637bca6d Binary files /dev/null and b/.venv/lib/python3.11/site-packages/anndata/experimental/backed/__pycache__/_lazy_arrays.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/anndata/experimental/backed/_compat.py b/.venv/lib/python3.11/site-packages/anndata/experimental/backed/_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..0657a4be3dbf7ebf2b6438c671ba5db1ea697f69 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/anndata/experimental/backed/_compat.py @@ -0,0 +1,18 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +from ..._core.xarray import Dataset2D + +if TYPE_CHECKING: + from anndata import AnnData + + +def has_dataset_2d(adata: AnnData) -> bool: + if any(isinstance(annot_df, Dataset2D) for annot_df in [adata.obs, adata.var]): + return True + for annot_m_key in ["varm", "obsm"]: + annot_m = getattr(adata, annot_m_key) + if any(isinstance(maybe_df, Dataset2D) for maybe_df in annot_m.values()): + return True + return False diff --git a/.venv/lib/python3.11/site-packages/anndata/experimental/backed/_io.py b/.venv/lib/python3.11/site-packages/anndata/experimental/backed/_io.py new file mode 100644 index 0000000000000000000000000000000000000000..98eb9b4ddc22e3d77dbdd87504e18776e7ccb710 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/anndata/experimental/backed/_io.py @@ -0,0 +1,173 @@ +from __future__ import annotations + +import typing +import warnings +from contextlib import nullcontext +from os import PathLike +from pathlib import Path +from typing import TYPE_CHECKING + +import h5py + +from anndata._core.file_backing import AnnDataFileManager +from anndata._io.specs.registry import read_elem_lazy +from anndata._types import AnnDataElem +from testing.anndata._doctest import doctest_needs + +from ..._core.anndata import AnnData +from ..._core.xarray import requires_xarray +from ..._settings import settings +from ...compat import ZarrGroup, is_zarr_v2 +from .. import read_dispatched + +if TYPE_CHECKING: + from collections.abc import MutableMapping + + from anndata._io.specs.registry import IOSpec + from anndata._types import Read, StorageType + + +@doctest_needs("xarray") +@requires_xarray +def read_lazy( + store: PathLike[str] | str | MutableMapping | ZarrGroup | h5py.File | h5py.Group, + *, + load_annotation_index: bool = True, +) -> AnnData: + """ + Lazily read in on-disk/in-cloud AnnData stores, including `obs` and `var`. + No array data should need to be read into memory with the exception of :class:`ak.Array`, scalars, and some older-encoding arrays. + + Parameters + ---------- + store + A store-like object to be read in. If :class:`zarr.Group`, it is best for it to be consolidated. + If a path to an ``.h5ad`` file is provided, the open HDF5 file will be attached to the {class}`~anndata.AnnData` at the `file` attribute and it will be the user’s responsibility to close it when done with the returned object. + For this reason, it is recommended to use an {class}`h5py.File` as the `store` argument when working with h5 files. + It must remain open for at least as long as this returned object is in use. + load_annotation_index + Whether or not to use a range index for the `{obs,var}` :class:`xarray.Dataset` so as not to load the index into memory. + If `False`, the real `index` will be inserted as `{obs,var}_names` in the object but not be one of the `coords` thereby preventing read operations. + Access to `adata.obs.index` will also only give the dummy index, and not the "real" index that is file-backed. + + Returns + ------- + A lazily read-in :class:`~anndata.AnnData` object. + + Examples + -------- + + Preparing example objects + + >>> import anndata as ad + >>> import pooch + >>> import scanpy as sc + >>> base_url = "https://datasets.cellxgene.cziscience.com" + >>> # To update hashes: pooch.retrieve(url, known_hash=None) prints the new hash + >>> def get_cellxgene_data(id_: str, hash_: str): + ... return pooch.retrieve( + ... f"{base_url}/{id_}.h5ad", + ... known_hash=hash_, + ... fname=f"{id_}.h5ad", + ... path=sc.settings.datasetdir, + ... ) + >>> path_b_cells = get_cellxgene_data( + ... "a93eab58-3d82-4b61-8a2f-d7666dcdb7c4", + ... "sha256:dac90fe2aa8b78aee2c1fc963104592f8eff7b873ca21d01a51a5e416734651c", + ... ) + >>> path_fetal = get_cellxgene_data( + ... "d170ff04-6da0-4156-a719-f8e1bbefbf53", + ... "sha256:d497eebca03533919877b6fc876e8c9d8ba063199ddc86dd9fbcb9d1d87a3622", + ... ) + >>> b_cells_adata = ad.experimental.read_lazy(path_b_cells) + >>> fetal_adata = ad.experimental.read_lazy(path_fetal) + >>> print(b_cells_adata) + AnnData object with n_obs × n_vars = 146 × 33452 + obs: 'donor_id', 'self_reported_ethnicity_ontology_term_id', 'organism_ontology_term_id', ... + >>> print(fetal_adata) + AnnData object with n_obs × n_vars = 344 × 15585 + obs: 'nCount_Spatial', 'nFeature_Spatial', 'Cluster', 'adult_pred_type'... + + This functionality is compatible with :func:`anndata.concat` + + >>> ad.concat([b_cells_adata, fetal_adata], join="outer") + AnnData object with n_obs × n_vars = 490 × 33452 + obs: 'donor_id', 'self_reported_ethnicity_ontology_term_id', 'organism_ontology_term_id'... + """ + is_store_arg_h5_store = isinstance(store, h5py.Dataset | h5py.File | h5py.Group) + is_store_arg_h5_path = ( + isinstance(store, PathLike | str) and Path(store).suffix == ".h5ad" + ) + is_h5 = is_store_arg_h5_path or is_store_arg_h5_store + + has_keys = True # true if consolidated or h5ad + if not is_h5: + import zarr + + if not isinstance(store, ZarrGroup): + # v3 returns a ValueError for consolidated metadata not found + err_cls = KeyError if is_zarr_v2() else ValueError + try: + f = zarr.open_consolidated(store, mode="r") + except err_cls: + msg = "Did not read zarr as consolidated. Consider consolidating your metadata." + warnings.warn(msg, UserWarning, stacklevel=2) + has_keys = False + f = zarr.open_group(store, mode="r") + else: + f = store + elif is_store_arg_h5_store: + f = store + else: + f = h5py.File(store, mode="r") + + def callback(func: Read, /, elem_name: str, elem: StorageType, *, iospec: IOSpec): + if iospec.encoding_type in {"anndata", "raw"} or elem_name.endswith("/"): + iter_object = ( + dict(elem).items() + if has_keys + else ( + (k, v) + for k, v in ( + (k, elem.get(k, None)) for k in typing.get_args(AnnDataElem) + ) + if v + is not None # need to do this instead of `k in elem` to prevent unnecessary metadata accesses + ) + ) + return AnnData(**{k: read_dispatched(v, callback) for k, v in iter_object}) + elif ( + iospec.encoding_type + in { + "csr_matrix", + "csc_matrix", + "array", + "string-array", + "dataframe", + "categorical", + } + or "nullable" in iospec.encoding_type + ): + if iospec.encoding_type == "dataframe" and ( + elem_name[:4] in {"/obs", "/var"} + or elem_name[:8] in {"/raw/obs", "/raw/var"} + ): + return read_elem_lazy(elem, use_range_index=not load_annotation_index) + return read_elem_lazy(elem) + elif iospec.encoding_type in {"awkward-array"}: + return read_dispatched(elem, None) + elif iospec.encoding_type == "dict": + return { + k: read_dispatched(v, callback=callback) for k, v in dict(elem).items() + } + return func(elem) + + with ( + settings.override(check_uniqueness=False) + if not load_annotation_index + else nullcontext() + ): + adata: AnnData = read_dispatched(f, callback=callback) + if is_store_arg_h5_path and not is_store_arg_h5_store: + adata.file = AnnDataFileManager(adata, file_obj=f) + return adata diff --git a/.venv/lib/python3.11/site-packages/anndata/experimental/backed/_lazy_arrays.py b/.venv/lib/python3.11/site-packages/anndata/experimental/backed/_lazy_arrays.py new file mode 100644 index 0000000000000000000000000000000000000000..f073473e0d586fc39e1d47382ff2cdfdfba17932 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/anndata/experimental/backed/_lazy_arrays.py @@ -0,0 +1,225 @@ +from __future__ import annotations + +from functools import cached_property +from typing import TYPE_CHECKING, Generic, TypeVar + +import numpy as np +import pandas as pd + +from anndata._core.index import _subset +from anndata._core.views import as_view +from anndata._io.specs.lazy_methods import get_chunksize + +from ..._io.utils import pandas_nullable_dtype +from ..._settings import settings +from ...compat import ( + NULLABLE_NUMPY_STRING_TYPE, + H5Array, + H5AsStrView, + H5AsTypeView, + XBackendArray, + XDataArray, + XZarrArrayWrapper, + ZarrArray, +) + +if TYPE_CHECKING: + from pathlib import Path + from typing import Literal + + from numpy.typing import NDArray + from pandas._libs.missing import NAType + from pandas.core.dtypes.dtypes import BaseMaskedDtype + + from anndata.compat import ZarrGroup + + from ...compat import Index1DNorm + + if TYPE_CHECKING: # Double nesting so Sphinx can import the parent block + from xarray.core.extension_array import PandasExtensionArray + from xarray.core.indexing import ExplicitIndexer + + +K = TypeVar("K", H5Array | H5AsStrView | H5AsTypeView, ZarrArray) + + +class ZarrOrHDF5Wrapper(XZarrArrayWrapper, Generic[K]): + def __init__(self, array: K) -> None: + # AstypeView from h5py .astype() lacks chunks attribute + self.chunks = getattr(array, "chunks", None) + if isinstance(array, ZarrArray): + super().__init__(array) + return + self._array = array + self.shape = self._array.shape + self.dtype = self._array.dtype + + def __getitem__(self, key: ExplicitIndexer): + from xarray.core.indexing import IndexingSupport, explicit_indexing_adapter + + if isinstance(self._array, ZarrArray): + return super().__getitem__(key) + res = explicit_indexing_adapter( + key, self.shape, IndexingSupport.OUTER_1VECTOR, self._getitem + ) + return res + + def _getitem(self, key: tuple[int | np.integer | slice | np.ndarray]): + if not isinstance(key, tuple): + msg = f"`xr.core.indexing.explicit_indexing_adapter` should have produced a tuple, got {type(key)} instead" + raise ValueError(msg) + if (n_key_dims := len(key)) != 1: + msg = f"Backed arrays currently only supported in 1d, got {n_key_dims} dims" + raise ValueError(msg) + key = key[0] + # See https://github.com/h5py/h5py/issues/293 for why we need to convert. + # See https://github.com/pydata/xarray/blob/fa03b5b4ae95a366f6de5b60f5cc4eb801cd51ec/xarray/core/indexing.py#L1259-L1263 + # for why we can expect sorted/deduped indexers (which are needed for hdf5). + if ( + isinstance(key, np.ndarray) + and np.issubdtype(key.dtype, np.integer) + and isinstance(self._array, H5Array | H5AsTypeView | H5AsStrView) + ): + key_mask = np.zeros(self._array.shape).astype("bool") + key_mask[key] = True + return self._array[key_mask] + return self._array[key] + + +class CategoricalArray(XBackendArray, Generic[K]): + """ + A wrapper class meant to enable working with lazy categorical data. + We do not guarantee the stability of this API beyond that guaranteed + by :class:`xarray.backends.BackendArray`. + """ + + _codes: ZarrOrHDF5Wrapper[K] + _categories: K + shape: tuple[int, ...] + base_path_or_zarr_group: Path | ZarrGroup + elem_name: str + + def __init__( + self, + codes: K, + categories: K, + base_path_or_zarr_group: Path | ZarrGroup, + elem_name: str, + *args, + ordered: bool, + **kwargs, + ): + self._categories = categories + self._ordered = ordered + self._codes = ZarrOrHDF5Wrapper(codes) + self.shape = self._codes.shape + self.base_path_or_zarr_group = base_path_or_zarr_group + self.file_format = "zarr" if isinstance(codes, ZarrArray) else "h5" + self.elem_name = elem_name + + @cached_property + def categories(self) -> np.ndarray: + from anndata.io import read_elem + + return read_elem(self._categories) + + def __getitem__(self, key: ExplicitIndexer) -> PandasExtensionArray: + from xarray.core.extension_array import PandasExtensionArray + + codes = self._codes[key] + categorical_array = pd.Categorical.from_codes( + codes=codes, + # casting to numpy (string) maintains our old behavior, this will be relaxed in 0.13 + categories=np.array(self.categories), + ordered=self._ordered, + ) + if settings.remove_unused_categories: + categorical_array = categorical_array.remove_unused_categories() + return PandasExtensionArray(categorical_array) + + @cached_property + def dtype(self): + return pd.CategoricalDtype(categories=self.categories, ordered=self._ordered) + + +class MaskedArray(XBackendArray, Generic[K]): + """ + A wrapper class meant to enable working with lazy masked data. + We do not guarantee the stability of this API beyond that guaranteed + by :class:`xarray.backends.BackendArray`. + """ + + _mask: ZarrOrHDF5Wrapper[K] + _values: ZarrOrHDF5Wrapper[K] + _dtype_str: Literal["nullable-integer", "nullable-boolean", "nullable-string-array"] + shape: tuple[int, ...] + base_path_or_zarr_group: Path | ZarrGroup + elem_name: str + + def __init__( + self, + values: K, + dtype_str: Literal[ + "nullable-integer", "nullable-boolean", "nullable-string-array" + ], + mask: K, + base_path_or_zarr_group: Path | ZarrGroup, + elem_name: str, + ): + self._mask = ZarrOrHDF5Wrapper(mask) + self._values = ZarrOrHDF5Wrapper(values) + self._dtype_str = dtype_str + self.shape = self._values.shape + self.base_path_or_zarr_group = base_path_or_zarr_group + self.file_format = "zarr" if isinstance(mask, ZarrArray) else "h5" + self.elem_name = elem_name + + def __getitem__( + self, key: ExplicitIndexer + ) -> PandasExtensionArray | NDArray[np.str_]: + values = self._values[key] + mask = self._mask[key] + + if isinstance(self.dtype, np.dtypes.StringDType): + # https://github.com/pydata/xarray/issues/10419 + values = values.astype(self.dtype) + values[mask] = pd.NA + return values + + from xarray.core.extension_array import PandasExtensionArray + + cls = self.dtype.construct_array_type() + return PandasExtensionArray(cls(values, mask)) + + @cached_property + def dtype(self) -> BaseMaskedDtype | np.dtypes.StringDType[NAType]: + if self._dtype_str == "nullable-string-array": + # https://github.com/pydata/xarray/issues/10419 + return NULLABLE_NUMPY_STRING_TYPE + try: + return pandas_nullable_dtype(self._values.dtype) + except NotImplementedError: + msg = f"Invalid dtype_str {self._dtype_str}" + raise RuntimeError(msg) from None + + +@_subset.register(XDataArray) +def _subset_masked( + a: XDataArray, subset_idx: tuple[Index1DNorm] | tuple[Index1DNorm, Index1DNorm] +): + return a[subset_idx] + + +@as_view.register(XDataArray) +def _view_pd_boolean_array(a: XDataArray, view_args): + return a + + +@get_chunksize.register(MaskedArray) +def _(a: MaskedArray): + return get_chunksize(a._values) + + +@get_chunksize.register(CategoricalArray) +def _(a: CategoricalArray): + return get_chunksize(a._codes) diff --git a/.venv/lib/python3.11/site-packages/anndata/experimental/merge.py b/.venv/lib/python3.11/site-packages/anndata/experimental/merge.py new file mode 100644 index 0000000000000000000000000000000000000000..c4e1dd716332e17f2370aa860fef952b82c9fc39 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/anndata/experimental/merge.py @@ -0,0 +1,762 @@ +from __future__ import annotations + +import shutil +from collections.abc import Mapping +from contextlib import ExitStack, contextmanager +from functools import singledispatch +from os import PathLike +from pathlib import Path +from typing import TYPE_CHECKING + +import numpy as np +import pandas as pd +from scipy.sparse import csc_matrix, csr_matrix + +from .._core.file_backing import to_memory +from .._core.merge import ( + MissingVal, + _resolve_axis, + concat_arrays, + gen_inner_reindexers, + gen_reindexer, + intersect_keys, + merge_dataframes, + merge_indices, + resolve_merge_strategy, + unify_dtypes, +) +from .._core.sparse_dataset import BaseCompressedSparseDataset, sparse_dataset +from .._io.specs import read_elem, write_elem +from ..compat import H5Array, H5Group, ZarrArray, ZarrGroup +from . import read_dispatched, read_elem_lazy + +if TYPE_CHECKING: + from collections.abc import Callable, Collection, Generator, Iterable, Sequence + from typing import Any, Literal + + from .._core.merge import Reindexer, StrategiesLiteral + from .._types import Join_T + +SPARSE_MATRIX = {"csc_matrix", "csr_matrix"} + +EAGER_TYPES = {"dataframe", "awkward-array"} + + +################### +# Utilities +################### + + +# Wrapper to reindexer that stores if there is a change +# and won't do anything if there is +class IdentityReindexer: + def __init__(self): + self.no_change = True + + def __call__(self, x, *args, **kwargs): + return x + + +# Checks if given indices are equal to each other in the whole list. +def _indices_equal(indices: Iterable[pd.Index]) -> bool: + init_elem = indices[0] + return all(np.array_equal(init_elem, elem) for elem in indices[1:]) + + +def _gen_slice_to_append( + datasets: Sequence[BaseCompressedSparseDataset], + reindexers, + max_loaded_elems: int, + axis=0, + fill_value=None, +): + for ds, ri in zip(datasets, reindexers, strict=False): + n_slices = ds.shape[axis] * ds.shape[1 - axis] // max_loaded_elems + if n_slices < 2: + yield (csr_matrix, csc_matrix)[axis]( + ri(to_memory(ds), axis=1 - axis, fill_value=fill_value) + ) + else: + slice_size = max_loaded_elems // ds.shape[1 - axis] + if slice_size == 0: + slice_size = 1 + rem_slices = ds.shape[axis] + idx = 0 + while rem_slices > 0: + ds_part = None + if axis == 0: + ds_part = ds[idx : idx + slice_size, :] + elif axis == 1: + ds_part = ds[:, idx : idx + slice_size] + + yield (csr_matrix, csc_matrix)[axis]( + ri(ds_part, axis=1 - axis, fill_value=fill_value) + ) + rem_slices -= slice_size + idx += slice_size + + +################### +# File Management +################### + + +@singledispatch +@contextmanager +def as_group(store, *, mode: str) -> Generator[ZarrGroup | H5Group]: + msg = "This is not yet implemented." + raise NotImplementedError(msg) + + +@as_group.register(PathLike) +@as_group.register(str) +@contextmanager +def _(store: PathLike[str] | str, *, mode: str) -> Generator[ZarrGroup | H5Group]: + store = Path(store) + if store.suffix == ".h5ad": + import h5py + + f = h5py.File(store, mode=mode) + try: + yield f + finally: + f.close() + + elif mode == "r": # others all write: r+, a, w, w- + import zarr + + yield zarr.open_group(store, mode=mode) + else: + from anndata._io.zarr import open_write_group + + yield open_write_group(store, mode=mode) + + +@as_group.register(ZarrGroup) +@as_group.register(H5Group) +@contextmanager +def _(store: ZarrGroup | H5Group, *, mode: str) -> Generator[ZarrGroup | H5Group]: + del mode + yield store + + +################### +# Reading +################### + + +def read_as_backed(group: ZarrGroup | H5Group): + """ + Read the group until + BaseCompressedSparseDataset, Array or EAGER_TYPES are encountered. + """ + + def callback(func, elem_name: str, elem, iospec): + if iospec.encoding_type in SPARSE_MATRIX: + return sparse_dataset(elem) + elif iospec.encoding_type in EAGER_TYPES: + return read_elem(elem) + elif iospec.encoding_type == "array": + return elem + elif iospec.encoding_type == "dict": + return {k: read_as_backed(v) for k, v in dict(elem).items()} + else: + return func(elem) + + return read_dispatched(group, callback=callback) + + +def _df_index(df: ZarrGroup | H5Group) -> pd.Index: + index_key = df.attrs["_index"] + return pd.Index(read_elem(df[index_key])) + + +################### +# Writing +################### + + +def write_concat_dense( # noqa: PLR0917 + arrays: Sequence[ZarrArray | H5Array], + output_group: ZarrGroup | H5Group, + output_path: ZarrGroup | H5Group, + axis: Literal[0, 1] = 0, + reindexers: Reindexer | None = None, + fill_value: Any = None, +): + """ + Writes the concatenation of given dense arrays to disk using dask. + """ + import dask.array as da + + darrays = ( + da.from_array(a, chunks="auto" if a.chunks is None else a.chunks) + for a in arrays + ) + + res = da.concatenate( + [ + ri(a, axis=1 - axis, fill_value=fill_value) + for a, ri in zip(darrays, reindexers, strict=False) + ], + axis=axis, + ) + write_elem(output_group, output_path, res) + output_group[output_path].attrs.update({ + "encoding-type": "array", + "encoding-version": "0.2.0", + }) + + +def write_concat_sparse( # noqa: PLR0917 + datasets: Sequence[BaseCompressedSparseDataset], + output_group: ZarrGroup | H5Group, + output_path: ZarrGroup | H5Group, + max_loaded_elems: int, + axis: Literal[0, 1] = 0, + reindexers: Reindexer | None = None, + fill_value: Any = None, +): + """ + Writes and concatenates sparse datasets into a single output dataset. + + Args: + datasets (Sequence[BaseCompressedSparseDataset]): A sequence of BaseCompressedSparseDataset objects to be concatenated. + output_group (Union[ZarrGroup, H5Group]): The output group where the concatenated dataset will be written. + output_path (Union[ZarrGroup, H5Group]): The output path where the concatenated dataset will be written. + max_loaded_elems (int): The maximum number of sparse elements to load at once. + axis (Literal[0, 1], optional): The axis along which the datasets should be concatenated. + Defaults to 0. + reindexers (Reindexer, optional): A reindexer object that defines the reindexing operation to be applied. + Defaults to None. + fill_value (Any, optional): The fill value to use for missing elements. Defaults to None. + """ + elems = None + if all(ri.no_change for ri in reindexers): + elems = iter(datasets) + else: + elems = _gen_slice_to_append( + datasets, reindexers, max_loaded_elems, axis, fill_value + ) + number_non_zero = sum(d.group["indices"].shape[0] for d in datasets) + init_elem = next(elems) + indptr_dtype = "int64" if number_non_zero >= np.iinfo(np.int32).max else "int32" + write_elem( + output_group, + output_path, + init_elem, + dataset_kwargs=dict(indptr_dtype=indptr_dtype), + ) + del init_elem + out_dataset: BaseCompressedSparseDataset = read_as_backed(output_group[output_path]) + for temp_elem in elems: + out_dataset.append(temp_elem) + del temp_elem + + +def _write_concat_mappings( # noqa: PLR0913, PLR0917 + mappings: Collection[dict], + output_group: ZarrGroup | H5Group, + keys: Collection[str], + output_path: str | Path, + max_loaded_elems: int, + axis: Literal[0, 1] = 0, + index: pd.Index = None, + reindexers: list[Reindexer] | None = None, + fill_value: Any = None, +): + """ + Write a list of mappings to a zarr/h5 group. + """ + mapping_group = output_group.create_group(output_path) + mapping_group.attrs.update({ + "encoding-type": "dict", + "encoding-version": "0.1.0", + }) + for k in keys: + elems = [m[k] for m in mappings] + _write_concat_sequence( + elems, + output_group=mapping_group, + output_path=k, + axis=axis, + index=index, + reindexers=reindexers, + fill_value=fill_value, + max_loaded_elems=max_loaded_elems, + ) + + +def _write_concat_arrays( # noqa: PLR0913, PLR0917 + arrays: Sequence[ZarrArray | H5Array | BaseCompressedSparseDataset], + output_group: ZarrGroup | H5Group, + output_path: str | Path, + max_loaded_elems: int, + axis: Literal[0, 1] = 0, + reindexers: list[Reindexer] | None = None, + fill_value: Any = None, + join: Literal["inner", "outer"] = "inner", +): + init_elem = arrays[0] + init_type = type(init_elem) + if not all(isinstance(a, init_type) for a in arrays): + msg = f"All elements must be the same type instead got types: {[type(a) for a in arrays]}" + raise NotImplementedError(msg) + + if reindexers is None: + if join == "inner": + reindexers = gen_inner_reindexers(arrays, new_index=None, axis=axis) + else: + msg = "Cannot reindex arrays with outer join." + raise NotImplementedError(msg) + + if isinstance(init_elem, BaseCompressedSparseDataset): + expected_sparse_fmt = ["csr", "csc"][axis] + if all(a.format == expected_sparse_fmt for a in arrays): + write_concat_sparse( + arrays, + output_group, + output_path, + max_loaded_elems, + axis, + reindexers, + fill_value, + ) + else: + msg = f"Concat of following not supported: {[a.format for a in arrays]}" + raise NotImplementedError(msg) + else: + write_concat_dense( + arrays, output_group, output_path, axis, reindexers, fill_value + ) + + +def _write_concat_sequence( # noqa: PLR0913, PLR0917 + arrays: Sequence[pd.DataFrame | BaseCompressedSparseDataset | H5Array | ZarrArray], + output_group: ZarrGroup | H5Group, + output_path: str | Path, + max_loaded_elems: int, + axis: Literal[0, 1] = 0, + index: pd.Index = None, + reindexers: list[Reindexer] | None = None, + fill_value: Any = None, + join: Literal["inner", "outer"] = "inner", +): + """ + array, dataframe, csc_matrix, csc_matrix + """ + if any(isinstance(a, pd.DataFrame) for a in arrays): + if reindexers is None: + if join == "inner": + reindexers = gen_inner_reindexers(arrays, None, axis=axis) + else: + msg = "Cannot reindex dataframes with outer join." + raise NotImplementedError(msg) + if not all( + isinstance(a, pd.DataFrame) or a is MissingVal or 0 in a.shape + for a in arrays + ): + msg = "Cannot concatenate a dataframe with other array types." + raise NotImplementedError(msg) + df = concat_arrays( + arrays=arrays, + reindexers=reindexers, + axis=axis, + index=index, + fill_value=fill_value, + ) + write_elem(output_group, output_path, df) + elif all( + isinstance(a, pd.DataFrame | BaseCompressedSparseDataset | H5Array | ZarrArray) + for a in arrays + ): + _write_concat_arrays( + arrays, + output_group, + output_path, + max_loaded_elems, + axis, + reindexers, + fill_value, + join, + ) + else: + msg = f"Concatenation of these types is not yet implemented: {[type(a) for a in arrays]} with axis={axis}." + raise NotImplementedError(msg) + + +def _write_alt_mapping( + groups: Collection[H5Group, ZarrGroup], + output_group: ZarrGroup | H5Group, + alt_axis_name: Literal["obs", "var"], + merge: Callable, + reindexers: list[Reindexer], +): + alt_mapping = merge([ + {k: r(read_elem(v), axis=0) for k, v in dict(g[f"{alt_axis_name}m"]).items()} + for r, g in zip(reindexers, groups, strict=True) + ]) + write_elem(output_group, f"{alt_axis_name}m", alt_mapping) + + +def _write_alt_annot( + groups: Collection[H5Group, ZarrGroup], + output_group: ZarrGroup | H5Group, + alt_axis_name: Literal["obs", "var"], + alt_indices: pd.Index, + merge: Callable, +): + # Annotation for other axis + alt_annot = merge_dataframes( + [read_elem(g[alt_axis_name]) for g in groups], alt_indices, merge + ) + write_elem(output_group, alt_axis_name, alt_annot) + + +def _write_axis_annot( # noqa: PLR0917 + groups: Collection[H5Group, ZarrGroup], + output_group: ZarrGroup | H5Group, + axis_name: Literal["obs", "var"], + concat_indices: pd.Index, + label: str, + label_col: str, + join: Literal["inner", "outer"], +): + concat_annot = pd.concat( + unify_dtypes(read_elem(g[axis_name]) for g in groups), + join=join, + ignore_index=True, + ) + concat_annot.index = concat_indices + if label is not None: + concat_annot[label] = label_col + write_elem(output_group, axis_name, concat_annot) + + +def _write_alt_pairwise( + groups: Collection[H5Group, ZarrGroup], + output_group: ZarrGroup | H5Group, + alt_axis_name: Literal["obs", "var"], + merge: Callable, + reindexers: list[Reindexer], +): + alt_pairwise = merge([ + { + k: r(r(read_elem_lazy(v), axis=0), axis=1) + for k, v in dict(g[f"{alt_axis_name}p"]).items() + } + for r, g in zip(reindexers, groups, strict=True) + ]) + write_elem(output_group, f"{alt_axis_name}p", alt_pairwise) + + +def concat_on_disk( # noqa: PLR0913 + in_files: Collection[PathLike[str] | str | H5Group | ZarrGroup] + | Mapping[str, PathLike[str] | str | H5Group | ZarrGroup], + out_file: PathLike[str] | str | H5Group | ZarrGroup, + *, + max_loaded_elems: int = 100_000_000, + axis: Literal["obs", 0, "var", 1] = 0, + join: Literal["inner", "outer"] = "inner", + merge: StrategiesLiteral | Callable[[Collection[Mapping]], Mapping] | None = None, + uns_merge: ( + StrategiesLiteral | Callable[[Collection[Mapping]], Mapping] | None + ) = None, + label: str | None = None, + keys: Collection[str] | None = None, + index_unique: str | None = None, + fill_value: Any | None = None, + pairwise: bool = False, +) -> None: + """\ + Concatenates multiple AnnData objects along a specified axis using their + corresponding stores or paths, and writes the resulting AnnData object + to a target location on disk. + + Unlike :func:`anndata.concat`, this method does not require + loading the input AnnData objects into memory, + making it a memory-efficient alternative for large datasets. + The resulting object written to disk should be equivalent + to the concatenation of the loaded AnnData objects using + :func:`anndata.concat`. + + To adjust the maximum amount of data loaded in memory; for sparse + arrays use the max_loaded_elems argument; for dense arrays + see the Dask documentation, as the Dask concatenation function is used + to concatenate dense arrays in this function + + Params + ------ + in_files + The corresponding stores or paths of AnnData objects to + be concatenated. If a Mapping is passed, keys are used for the `keys` + argument and values are concatenated. + out_file + The target path or store to write the result in. + max_loaded_elems + The maximum number of elements to load in memory when concatenating + sparse arrays. Note that this number also includes the empty entries. + Set to 100m by default meaning roughly 400mb will be loaded + to memory simultaneously. + axis + Which axis to concatenate along. + join + How to align values when concatenating. If `"outer"`, the union of the other axis + is taken. If `"inner"`, the intersection. See :doc:`concatenation <../concatenation>` + for more. + merge + How elements not aligned to the axis being concatenated along are selected. + Currently implemented strategies include: + + * `None`: No elements are kept. + * `"same"`: Elements that are the same in each of the objects. + * `"unique"`: Elements for which there is only one possible value. + * `"first"`: The first element seen at each from each position. + * `"only"`: Elements that show up in only one of the objects. + uns_merge + How the elements of `.uns` are selected. Uses the same set of strategies as + the `merge` argument, except applied recursively. + label + Column in axis annotation (i.e. `.obs` or `.var`) to place batch information in. + If it's None, no column is added. + keys + Names for each object being added. These values are used for column values for + `label` or appended to the index if `index_unique` is not `None`. Defaults to + incrementing integer labels. + index_unique + Whether to make the index unique by using the keys. If provided, this + is the delimiter between `"{orig_idx}{index_unique}{key}"`. When `None`, + the original indices are kept. + fill_value + When `join="outer"`, this is the value that will be used to fill the introduced + indices. By default, sparse arrays are padded with zeros, while dense arrays and + DataFrames are padded with missing values. + pairwise + Whether pairwise elements along the concatenated dimension should be included. + This is False by default, since the resulting arrays are often not meaningful, and raises {class}`NotImplementedError` when True. + If you are interested in this feature, please open an issue. + + Notes + ----- + .. warning:: + If you use `join='outer'` this fills 0s for sparse data when + variables are absent in a batch. Use this with care. Dense data is + filled with `NaN`. + + Examples + -------- + + See :func:`anndata.concat` for the semantics. + The following examples highlight the differences this function has. + + First, let’s get some “big” datasets with a compatible ``var`` axis: + + >>> import pooch + >>> import scanpy as sc + >>> base_url = "https://datasets.cellxgene.cziscience.com" + >>> # To update hashes: pooch.retrieve(url, known_hash=None) prints the new hash + >>> def get_cellxgene_data(id_: str, hash_: str): + ... return pooch.retrieve( + ... f"{base_url}/{id_}.h5ad", + ... known_hash=hash_, + ... fname=f"{id_}.h5ad", + ... path=sc.settings.datasetdir, + ... ) + >>> path_b_cells = get_cellxgene_data( + ... 'a93eab58-3d82-4b61-8a2f-d7666dcdb7c4', + ... 'sha256:dac90fe2aa8b78aee2c1fc963104592f8eff7b873ca21d01a51a5e416734651c', + ... ) + >>> path_fetal = get_cellxgene_data( + ... 'd170ff04-6da0-4156-a719-f8e1bbefbf53', + ... 'sha256:d497eebca03533919877b6fc876e8c9d8ba063199ddc86dd9fbcb9d1d87a3622', + ... ) + + Now we can concatenate them on-disk: + + >>> import anndata as ad + >>> ad.experimental.concat_on_disk( + ... dict(b_cells=path_b_cells, fetal=path_fetal), + ... 'merged.h5ad', + ... label='dataset', + ... ) + >>> adata = ad.read_h5ad('merged.h5ad', backed=True) + >>> adata.X + CSRDataset: backend hdf5, shape (490, 15585), data_dtype float32 + >>> adata.obs['dataset'].value_counts() # doctest: +SKIP + dataset + fetal 344 + b_cells 146 + Name: count, dtype: int64 + """ + if len(in_files) == 0: + msg = "No objects to concatenate." + raise ValueError(msg) + + # Argument normalization + if pairwise: + msg = "pairwise concatenation not yet implemented" + raise NotImplementedError(msg) + + merge = resolve_merge_strategy(merge) + uns_merge = resolve_merge_strategy(uns_merge) + + if is_out_path_like := isinstance(out_file, str | PathLike): + out_file = Path(out_file) + if not out_file.parent.exists(): + msg = f"Parent directory of {out_file} does not exist." + raise FileNotFoundError(msg) + + if isinstance(in_files, Mapping): + if keys is not None: + msg = ( + "Cannot specify categories in both mapping keys and using `keys`. " + "Only specify this once." + ) + raise TypeError(msg) + keys, in_files = list(in_files.keys()), list(in_files.values()) + else: + in_files = list(in_files) + + if ( + len(in_files) == 1 + and isinstance(in_file := in_files[0], str | PathLike) + and is_out_path_like + ): + (shutil.copytree if in_file.is_dir() else shutil.copy2)(in_file, out_file) + return + + if keys is None: + keys = np.arange(len(in_files)).astype(str) + + axis, axis_name = _resolve_axis(axis) + _, alt_axis_name = _resolve_axis(1 - axis) + + with ExitStack() as stack, as_group(out_file, mode="w") as output_group: + groups = [stack.enter_context(as_group(f, mode="r")) for f in in_files] + _concat_on_disk_inner( + groups=groups, + output_group=output_group, + axis=axis, + axis_name=axis_name, + alt_axis_name=alt_axis_name, + keys=keys, + max_loaded_elems=max_loaded_elems, + join=join, + label=label, + index_unique=index_unique, + fill_value=fill_value, + merge=merge, + ) + + +def _concat_on_disk_inner( # noqa: PLR0913 + *, + groups: list[H5Group | ZarrGroup], + output_group: H5Group | ZarrGroup, + axis: Literal[0, 1], + axis_name: Literal["obs", "var"], + alt_axis_name: Literal["obs", "var"], + keys: np.ndarray[tuple[int], np.dtype[Any]] | Collection[str], + max_loaded_elems: int, + join: Join_T = "inner", + label: str | None, + index_unique: str | None, + fill_value: Any | None, + merge: Callable[[Collection[Mapping]], Mapping], +) -> None: + """Internal helper to minimize the amount of indented code within the context manager""" + use_reindexing = False + + alt_idxs = [_df_index(g[alt_axis_name]) for g in groups] + # All {axis_name}_names must be equal if reindexing not applied + if not _indices_equal(alt_idxs): + use_reindexing = True + + # All groups must be anndata + if not all(g.attrs.get("encoding-type") == "anndata" for g in groups): + msg = "All groups must be anndata" + raise ValueError(msg) + + # Write metadata + output_group.attrs.update({"encoding-type": "anndata", "encoding-version": "0.1.0"}) + + # Read the backed objects of Xs + Xs = [read_as_backed(g["X"]) for g in groups] + + # Label column + label_col = pd.Categorical.from_codes( + np.repeat(np.arange(len(groups)), [x.shape[axis] for x in Xs]), + categories=keys, + ) + + # Combining indexes + concat_indices = pd.concat( + [pd.Series(_df_index(g[axis_name])) for g in groups], ignore_index=True + ) + if index_unique is not None: + concat_indices = concat_indices.str.cat( + label_col.map(str, na_action="ignore"), sep=index_unique + ) + + # Resulting indices for {axis_name} and {alt_axis_name} + concat_indices = pd.Index(concat_indices) + + alt_index = merge_indices(alt_idxs, join=join) + + reindexers = None + if use_reindexing: + reindexers = [ + gen_reindexer(alt_index, alt_old_index) for alt_old_index in alt_idxs + ] + else: + reindexers = [IdentityReindexer()] * len(groups) + + # Write {axis_name} + _write_axis_annot( + groups, output_group, axis_name, concat_indices, label, label_col, join + ) + + # Write {alt_axis_name} + _write_alt_annot(groups, output_group, alt_axis_name, alt_index, merge) + + # Write {alt_axis_name}m + _write_alt_mapping(groups, output_group, alt_axis_name, merge, reindexers) + + # Write {alt_axis_name}p + _write_alt_pairwise(groups, output_group, alt_axis_name, merge, reindexers) + + # Write X + + _write_concat_arrays( + arrays=Xs, + output_group=output_group, + output_path="X", + axis=axis, + reindexers=reindexers, + fill_value=fill_value, + max_loaded_elems=max_loaded_elems, + ) + + # Write Layers and {axis_name}m + mapping_names = [ + ( + f"{axis_name}m", + concat_indices, + 0, + None if use_reindexing else [IdentityReindexer()] * len(groups), + ), + ("layers", None, axis, reindexers), + ] + for m, m_index, m_axis, m_reindexers in mapping_names: + maps = [read_as_backed(g[m]) for g in groups] + _write_concat_mappings( + maps, + output_group, + intersect_keys(maps), + m, + max_loaded_elems=max_loaded_elems, + axis=m_axis, + index=m_index, + reindexers=m_reindexers, + fill_value=fill_value, + ) diff --git a/.venv/lib/python3.11/site-packages/anndata/experimental/multi_files/__init__.py b/.venv/lib/python3.11/site-packages/anndata/experimental/multi_files/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..956ebb8d29e593f784f72748be55a45f5e8205f7 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/anndata/experimental/multi_files/__init__.py @@ -0,0 +1,5 @@ +from __future__ import annotations + +from ._anncollection import AnnCollection + +__all__ = ["AnnCollection"] diff --git a/.venv/lib/python3.11/site-packages/anndata/experimental/multi_files/__pycache__/__init__.cpython-311.pyc b/.venv/lib/python3.11/site-packages/anndata/experimental/multi_files/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..36cdd21d7e6e756a05ad7a5480c0f9e278c910d3 Binary files /dev/null and b/.venv/lib/python3.11/site-packages/anndata/experimental/multi_files/__pycache__/__init__.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/anndata/experimental/multi_files/__pycache__/_anncollection.cpython-311.pyc b/.venv/lib/python3.11/site-packages/anndata/experimental/multi_files/__pycache__/_anncollection.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f14d3967dfcd406c737616b5b175cf21bac59c40 Binary files /dev/null and b/.venv/lib/python3.11/site-packages/anndata/experimental/multi_files/__pycache__/_anncollection.cpython-311.pyc differ diff --git a/.venv/lib/python3.11/site-packages/anndata/experimental/multi_files/_anncollection.py b/.venv/lib/python3.11/site-packages/anndata/experimental/multi_files/_anncollection.py new file mode 100644 index 0000000000000000000000000000000000000000..e45561ef992e38c46fb79ecdcf66eb58021225c0 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/anndata/experimental/multi_files/_anncollection.py @@ -0,0 +1,1000 @@ +from __future__ import annotations + +import warnings +from collections.abc import Callable, Mapping +from functools import reduce +from itertools import chain, pairwise +from typing import TYPE_CHECKING + +import numpy as np +import pandas as pd +from h5py import Dataset + +from ..._core.aligned_mapping import AxisArrays +from ..._core.anndata import AnnData +from ..._core.index import _normalize_index, _normalize_indices +from ..._core.merge import concat_arrays, inner_concat_aligned_mapping +from ..._core.sparse_dataset import BaseCompressedSparseDataset +from ..._core.views import _resolve_idx +from ...compat import old_positionals + +if TYPE_CHECKING: + from collections.abc import Iterable, Sequence + from typing import Literal + + from ..._core.index import Index + +ATTRS = ["obs", "obsm", "layers"] + + +def _merge(arrs): + rxers = [lambda x, fill_value, axis: x] * len(arrs) + return concat_arrays(arrs, rxers) + + +def _select_convert(key, convert, arr=None): + key_convert = None + + if callable(convert): + key_convert = convert + elif isinstance(convert, dict) and key in convert: + key_convert = convert[key] + + if arr is not None: + return key_convert(arr) if key_convert is not None else arr + else: + return key_convert + + +def _harmonize_types(attrs_keys, adatas): + attrs_keys_types = {} + + def check_type(attr, key=None): + arrs = [] + for a in adatas: + attr_arr = getattr(a, attr) + if key is not None: + attr_arr = attr_arr[key] + arrs.append(attr_arr) + # hacky but numpy find_common_type doesn't work with categoricals + try: + dtype = _merge([arr[:1] for arr in arrs]).dtype + except ValueError: + dtype = _merge([arr[:1, :1] for arr in arrs]).dtype + return dtype + + for attr, keys in attrs_keys.items(): + if len(keys) == 0: + continue + attrs_keys_types[attr] = {} + for key in keys: + attrs_keys_types[attr][key] = check_type(attr, key) + + attrs_keys_types["X"] = check_type("X") + + return attrs_keys_types + + +class _ConcatViewMixin: + def _resolve_idx(self, oidx, vidx): + adatas_oidx = [] + reverse = None + + old_oidx = getattr(self, "oidx", None) + if old_oidx is not None: + oidx = _resolve_idx(old_oidx, oidx, self.limits[-1]) + + if isinstance(oidx, slice): + start, stop, step = oidx.indices(self.limits[-1]) + oidx = np.arange(start, stop, step) + else: + oidx = np.array([oidx]) if isinstance(oidx, int) else oidx + u_oidx = oidx + + if len(self.adatas) == 1: + return [u_oidx], oidx, vidx, reverse + + iter_limits = list(pairwise(chain([0], self.limits))) + + n_adatas_used = 0 + for lower, upper in iter_limits: + if np.any((u_oidx >= lower) & (u_oidx < upper)): + n_adatas_used += 1 + + need_reverse = ( + self.indices_strict + and n_adatas_used > 1 + and u_oidx.size > 1 + and np.any(u_oidx[:-1] > u_oidx[1:]) + ) + if need_reverse: + u_oidx, reverse = np.unique(u_oidx, return_inverse=True) + + for lower, upper in iter_limits: + mask = (u_oidx >= lower) & (u_oidx < upper) + adatas_oidx.append(u_oidx[mask] - lower if mask.any() else None) + + old_vidx = getattr(self, "vidx", None) + if old_vidx is not None: + vidx = _resolve_idx(old_vidx, vidx, self.adatas[0].n_vars) + if isinstance(vidx, int): + vidx = np.array([vidx]) + + return adatas_oidx, oidx, vidx, reverse + + +class _IterateViewMixin: + @old_positionals("axis", "shuffle", "drop_last") + def iterate_axis( + self, + batch_size: int, + *, + axis: Literal[0, 1] = 0, + shuffle: bool = False, + drop_last: bool = False, + ): + """Iterate the lazy object over an axis. + + Parameters + ---------- + batch_size + How many samples to put into a batch when iterating. + axis + The axis to iterate over. + shuffle + Set to `True` to have the indices reshuffled before iterating. + drop_last + Set to `True` to drop a batch with the length lower than `batch_size`. + """ + if axis not in {0, 1}: + msg = "Axis should be either 0 or 1." + raise ValueError(msg) + + n = self.shape[axis] + indices = np.random.permutation(n).tolist() if shuffle else list(range(n)) + + for i in range(0, n, batch_size): + idx = indices[i : min(i + batch_size, n)] + batch = self[:, idx] if axis == 1 else self[idx] + # only happens if the last batch is smaller than batch_size + if len(batch) < batch_size and drop_last: + continue + + yield batch, idx + + +class MapObsView: + def __init__( # noqa: PLR0913 + self, + attr, + adatas, + keys, + *, + adatas_oidx, + adatas_vidx=None, + convert=None, + reverse=None, + dtypes=None, + obs_names=None, + ): + self.adatas = adatas + self._keys = keys + self.adatas_oidx = adatas_oidx + self.adatas_vidx = adatas_vidx + self.attr = attr + self.convert = convert + self.reverse = reverse + self.dtypes = dtypes + self.obs_names = obs_names + + def __getitem__(self, key: str, *, use_convert: bool = True): + if self._keys is not None and key not in self._keys: + msg = f"No {key} in {self.attr} view" + raise KeyError(msg) + + arrs = [] + for i, oidx in enumerate(self.adatas_oidx): + if oidx is None: + continue + + arr = getattr(self.adatas[i], self.attr)[key] + vidx = self.adatas_vidx[i] if self.adatas_vidx is not None else None + idx = (oidx, vidx) if vidx is not None else oidx + + if isinstance(arr, pd.DataFrame): + arrs.append(arr.iloc[idx]) + else: + if vidx is not None: + idx = np.ix_(*idx) if not isinstance(idx[1], slice) else idx + arrs.append(arr.iloc[idx] if isinstance(arr, pd.Series) else arr[idx]) + + if len(arrs) > 1: + _arr = _merge(arrs) + _arr = _arr if self.reverse is None else _arr[self.reverse] + else: + _arr = arrs[0] + # what if it is a dataframe? + if self.dtypes is not None: + _arr = _arr.astype(self.dtypes[key], copy=False) + + if self.convert is not None and use_convert: + _arr = _select_convert(key, self.convert, _arr) + + return _arr + + def keys(self): + if self._keys is not None: + return self._keys + else: + return list(getattr(self.adatas[0], self.attr).keys()) + + @old_positionals("use_convert") + def to_dict(self, keys: Iterable[str] | None = None, *, use_convert=True): + dct = {} + keys = self.keys() if keys is None else keys + for key in keys: + dct[key] = self.__getitem__(key, use_convert=use_convert) + return dct + + @property + def df(self): + if self.attr != "obs": + return None + return pd.DataFrame(self.to_dict(use_convert=False), index=self.obs_names) + + def __repr__(self): + descr = f"View of {self.attr} with keys: {str(self.keys())[1:-1]}" + return descr + + +class AnnCollectionView(_ConcatViewMixin, _IterateViewMixin): + """\ + An object to access the observation attributes of `adatas` in AnnCollection. + + Created as a result of subsetting an :class:`~anndata.experimental.AnnCollection` object. + An object of this class can have `.obs`, `.obsm`, `.layers`, `.X` depending on the + results of joins in the reference AnnCollection object. + + Notes + ----- + Nothing is copied until keys of the attributes or `.X` are accessed. + """ + + def __init__(self, reference, convert, resolved_idx): + self.reference = reference + + self.indices_strict = self.reference.indices_strict + + self.adatas = self.reference.adatas + self.limits = self.reference.limits + + self.adatas_oidx, self.oidx, self.vidx, self.reverse = resolved_idx + + self.adatas_vidx = [] + + for i, vidx in enumerate(self.reference.adatas_vidx): + if vidx is None: + self.adatas_vidx.append(self.vidx) + else: + new_vidx = _resolve_idx(vidx, self.vidx, self.adatas[i].n_vars) + self.adatas_vidx.append(new_vidx) + + self._view_attrs_keys = self.reference._view_attrs_keys + self._attrs = self.reference._attrs + + self._dtypes = self.reference._dtypes + + self._layers_view, self._obsm_view, self._obs_view = None, None, None + self._X = None + + self._convert = None + self._convert_X = None + self.convert = convert + + def _lazy_init_attr(self, attr: str, *, set_vidx: bool = False): + if getattr(self, f"_{attr}_view") is not None: + return + keys = None + attr_dtypes = None + if attr in self._view_attrs_keys: + reverse = self.reverse + keys = self._view_attrs_keys[attr] + if len(keys) == 0: + return + adatas = self.adatas + adatas_oidx = self.adatas_oidx + if self._dtypes is not None: + attr_dtypes = self._dtypes[attr] + else: + reverse = None + adatas = [self.reference] + adatas_oidx = [self.oidx] + adatas_vidx = self.adatas_vidx if set_vidx else None + + attr_convert = None + if self.convert is not None: + attr_convert = _select_convert(attr, self.convert) + + obs_names = self.obs_names if attr == "obs" else None + + setattr( + self, + f"_{attr}_view", + MapObsView( + attr, + adatas, + keys, + adatas_oidx=adatas_oidx, + adatas_vidx=adatas_vidx, + convert=attr_convert, + reverse=reverse, + dtypes=attr_dtypes, + obs_names=obs_names, + ), + ) + + def _gather_X(self): + if self._X is not None: + return self._X + + Xs = [] + for i, oidx in enumerate(self.adatas_oidx): + if oidx is None: + continue + + adata = self.adatas[i] + X = adata.X + vidx = self.adatas_vidx[i] + + if isinstance(X, Dataset): + reverse = None + if oidx.size > 1 and np.any(oidx[:-1] >= oidx[1:]): + oidx, reverse = np.unique(oidx, return_inverse=True) + + # TODO: fix memory inefficient approach of X[oidx][:, vidx] + arr = X[oidx, vidx] if isinstance(vidx, slice) else X[oidx][:, vidx] + Xs.append(arr if reverse is None else arr[reverse]) + elif isinstance(X, BaseCompressedSparseDataset): + # very slow indexing with two arrays + if isinstance(vidx, slice) or len(vidx) <= 1000: + Xs.append(X[oidx, vidx]) + else: + Xs.append(X[oidx][:, vidx]) + else: + # if vidx is present it is less memory efficient + idx = oidx, vidx + idx = np.ix_(*idx) if not isinstance(vidx, slice) else idx + Xs.append(X[idx]) + + if len(Xs) > 1: + _X = _merge(Xs) + # todo: get rid of reverse for dense arrays + _X = _X if self.reverse is None else _X[self.reverse] + else: + _X = Xs[0] + if self._dtypes is not None: + _X = _X.astype(self._dtypes["X"], copy=False) + + self._X = _X + + return _X + + @property + def X(self): + """Lazy subset of data matrix. + + The data matrix formed from the `.X` attributes of the underlying `adatas`, + properly reindexed and lazily merged. + Nothing is copied until `.X` is accessed, no real concatenation of the + underlying `.X` attributes is done. + """ + # inconsistent behavior here, _X can be changed, + # but the other attributes can't be changed. + # maybe do return ... _X.copy() or _X.setflags(write=False) + + _X = self._gather_X() + + return self._convert_X(_X) if self._convert_X is not None else _X + + @property + def layers(self): + """Lazy subset of layers. + + The layers attribute formed from lazy inner join and subsetting of the `.layers` + of the underlying `adatas`. No copy is made until you access a key from `.layers`, + only the subset of the accessed key is copied. + + To get `.layers` as a dictionary, use `.layers.to_dict()`. You can also specify keys + to include in the dict `.layers.to_dict(keys=['key1', 'key2'])` and if you want + converters to be turned off when copying to dict `.layers.to_dict(use_convert=False)`. + """ + self._lazy_init_attr("layers", set_vidx=True) + return self._layers_view + + @property + def obsm(self): + """Lazy subset of multi-dimensional annotation of observations. + + Points to the `.obsm` attributes of the underlying adatas to `.obsm` of the parent + AnnCollection object depending on the `join_obsm` option of the AnnCollection object. + See the docs of :class:`~anndata.experimental.AnnCollection` for details. + Copy rules are the same as for `.layers`, i.e. everything is lazy. + + To get `.obsm` as a dictionary, use `.obsm.to_dict()`. You can also specify keys + to include in the dict `.obsm.to_dict(keys=['key1', 'key2'])` and if you want + converters to be turned off when copying to dict `.obsm.to_dict(use_convert=False)`. + """ + self._lazy_init_attr("obsm") + return self._obsm_view + + @property + def obs(self): + """Lazy suset of one-dimensional annotation of observations. + + Points to the `.obs` attributes of the underlying adatas to `.obs` of the parent + AnnCollection object depending on the `join_obs` option of the AnnCollection object. + See the docs of `~anndata.experimental.AnnCollection` for details. + Copy rules are the same as for `.layers`, i.e. everything is lazy. + + To get `.obs` as a DataFrame, use `.obs.df`. + To get `.obs` as a dictionary, use `.obs.to_dict()`. You can also specify keys + to include in the dict `.obs.to_dict(keys=['key1', 'key2'])` and if you want + converters to be turned off when copying to dict `.obs.to_dict(use_convert=False)`. + """ + self._lazy_init_attr("obs") + return self._obs_view + + @property + def obs_names(self): + """Names of observations of this subset object.""" + return self.reference.obs_names[self.oidx] + + @property + def var_names(self): + """Names of variables of this subset object.""" + return self.reference.var_names[self.vidx] + + @property + def shape(self): + """Shape of the lazily concatenated subset of the data matrix.""" + return len(self.obs_names), len(self.var_names) + + @property + def n_obs(self): + """Number of observations.""" + return self.shape[0] + + @property + def n_vars(self): + """Number of variables/features.""" + return self.shape[1] + + @property + def convert(self): + """On the fly converters for keys of attributes and data matrix. + + A function or a Mapping of functions which will be applied + to the values of attributes (`.X`) or to specific keys of these attributes + (`.obs`, `.obsm`, `.layers`). + The keys of the Mapping should correspond to the attributes or keys of the + attributes (hierarchically) and the values should be functions used for conversion. + + Examples + ---------- + :: + + { + # densify .X + "X": lambda a: a.toarray() if issparse(a) else a, + # change dtype for all keys of .obsm + "obsm": lambda a: np.asarray(a, dtype="float32"), + # change type only for one key of .obs + "obs": dict(key1=lambda c: c.astype("string")), + } + """ + return self._convert + + @convert.setter + def convert(self, value): + self._convert = value + self._convert_X = _select_convert("X", self._convert) + for attr in ATTRS: + setattr(self, f"_{attr}_view", None) + + def __len__(self): + return len(self.obs_names) + + def __getitem__(self, index: Index): + oidx, vidx = _normalize_indices(index, self.obs_names, self.var_names) + resolved_idx = self._resolve_idx(oidx, vidx) + + return AnnCollectionView(self.reference, self.convert, resolved_idx) + + @property + def has_backed(self): + """`True` if the current subset of `adatas` has backed objects, `False` otherwise.""" + for i, adata in enumerate(self.adatas): + if adata.isbacked and self.adatas_oidx[i] is not None: + return True + return False + + def __repr__(self): + n_obs, n_vars = self.shape + descr = f"AnnCollectionView object with n_obs × n_vars = {n_obs} × {n_vars}" + all_attrs_keys = self._view_attrs_keys.copy() + for attr in self._attrs: + all_attrs_keys[attr] = list(getattr(self.reference, attr).keys()) + for attr, keys in all_attrs_keys.items(): + if len(keys) > 0: + descr += f"\n {attr}: {str(keys)[1:-1]}" + return descr + + @old_positionals("ignore_X", "ignore_layers") + def to_adata(self, *, ignore_X: bool = False, ignore_layers: bool = False): + """Convert this AnnCollectionView object to an AnnData object. + + Parameters + ---------- + ignore_X + if `True`, adds `.X` to the AnnData object. + ignore_layers + if `True`, copies `.layers` to the AnnData object. + """ + if ignore_layers or self.layers is None: + layers = None + else: + layers = self.layers.to_dict(use_convert=False) + obsm = None if self.obsm is None else self.obsm.to_dict(use_convert=False) + obs = ( + None + if self.obs is None + else pd.DataFrame(self.obs.to_dict(use_convert=False)) + ) + + if ignore_X: + X = None + shape = self.shape + else: + X = self._gather_X() + shape = None + + adata = AnnData(X, obs=obs, obsm=obsm, layers=layers, shape=shape) + adata.obs_names = self.obs_names + adata.var_names = self.var_names + return adata + + @property + def attrs_keys(self): + """Dict of all accessible attributes and their keys.""" + return self.reference.attrs_keys + + +DictCallable = dict[str, Callable] +ConvertType = Callable | dict[str, Callable | DictCallable] + + +class AnnCollection(_ConcatViewMixin, _IterateViewMixin): + """\ + Lazily concatenate AnnData objects along the `obs` axis. + + This class doesn't copy data from underlying AnnData objects, but lazily subsets using a joint + index of observations and variables. It also allows on-the-fly application of prespecified + converters to `.obs` attributes of the AnnData objects. + + Subsetting of this object returns an `AnnCollectionView`, which provides views of `.obs`, + `.obsm`, `.layers`, `.X` from the underlying AnnData objects. + + Parameters + ---------- + adatas + The objects to be lazily concatenated. + If a Mapping is passed, keys are used for the `keys` argument and values are concatenated. + join_obs + If "inner" specified all `.obs` attributes from `adatas` will be inner joined + and copied to this object. + If "outer" specified all `.obsm` attributes from `adatas` will be outer joined + and copied to this object. + For "inner" and "outer" subset objects will access `.obs` of this object, + not the original `.obs` attributes of `adatas`. + If `None`, nothing is copied to this object's `.obs`, a subset object will directly + access `.obs` attributes of `adatas` (with proper reindexing and dtype conversions). + For `None`the inner join rule is used to select columns of `.obs` of `adatas`. + join_obsm + If "inner" specified all `.obsm` attributes from `adatas` will be inner joined + and copied to this object. Subset objects will access `.obsm` of this object, + not the original `.obsm` attributes of `adatas`. + If `None`, nothing is copied to this object's `.obsm`, a subset object will directly + access `.obsm` attributes of `adatas` (with proper reindexing and dtype conversions). + For both options the inner join rule for the underlying `.obsm` attributes is used. + join_vars + Specify how to join `adatas` along the var axis. If `None`, assumes all `adatas` + have the same variables. If "inner", the intersection of all variables in + `adatas` will be used. + label + Column in `.obs` to place batch information in. + If it's None, no column is added. + keys + Names for each object being added. These values are used for column values for + `label` or appended to the index if `index_unique` is not `None`. Defaults to + incrementing integer labels. + index_unique + Whether to make the index unique by using the keys. If provided, this + is the delimiter between "{orig_idx}{index_unique}{key}". When `None`, + the original indices are kept. + convert + You can pass a function or a Mapping of functions which will be applied + to the values of attributes (`.obs`, `.obsm`, `.layers`, `.X`) or to specific + keys of these attributes in the subset object. + Specify an attribute and a key (if needed) as keys of the passed Mapping + and a function to be applied as a value. + harmonize_dtypes + If `True`, all retrieved arrays from subset objects will have the same dtype. + indices_strict + If `True`, arrays from the subset objects will always have the same order + of indices as in selection used to subset. + This parameter can be set to `False` if the order in the returned arrays + is not important, for example, when using them for stochastic gradient descent. + In this case the performance of subsetting can be a bit better. + + Examples + ---------- + >>> from scanpy.datasets import pbmc68k_reduced, pbmc3k_processed + >>> adata1, adata2 = pbmc68k_reduced(), pbmc3k_processed() + >>> adata1.shape + (700, 765) + >>> adata2.shape + (2638, 1838) + >>> dc = AnnCollection([adata1, adata2], join_vars='inner') + >>> dc + AnnCollection object with n_obs × n_vars = 3338 × 208 + constructed from 2 AnnData objects + view of obsm: 'X_pca', 'X_umap' + obs: 'n_genes', 'percent_mito', 'n_counts', 'louvain' + >>> batch = dc[100:200] # AnnCollectionView + >>> batch + AnnCollectionView object with n_obs × n_vars = 100 × 208 + obsm: 'X_pca', 'X_umap' + obs: 'n_genes', 'percent_mito', 'n_counts', 'louvain' + >>> batch.X.shape + (100, 208) + >>> len(batch.obs['louvain']) + 100 + """ + + @old_positionals( + "join_obs", + "join_obsm", + "join_vars", + "label", + "keys", + "index_unique", + "convert", + "harmonize_dtypes", + "indices_strict", + ) + def __init__( # noqa: PLR0912, PLR0913, PLR0915 + self, + adatas: Sequence[AnnData] | dict[str, AnnData], + *, + join_obs: Literal["inner", "outer"] | None = "inner", + join_obsm: Literal["inner"] | None = None, + join_vars: Literal["inner"] | None = None, + label: str | None = None, + keys: Sequence[str] | None = None, + index_unique: str | None = None, + convert: ConvertType | None = None, + harmonize_dtypes: bool = True, + indices_strict: bool = True, + ): + if isinstance(adatas, Mapping): + if keys is not None: + msg = ( + "Cannot specify categories in both mapping keys and using `keys`. " + "Only specify this once." + ) + raise TypeError(msg) + keys, adatas = list(adatas.keys()), list(adatas.values()) + else: + adatas = list(adatas) + + # check if the variables are the same in all adatas + self.adatas_vidx = [None for adata in adatas] + vars_names_list = [adata.var_names for adata in adatas] + vars_eq = all(adatas[0].var_names.equals(vrs) for vrs in vars_names_list[1:]) + if vars_eq: + self.var_names = adatas[0].var_names + elif join_vars == "inner": + var_names = reduce(pd.Index.intersection, vars_names_list) + self.adatas_vidx = [] + for adata in adatas: + if var_names.equals(adata.var_names): + self.adatas_vidx.append(None) + else: + adata_vidx = _normalize_index(var_names, adata.var_names) + self.adatas_vidx.append(adata_vidx) + self.var_names = var_names + else: + msg = ( + "Adatas have different variables. " + "Please specify join_vars='inner' for intersection." + ) + raise ValueError(msg) + + concat_indices = pd.concat( + [pd.Series(a.obs_names) for a in adatas], ignore_index=True + ) + if keys is None: + keys = np.arange(len(adatas)).astype(str) + label_col = pd.Categorical.from_codes( + np.repeat(np.arange(len(adatas)), [a.shape[0] for a in adatas]), + categories=keys, + ) + if index_unique is not None: + concat_indices = concat_indices.str.cat( + label_col.map(str, na_action="ignore"), sep=index_unique + ) + self.obs_names = pd.Index(concat_indices) + + if not self.obs_names.is_unique: + msg = "Observation names are not unique." + warnings.warn(msg, UserWarning, stacklevel=2) + + view_attrs = ATTRS.copy() + + self._attrs = [] + # process obs joins + if join_obs is not None: + view_attrs.remove("obs") + self._attrs.append("obs") + concat_annot = pd.concat( + [a.obs for a in adatas], join=join_obs, ignore_index=True + ) + concat_annot.index = self.obs_names + self._obs = concat_annot + else: + self._obs = pd.DataFrame(index=self.obs_names) + + if label is not None: + self._obs[label] = label_col + + # process obsm inner join + self._obsm = None + if join_obsm == "inner": + view_attrs.remove("obsm") + self._attrs.append("obsm") + self._obsm = inner_concat_aligned_mapping( + [a.obsm for a in adatas], index=self.obs_names + ) + self._obsm = ( + AxisArrays(self, axis=0, store={}) if self._obsm == {} else self._obsm + ) + + # process inner join of views + self._view_attrs_keys = {} + for attr in view_attrs: + self._view_attrs_keys[attr] = list(getattr(adatas[0], attr).keys()) + + for a in adatas[1:]: + for attr, keys in self._view_attrs_keys.items(): + ai_attr = getattr(a, attr) + a0_attr = getattr(adatas[0], attr) + new_keys = [] + for key in keys: + if key in ai_attr: + a0_ashape = a0_attr[key].shape + ai_ashape = ai_attr[key].shape + if ( + len(a0_ashape) < 2 + or a0_ashape[1] == ai_ashape[1] + or attr == "layers" + ): + new_keys.append(key) + self._view_attrs_keys[attr] = new_keys + + self.adatas = adatas + + self.limits = [adatas[0].n_obs] + for i in range(len(adatas) - 1): + self.limits.append(self.limits[i] + adatas[i + 1].n_obs) + + # init converter + self._convert = convert + + self._dtypes = None + if len(adatas) > 1 and harmonize_dtypes: + self._dtypes = _harmonize_types(self._view_attrs_keys, self.adatas) + + self.indices_strict = indices_strict + + def __getitem__(self, index: Index): + oidx, vidx = _normalize_indices(index, self.obs_names, self.var_names) + resolved_idx = self._resolve_idx(oidx, vidx) + + return AnnCollectionView(self, self.convert, resolved_idx) + + @property + def convert(self): + """On the fly converters for keys of attributes and data matrix. + + A function or a Mapping of functions which will be applied + to the values of attributes (`.X`) or to specific keys of these attributes + (`.obs`, `.obsm`, `.layers`) of subset objects. The converters are not + applied to `.obs` and `.obsm` (if present) of this object, only to the attributes + of subset objects. + The keys of the Mapping should correspond to the attributes or keys of the + attributes (hierarchically) and the values should be functions used for conversion. + + Examples + -------- + :: + + { + # densify .X + "X": lambda a: a.toarray() if issparse(a) else a, + # change dtype for all keys of .obsm + "obsm": lambda a: np.asarray(a, dtype="float32"), + # change type only for one key of .obs + "obs": dict(key1=lambda c: c.astype("string")), + } + """ + return self._convert + + @convert.setter + def convert(self, value): + self._convert = value + + @property + def obs(self): + """One-dimensional annotation of observations. + + If `join_obs` was set to "inner" and "outer", subset objects' `.obs` + will point to this `.obs`; otherwise, to `.obs` of the underlying objects (`adatas`). + """ + return self._obs + + @property + def obsm(self): + """Multi-dimensional annotation of observations. + + If `join_obsm` was set to "inner", subset objects' `.obsm` + will point to this `.obsm`; otherwise, to `.obsm` of the underlying objects (`adatas`). + In the latter case, `.obsm` of this object will be `None`. + """ + return self._obsm + + @property + def shape(self): + """Shape of the lazily concatenated data matrix""" + return self.limits[-1], len(self.var_names) + + @property + def n_obs(self): + """Number of observations.""" + return self.shape[0] + + @property + def n_vars(self): + """Number of variables/features.""" + return self.shape[1] + + def __len__(self): + return self.limits[-1] + + def to_adata(self): + """Convert this AnnCollection object to an AnnData object. + + The AnnData object won't have `.X`, only `.obs` and `.obsm`. + """ + if "obs" in self._view_attrs_keys or "obsm" in self._view_attrs_keys: + concat_view = self[self.obs_names] + + if "obsm" in self._view_attrs_keys: + obsm = ( + concat_view.obsm.to_dict(use_convert=False) + if concat_view.obsm is not None + else None + ) + else: + obsm = self.obsm.copy() + + obs = self.obs.copy() + if "obs" in self._view_attrs_keys and concat_view.obs is not None: + for key, value in concat_view.obs.to_dict(use_convert=False).items(): + obs[key] = value + + adata = AnnData(X=None, obs=obs, obsm=obsm, shape=self.shape) + adata.obs_names = self.obs_names + adata.var_names = self.var_names + return adata + + def lazy_attr(self, attr, key=None): + """Get a subsettable key from an attribute (array-like) or an attribute. + + Returns a LazyAttrData object which provides subsetting over the specified + attribute (`.obs` or `.obsm`) or over a key from this attribute. + In the latter case, it acts as a lazy array. + """ + return LazyAttrData(self, attr, key) + + @property + def has_backed(self): + """`True` if `adatas` have backed AnnData objects, `False` otherwise.""" + return any(adata.isbacked for adata in self.adatas) + + @property + def attrs_keys(self): + """Dict of all accessible attributes and their keys.""" + _attrs_keys = {} + for attr in self._attrs: + keys = list(getattr(self, attr).keys()) + _attrs_keys[attr] = keys + _attrs_keys.update(self._view_attrs_keys) + return _attrs_keys + + def __repr__(self): + n_obs, n_vars = self.shape + descr = f"AnnCollection object with n_obs × n_vars = {n_obs} × {n_vars}" + descr += f"\n constructed from {len(self.adatas)} AnnData objects" + for attr, keys in self._view_attrs_keys.items(): + if len(keys) > 0: + descr += f"\n view of {attr}: {str(keys)[1:-1]}" + for attr in self._attrs: + keys = list(getattr(self, attr).keys()) + if len(keys) > 0: + descr += f"\n {attr}: {str(keys)[1:-1]}" + if "obs" in self._view_attrs_keys: + keys = list(self.obs.keys()) + if len(keys) > 0: + descr += f"\n own obs: {str(keys)[1:-1]}" + + return descr + + +class LazyAttrData(_IterateViewMixin): + def __init__(self, adset: AnnCollection, attr: str, key: str | None = None): + self.adset = adset + self.attr = attr + self.key = key + + def __getitem__(self, index): + oidx = None + vidx = None + + if isinstance(index, tuple) and self.attr in {"obs", "obsm"}: + oidx = index[0] + if len(index) > 1: + vidx = index[1] + + view = self.adset[index] if oidx is None else self.adset[oidx] + attr_arr = getattr(view, self.attr) + if self.key is not None: + attr_arr = attr_arr[self.key] + return attr_arr if vidx is None else attr_arr[:, vidx] + + @property + def shape(self): + shape = self.adset.shape + if self.attr in {"X", "layers"}: + return shape + elif self.attr == "obs": + return (shape[0],) + elif self.attr == "obsm" and self.key is not None: + return shape[0], self[:1].shape[1] + else: + return None + + @property + def ndim(self): + return len(self.shape) if self.shape is not None else 0 + + @property + def dtype(self): + _dtypes = self.adset._dtypes + if _dtypes is not None and self.attr in _dtypes: + return _dtypes[self.attr][self.key] + + attr = self[:1] + if hasattr(attr, "dtype"): + return attr.dtype + else: + return None diff --git a/.venv/lib/python3.11/site-packages/anndata/experimental/pytorch/__init__.py b/.venv/lib/python3.11/site-packages/anndata/experimental/pytorch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..36c9441fead472fd4e5c851f331e050af81a8f29 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/anndata/experimental/pytorch/__init__.py @@ -0,0 +1,5 @@ +from __future__ import annotations + +from ._annloader import AnnLoader + +__all__ = ["AnnLoader"] diff --git a/.venv/lib/python3.11/site-packages/anndata/experimental/pytorch/_annloader.py b/.venv/lib/python3.11/site-packages/anndata/experimental/pytorch/_annloader.py new file mode 100644 index 0000000000000000000000000000000000000000..7356bd122f58c28e10b1e1af67348437ee19ff3a --- /dev/null +++ b/.venv/lib/python3.11/site-packages/anndata/experimental/pytorch/_annloader.py @@ -0,0 +1,238 @@ +from __future__ import annotations + +from collections.abc import Mapping +from copy import copy +from functools import partial +from importlib.util import find_spec +from math import ceil +from typing import TYPE_CHECKING + +import numpy as np +from scipy.sparse import issparse +from scverse_misc import Deprecation, deprecated + +from ..._core.anndata import AnnData +from ...compat import old_positionals +from ..multi_files._anncollection import AnnCollection, _ConcatViewMixin + +if find_spec("torch") or TYPE_CHECKING: + import torch + from torch.utils.data import BatchSampler, DataLoader, Sampler +else: + Sampler, BatchSampler, DataLoader = object, object, object + +if TYPE_CHECKING: + from collections.abc import Callable, Generator, Sequence + from typing import TypeAlias, Union + + from scipy.sparse import spmatrix + + # need to use Union because of autodoc_mock_imports + Array: TypeAlias = Union[torch.Tensor, np.ndarray, spmatrix] # noqa: UP007 + + +# Custom sampler to get proper batches instead of joined separate indices +# maybe move to multi_files +class BatchIndexSampler(Sampler): + @old_positionals("batch_size", "shuffle", "drop_last") + def __init__( + self, + n_obs: int, + *, + batch_size: int, + shuffle: bool = False, + drop_last: bool = False, + ) -> None: + self.n_obs = n_obs + self.batch_size = batch_size if batch_size < n_obs else n_obs + self.shuffle = shuffle + self.drop_last = drop_last + + def __iter__(self) -> Generator[list[int], None, None]: + indices: list[int] + if self.shuffle: + indices = np.random.permutation(self.n_obs).tolist() + else: + indices = list(range(self.n_obs)) + + for i in range(0, self.n_obs, self.batch_size): + batch = indices[i : min(i + self.batch_size, self.n_obs)] + + # only happens if the last batch is smaller than batch_size + if len(batch) < self.batch_size and self.drop_last: + continue + + yield batch + + def __len__(self) -> int: + if self.drop_last: + length = self.n_obs // self.batch_size + else: + length = ceil(self.n_obs / self.batch_size) + + return length + + +# maybe replace use_cuda with explicit device option +def default_converter(arr: Array, *, use_cuda: bool, pin_memory: bool): + if isinstance(arr, torch.Tensor): + if use_cuda: + arr = arr.cuda() + elif pin_memory: + arr = arr.pin_memory() + elif arr.dtype.name != "category" and np.issubdtype(arr.dtype, np.number): + if issparse(arr): + arr = arr.toarray() + if use_cuda: + arr = torch.tensor(arr, device="cuda") + else: + arr = torch.tensor(arr) + arr = arr.pin_memory() if pin_memory else arr + return arr + + +def _convert_on_top( + convert: Callable[[Array], Array] | None | Mapping[str, Callable[[Array], Array]], + top_convert: Callable[[Array], Array], + attrs_keys: Sequence[str] | Mapping[str, Sequence[str]], +): + if convert is None: + new_convert = top_convert + elif callable(convert): + + def compose_convert(arr): + return top_convert(convert(arr)) + + new_convert = compose_convert + else: + new_convert = {} + for attr in attrs_keys: + if attr not in convert: + new_convert[attr] = top_convert + else: + as_ks: Sequence[str] | None + if not isinstance(attrs_keys, Mapping): + as_ks = None + else: + as_ks = attrs_keys[attr] + new_convert[attr] = _convert_on_top(convert[attr], top_convert, as_ks) + return new_convert + + +# AnnLoader has the same arguments as DataLoader, but uses BatchIndexSampler by default +@deprecated( + Deprecation("0.12.17", "Use :class:`annbatch.Loader` instead of `AnnLoader`") +) +class AnnLoader(DataLoader): + """\ + PyTorch DataLoader for AnnData objects. + + Builds DataLoader from a sequence of AnnData objects, from an + :class:`~anndata.experimental.AnnCollection` object or from an `AnnCollectionView` object. + Takes care of the required conversions. + + Parameters + ---------- + adatas + `AnnData` objects or an `AnnCollection` object from which to load the data. + batch_size + How many samples per batch to load. + shuffle + Set to `True` to have the data reshuffled at every epoch. + use_default_converter + Use the default converter to convert arrays to pytorch tensors, transfer to + the default cuda device (if `use_cuda=True`), do memory pinning (if `pin_memory=True`). + If you pass an AnnCollection object with prespecified converters, the default converter + won't overwrite these converters but will be applied on top of them. + use_cuda + Transfer pytorch tensors to the default cuda device after conversion. + Only works if `use_default_converter=True` + **kwargs + Arguments for PyTorch DataLoader. If `adatas` is not an `AnnCollection` object, then also + arguments for `AnnCollection` initialization. + """ + + @old_positionals("batch_size", "shuffle", "use_default_converter", "use_cuda") + def __init__( + self, + adatas: Sequence[AnnData] | dict[str, AnnData], + *, + batch_size: int = 1, + shuffle: bool = False, + use_default_converter: bool = True, + use_cuda: bool = False, + **kwargs, + ): + if isinstance(adatas, AnnData): + adatas = [adatas] + + if isinstance(adatas, list | tuple | dict): + join_obs = kwargs.pop("join_obs", "inner") + join_obsm = kwargs.pop("join_obsm", None) + label = kwargs.pop("label", None) + keys = kwargs.pop("keys", None) + index_unique = kwargs.pop("index_unique", None) + convert = kwargs.pop("convert", None) + harmonize_dtypes = kwargs.pop("harmonize_dtypes", True) + indices_strict = kwargs.pop("indices_strict", True) + + dataset = AnnCollection( + adatas, + join_obs=join_obs, + join_obsm=join_obsm, + label=label, + keys=keys, + index_unique=index_unique, + convert=convert, + harmonize_dtypes=harmonize_dtypes, + indices_strict=indices_strict, + ) + + elif isinstance(adatas, _ConcatViewMixin): + dataset = copy(adatas) + else: + msg = "adata should be of type AnnData or AnnCollection." + raise ValueError(msg) + + if use_default_converter: + pin_memory = kwargs.pop("pin_memory", False) + _converter = partial( + default_converter, use_cuda=use_cuda, pin_memory=pin_memory + ) + dataset.convert = _convert_on_top( + dataset.convert, _converter, dict(dataset.attrs_keys, X=[]) + ) + + has_sampler = "sampler" in kwargs + has_batch_sampler = "batch_sampler" in kwargs + + has_worker_init_fn = ( + "worker_init_fn" in kwargs and kwargs["worker_init_fn"] is not None + ) + has_workers = "num_workers" in kwargs and kwargs["num_workers"] > 0 + use_parallel = has_worker_init_fn or has_workers + + if ( + batch_size is not None + and batch_size > 1 + and not has_batch_sampler + and not use_parallel + ): + drop_last = kwargs.pop("drop_last", False) + + if has_sampler: + sampler = kwargs.pop("sampler") + sampler = BatchSampler( + sampler, batch_size=batch_size, drop_last=drop_last + ) + else: + sampler = BatchIndexSampler( + len(dataset), + batch_size=batch_size, + shuffle=shuffle, + drop_last=drop_last, + ) + + super().__init__(dataset, batch_size=None, sampler=sampler, **kwargs) + else: + super().__init__(dataset, batch_size=batch_size, shuffle=shuffle, **kwargs) diff --git a/.venv/lib/python3.11/site-packages/anndata/io.py b/.venv/lib/python3.11/site-packages/anndata/io.py new file mode 100644 index 0000000000000000000000000000000000000000..9becb3715c76c609f9513aa8c21e6aa1ec9543a3 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/anndata/io.py @@ -0,0 +1,35 @@ +from __future__ import annotations + +from ._core.sparse_dataset import sparse_dataset +from ._io.h5ad import read_h5ad, write_h5ad +from ._io.read import ( + read_csv, + read_excel, + read_hdf, + read_loom, + read_mtx, + read_text, + read_umi_tools, +) +from ._io.specs import read_elem, write_elem +from ._io.write import write_csvs, write_loom +from ._io.zarr import read_zarr, write_zarr + +__all__ = [ + "read_csv", + "read_elem", + "read_excel", + "read_h5ad", + "read_hdf", + "read_loom", + "read_mtx", + "read_text", + "read_umi_tools", + "read_zarr", + "sparse_dataset", + "write_csvs", + "write_elem", + "write_h5ad", + "write_loom", + "write_zarr", +] diff --git a/.venv/lib/python3.11/site-packages/anndata/logging.py b/.venv/lib/python3.11/site-packages/anndata/logging.py new file mode 100644 index 0000000000000000000000000000000000000000..7eb714091bb38adcc694720af3cc2f1f70a1c0ee --- /dev/null +++ b/.venv/lib/python3.11/site-packages/anndata/logging.py @@ -0,0 +1,57 @@ +from __future__ import annotations + +import logging +import os + +from .compat import old_positionals + +_previous_memory_usage = None + +anndata_logger = logging.getLogger("anndata") +# Don’t pass log messages on to logging.root and its handler +anndata_logger.propagate = False +anndata_logger.addHandler(logging.StreamHandler()) # Logs go to stderr +anndata_logger.handlers[-1].setFormatter(logging.Formatter("%(message)s")) +anndata_logger.handlers[-1].setLevel("INFO") + + +def get_logger(name: str) -> logging.Logger: + """\ + Creates a child logger that delegates to anndata_logger + instead to logging.root + """ + return anndata_logger.manager.getLogger(name) + + +def get_memory_usage() -> tuple[float, float]: + import psutil + + process = psutil.Process(os.getpid()) + try: + meminfo = process.memory_info() + except AttributeError: + meminfo = process.get_memory_info() + mem = meminfo[0] / 2**30 # output in GB + mem_diff = mem + global _previous_memory_usage # noqa: PLW0603 + if _previous_memory_usage is not None: + mem_diff = mem - _previous_memory_usage + _previous_memory_usage = mem + return mem, mem_diff + + +@old_positionals("newline") +def format_memory_usage( + mem_usage: tuple[float, float], msg: str = "", *, newline: bool = False +): + nl = "\n" if newline else "" + more = " \n... " if msg != "" else "" + mem, diff = mem_usage + return ( + f"{nl}{msg}{more}Memory usage: current {mem:.2f} GB, difference {diff:+.2f} GB" + ) + + +@old_positionals("newline") +def print_memory_usage(msg: str = "", *, newline: bool = False): + print(format_memory_usage(get_memory_usage(), msg, newline)) diff --git a/.venv/lib/python3.11/site-packages/anndata/tests/__init__.py b/.venv/lib/python3.11/site-packages/anndata/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.11/site-packages/anndata/tests/helpers.py b/.venv/lib/python3.11/site-packages/anndata/tests/helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..1196d57a035f5158bc839c2ab9ce06793191e220 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/anndata/tests/helpers.py @@ -0,0 +1,1227 @@ +from __future__ import annotations + +import itertools +import random +import warnings +from collections import Counter, defaultdict +from collections.abc import Mapping +from functools import partial, singledispatch, wraps +from importlib.util import find_spec +from string import ascii_letters +from typing import TYPE_CHECKING + +import h5py +import numpy as np +import pandas as pd +import pytest +import zarr +from pandas.api.types import is_numeric_dtype +from scipy import sparse + +from anndata import AnnData, ExperimentalFeatureWarning, Raw +from anndata._core.aligned_mapping import AlignedMappingBase +from anndata._core.sparse_dataset import BaseCompressedSparseDataset +from anndata._core.views import ArrayView +from anndata._core.xarray import Dataset2D +from anndata.compat import ( + AwkArray, + CSArray, + CSMatrix, + CupyArray, + CupyCSCMatrix, + CupyCSRMatrix, + CupySparseMatrix, + DaskArray, + XDataArray, + XDataset, + ZarrArray, + ZarrGroup, + is_zarr_v2, +) +from anndata.utils import asarray + +if TYPE_CHECKING: + from collections.abc import Callable, Collection, Iterable + from typing import Literal, TypeGuard, TypeVar + + from numpy.typing import NDArray + from zarr.abc.store import ByteRequest + from zarr.core.buffer import BufferPrototype + + from .._types import ArrayStorageType + from ..compat import Index1D + + DT = TypeVar("DT") + _SubsetFunc = Callable[[pd.Index[str], int], Index1D] + + +try: + from pandas.core.arrays.integer import IntegerDtype +except ImportError: + IntegerDtype = ( + *(pd.Int8Dtype, pd.Int16Dtype, pd.Int32Dtype, pd.Int64Dtype), + *(pd.UInt8Dtype, pd.UInt16Dtype, pd.UInt32Dtype, pd.UInt64Dtype), + ) + + +DEFAULT_KEY_TYPES = ( + sparse.csr_matrix, + np.ndarray, + pd.DataFrame, + sparse.csr_array, +) + + +DEFAULT_COL_TYPES = ( + pd.CategoricalDtype(ordered=False), + pd.CategoricalDtype(ordered=True), + np.dtype(np.int64), + np.dtype(np.float64), + np.dtype(np.uint8), + np.dtype(bool), + pd.BooleanDtype(), + pd.Int32Dtype(), + pd.UInt8Dtype(), +) + + +# Give this to gen_adata when dask array support is expected. +GEN_ADATA_DASK_ARGS = dict( + obsm_types=(*DEFAULT_KEY_TYPES, DaskArray), + varm_types=(*DEFAULT_KEY_TYPES, DaskArray), + layers_types=(*DEFAULT_KEY_TYPES, DaskArray), +) + +GEN_ADATA_NO_XARRAY_ARGS = dict( + obsm_types=(*DEFAULT_KEY_TYPES, AwkArray), varm_types=(*DEFAULT_KEY_TYPES, AwkArray) +) + + +def gen_vstr_recarray(m, n, dtype=None): + size = m * n + lengths = np.random.randint(3, 5, size) + letters = np.array(list(ascii_letters)) + gen_word = lambda l: "".join(np.random.choice(letters, l)) + arr = np.array([gen_word(l) for l in lengths]).reshape(m, n) + return pd.DataFrame(arr, columns=[gen_word(5) for i in range(n)]).to_records( + index=False, column_dtypes=dtype + ) + + +def issubdtype( + a: np.dtype | pd.api.extensions.ExtensionDtype, b: type[DT] | tuple[type[DT], ...] +) -> TypeGuard[DT]: + assert not isinstance(a, type) + if isinstance(b, tuple): + return any(issubdtype(a, t) for t in b) + if isinstance(a, pd.api.extensions.ExtensionDtype): + return isinstance(a, b) + try: + return np.issubdtype(a, b) + except TypeError: # pragma: no cover + pytest.fail(f"issubdtype can’t handle everything yet: {a} {b}") + + +def gen_random_column( # noqa: PLR0911 + n: int, dtype: np.dtype | pd.api.extensions.ExtensionDtype +) -> tuple[str, np.ndarray | pd.api.extensions.ExtensionArray]: + assert isinstance(dtype, np.dtype | pd.api.extensions.ExtensionDtype) + if issubdtype(dtype, pd.CategoricalDtype): + # TODO: Think about allowing index to be passed for n + letters = np.fromiter(iter(ascii_letters), "U1") + if n > len(letters): + letters = letters[: n // 2] # Make sure categories are repeated + key = "cat" if dtype.ordered else "cat_unordered" + return key, pd.Categorical(np.random.choice(letters, n), dtype=dtype) + if issubdtype(dtype, pd.BooleanDtype): + return ( + "nullable-bool", + pd.arrays.BooleanArray( + np.random.randint(0, 2, size=n, dtype=bool), + mask=np.random.randint(0, 2, size=n, dtype=bool), + ), + ) + if issubdtype(dtype, IntegerDtype): + name, values = gen_random_column(n, dtype.numpy_dtype) + mask = np.random.randint(0, 2, size=n, dtype=bool) + return f"nullable-{name}", pd.arrays.IntegerArray(values, mask) + if issubdtype(dtype, pd.StringDtype): + letters = np.fromiter(iter(ascii_letters), "U1") + array = pd.array(np.random.choice(letters, n), dtype=pd.StringDtype()) + array[np.random.randint(0, 2, size=n, dtype=bool)] = pd.NA + return "string", array + # if issubdtype(dtype, pd.DatetimeTZDtype): + # return "datetime", pd.to_datetime(np.random.randint(0, 1000, size=n)) + if issubdtype(dtype, np.bool_): + return "bool", np.random.randint(0, 2, size=n, dtype=dtype) + + if not issubdtype(dtype, np.number): # pragma: no cover + pytest.fail(f"Unexpected dtype: {dtype}") + + n_bits = 8 * dtype.itemsize + + if issubdtype(dtype, np.unsignedinteger): + return f"uint{n_bits}", np.random.randint(0, 255, n, dtype=dtype) + if issubdtype(dtype, np.signedinteger): + return f"int{n_bits}", np.random.randint(-50, 50, n, dtype=dtype) + if issubdtype(dtype, np.floating): + return f"float{n_bits}", np.random.random(n).astype(dtype) + + pytest.fail(f"Unexpected numeric dtype: {dtype}") # pragma: no cover + + +def gen_typed_df( + n: int, + index: pd.Index[str] | None = None, + dtypes: Collection[np.dtype | pd.api.extensions.ExtensionDtype] = DEFAULT_COL_TYPES, +): + columns = [gen_random_column(n, dtype) for dtype in dtypes] + col_names = [n for n, _ in columns] + assert len(col_names) == len(set(col_names)), "Duplicate column names generated!" + return pd.DataFrame(dict(columns), index=index) + + +def _gen_awkward_inner(shape, rng, dtype): + # the maximum length a ragged dimension can take + MAX_RAGGED_DIM_LEN = 20 + if not len(shape): + # abort condition -> no dimension left, return an actual value instead + return dtype(rng.randrange(1000)) + else: + curr_dim_len = shape[0] + if curr_dim_len is None: + # ragged dimension, set random length + curr_dim_len = rng.randrange(MAX_RAGGED_DIM_LEN) + + return [_gen_awkward_inner(shape[1:], rng, dtype) for _ in range(curr_dim_len)] + + +def gen_awkward(shape, dtype=np.int32): + """Function to generate an awkward array with random values. + + Awkward array dimensions can either be fixed-length ("regular") or variable length ("ragged") + (the first dimension is always fixed-length). + + + Parameters + ---------- + shape + shape of the array to be generated. Any dimension specified as `None` will be simulated as ragged. + """ + import awkward as ak + + if shape[0] is None: + msg = "The first dimension must be fixed-length." + raise ValueError(msg) + + rng = random.Random(123) + shape = np.array(shape) + + if np.any(shape == 0): + # use empty numpy array for fixed dimensions, then add empty singletons for ragged dimensions + var_dims = [i for i, s in enumerate(shape) if s is None] + shape = [s for s in shape if s is not None] + arr = ak.Array(np.empty(shape, dtype=dtype)) + for d in var_dims: + arr = ak.singletons(arr, axis=d - 1) + return arr + else: + lil = _gen_awkward_inner(shape, rng, dtype) + arr = ak.values_astype(AwkArray(lil), dtype) + + # make fixed-length dimensions regular + for i, d in enumerate(shape): + if d is not None: + arr = ak.to_regular(arr, i) + + return arr + + +def gen_typed_df_t2_size(m, n, index=None, columns=None) -> pd.DataFrame: + s = 0 + df = pd.DataFrame() + new_vals = gen_typed_df(m) + while s < (n / new_vals.shape[1]): + new_vals = gen_typed_df(m, index=index) + new_vals.columns = new_vals.columns + "_" + str(s) + df[new_vals.columns] = new_vals + s += 1 + df = df.iloc[:m, :n].copy() + if columns is not None: + df.columns = columns + return df + + +def maybe_add_sparse_array( + mapping: Mapping, + types: Collection[type], + format: Literal["csr", "csc"], + random_state: np.random.Generator, + shape: tuple[int, int], +): + if sparse.csr_array in types or sparse.csr_matrix in types: + mapping["sparse_array"] = sparse.csr_array( + sparse.random(*shape, format=format, random_state=random_state) + ) + return mapping + + +# TODO: Use hypothesis for this? +def gen_adata( # noqa: PLR0913 + shape: tuple[int, int], + X_type: Callable[[np.ndarray], object] = sparse.csr_matrix, + *, + X_dtype: np.dtype = np.float32, + obs_dtypes: Collection[ + np.dtype | pd.api.extensions.ExtensionDtype + ] = DEFAULT_COL_TYPES, + var_dtypes: Collection[ + np.dtype | pd.api.extensions.ExtensionDtype + ] = DEFAULT_COL_TYPES, + obs_xdataset: bool = False, + var_xdataset: bool = False, + obsm_types: Collection[type] = (*DEFAULT_KEY_TYPES, AwkArray, XDataset), + varm_types: Collection[type] = (*DEFAULT_KEY_TYPES, AwkArray, XDataset), + layers_types: Collection[type] = DEFAULT_KEY_TYPES, + random_state: np.random.Generator | None = None, + sparse_fmt: Literal["csr", "csc"] = "csr", +) -> AnnData: + """\ + Helper function to generate a random AnnData for testing purposes. + + Note: For `obsm_types`, `varm_types`, and `layers_types` these currently + just filter already created objects. + In future, these should choose which objects are created. + + Params + ------ + shape + What shape you want the anndata to be. + X_type + What kind of container should `X` be? This will be called on a randomly + generated 2d array. + X_dtype + What should the dtype of the `.X` container be? + obsm_types + What kinds of containers should be in `.obsm`? + varm_types + What kinds of containers should be in `.varm`? + layers_types + What kinds of containers should be in `.layers`? + sparse_fmt + What sparse format should be used for sparse matrices? + (csr, csc) + """ + import dask.array as da + + if random_state is None: + random_state = np.random.default_rng() + + M, N = shape + obs_names = pd.Index([f"cell{i}" for i in range(shape[0])], dtype="str") + var_names = pd.Index([f"gene{i}" for i in range(shape[1])], dtype="str") + obs = gen_typed_df(M, obs_names, dtypes=obs_dtypes) + var = gen_typed_df(N, var_names, dtypes=var_dtypes) + # For #147 + obs.rename(columns=dict(cat="obs_cat"), inplace=True) + var.rename(columns=dict(cat="var_cat"), inplace=True) + + if has_xr := find_spec("xarray"): + if obs_xdataset: + obs = XDataset.from_dataframe(obs) + if var_xdataset: + var = XDataset.from_dataframe(var) + + if X_type is None: + X = None + else: + X = X_type(random_state.binomial(100, 0.005, (M, N)).astype(X_dtype)) + + obsm = dict( + array=np.random.random((M, 50)), + sparse=sparse.random(M, 100, format=sparse_fmt, random_state=random_state), + df=gen_typed_df(M, obs_names, dtypes=obs_dtypes), + awk_2d_ragged=gen_awkward((M, None)), + da=da.random.random((M, 50)), + ) + varm = dict( + array=np.random.random((N, 50)), + sparse=sparse.random(N, 100, format=sparse_fmt, random_state=random_state), + df=gen_typed_df(N, var_names, dtypes=var_dtypes), + awk_2d_ragged=gen_awkward((N, None)), + da=da.random.random((N, 50)), + ) + if has_xr: + obsm["xdataset"] = XDataset.from_dataframe( + gen_typed_df(M, obs_names, dtypes=obs_dtypes) + ) + varm["xdataset"] = XDataset.from_dataframe( + gen_typed_df(N, var_names, dtypes=var_dtypes) + ) + obsm = {k: v for k, v in obsm.items() if type(v) in obsm_types} + obsm = maybe_add_sparse_array( + mapping=obsm, + types=obsm_types, + format=sparse_fmt, + random_state=random_state, + shape=(M, 100), + ) + varm = {k: v for k, v in varm.items() if type(v) in varm_types} + varm = maybe_add_sparse_array( + mapping=varm, + types=varm_types, + format=sparse_fmt, + random_state=random_state, + shape=(N, 100), + ) + layers = dict( + array=np.random.random((M, N)), + sparse=sparse.random(M, N, format=sparse_fmt, random_state=random_state), + da=da.random.random((M, N)), + ) + layers = maybe_add_sparse_array( + mapping=layers, + types=layers_types, + format=sparse_fmt, + random_state=random_state, + shape=(M, N), + ) + layers = {k: v for k, v in layers.items() if type(v) in layers_types} + obsp = dict( + array=np.random.random((M, M)), + sparse=sparse.random(M, M, format=sparse_fmt, random_state=random_state), + ) + obsp["sparse_array"] = sparse.csr_array( + sparse.random(M, M, format=sparse_fmt, random_state=random_state) + ) + varp = dict( + array=np.random.random((N, N)), + sparse=sparse.random(N, N, format=sparse_fmt, random_state=random_state), + ) + varp["sparse_array"] = sparse.csr_array( + sparse.random(N, N, format=sparse_fmt, random_state=random_state) + ) + uns = dict( + O_recarray=gen_vstr_recarray(N, 5), + nested=dict( + scalar_str="str", + scalar_int=42, + scalar_float=3.0, + nested_further=dict(array=np.arange(5)), + ), + awkward_regular=gen_awkward((10, 5)), + awkward_ragged=gen_awkward((12, None, None)), + df=gen_typed_df(10, index=pd.Index(list(map(str, range(10))))), + df_int_index=gen_typed_df(10, index=pd.Index(list(range(10)))), + # U_recarray=gen_vstr_recarray(N, 5, "U4") + ) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ExperimentalFeatureWarning) + adata = AnnData( + X=X, + obs=obs, + var=var, + obsm=obsm, + varm=varm, + layers=layers, + obsp=obsp, + varp=varp, + uns=uns, + ) + return adata + + +def array_bool_subset(index: pd.Index[str], min_size: int = 2) -> NDArray[np.bool_]: + b = np.zeros(len(index), dtype=bool) + selected = np.random.choice( + range(len(index)), + size=np.random.randint(min_size, len(index), ()), + replace=False, + ) + b[selected] = True + return b + + +def list_bool_subset(index: pd.Index[str], min_size: int = 2) -> list[bool]: + return array_bool_subset(index, min_size=min_size).tolist() + + +def matrix_bool_subset(index: pd.Index[str], min_size: int = 2) -> np.matrix: + with warnings.catch_warnings(): + warnings.simplefilter("ignore", PendingDeprecationWarning) + indexer = np.matrix( + array_bool_subset(index, min_size=min_size).reshape(len(index), 1) + ) + return indexer + + +def spmatrix_bool_subset(index: pd.Index[str], min_size: int = 2) -> sparse.csr_matrix: + return sparse.csr_matrix( + array_bool_subset(index, min_size=min_size).reshape(len(index), 1) + ) + + +def sparray_bool_subset(index: pd.Index[str], min_size: int = 2) -> sparse.csr_array: + return sparse.csr_array( + array_bool_subset(index, min_size=min_size).reshape(len(index), 1) + ) + + +def single_subset(index: pd.Index[str], min_size: int = 1) -> str: + if min_size > 1: + msg = "max_size must be ≤1" + raise AssertionError(msg) + return index[np.random.randint(0, len(index))] + + +def array_subset(index: pd.Index[str], min_size: int = 2) -> NDArray[np.str_]: + if len(index) < min_size: + msg = f"min_size (={min_size}) must be smaller than len(index) (={len(index)}" + raise ValueError(msg) + return np.random.choice( + index, size=np.random.randint(min_size, len(index), ()), replace=False + ) + + +def array_int_subset(index: pd.Index[str], min_size: int = 2) -> NDArray[np.int64]: + if len(index) < min_size: + msg = f"min_size (={min_size}) must be smaller than len(index) (={len(index)}" + raise ValueError(msg) + return np.random.choice( + np.arange(len(index)), + size=np.random.randint(min_size, len(index), ()), + replace=False, + ) + + +def list_int_subset(index: pd.Index[str], min_size: int = 2) -> list[int]: + return array_int_subset(index, min_size=min_size).tolist() + + +def slice_int_subset(index: pd.Index[str], min_size: int = 2) -> slice: + while True: + points = np.random.choice(np.arange(len(index) + 1), size=2, replace=False) + s = slice(*sorted(points)) + if len(range(*s.indices(len(index)))) >= min_size: + break + return s + + +def single_int_subset(index: pd.Index[str], min_size: int = 1) -> int: + if min_size > 1: + msg = "max_size must be ≤1" + raise AssertionError(msg) + return np.random.randint(0, len(index)) + + +_SUBSET_FUNCS: list[_SubsetFunc] = [ + # str (obs/var name) + single_subset, + array_subset, + # int (numeric index) + single_int_subset, + slice_int_subset, + array_int_subset, + list_int_subset, + # bool (mask) + array_bool_subset, + list_bool_subset, + matrix_bool_subset, + spmatrix_bool_subset, + sparray_bool_subset, +] + + +@pytest.fixture(params=_SUBSET_FUNCS) +def subset_func(request: pytest.FixtureRequest) -> _SubsetFunc: + return request.param + + +################### +# Checking equality +################### + + +def format_msg(elem_name: str | None) -> str: + if elem_name is not None: + return f"Error raised from element {elem_name!r}." + else: + return "" + + +# TODO: it would be better to modify the other exception +def report_name(func): + """Report name of element being tested if test fails.""" + + @wraps(func) + def func_wrapper(*args, _elem_name: str | None = None, **kwargs): + try: + return func(*args, **kwargs) + except Exception as e: + if _elem_name is not None and not hasattr(e, "_name_attached"): + msg = format_msg(_elem_name) + args = list(e.args) + if len(args) == 0: + args = [msg] + else: + args[0] = f"{args[0]}\n\n{msg}" + e.args = tuple(args) + e._name_attached = True + raise e + + return func_wrapper + + +@report_name +def _assert_equal(a, b): + """Allows reporting elem name for simple assertion.""" + assert a == b + + +@singledispatch +def assert_equal( + a: object, b: object, *, exact: bool = False, elem_name: str | None = None +): + _assert_equal(a, b, _elem_name=elem_name) + + +@assert_equal.register(CupyArray) +def assert_equal_cupy( + a: CupyArray, b: object, *, exact: bool = False, elem_name: str | None = None +): + assert_equal(b, a.get(), exact=exact, elem_name=elem_name) + + +@assert_equal.register(np.ndarray) +def assert_equal_ndarray( + a: np.ndarray, b: object, *, exact: bool = False, elem_name: str | None = None +): + b = asarray(b) + if not exact and is_numeric_dtype(a) and is_numeric_dtype(b): + assert a.shape == b.shape, format_msg(elem_name) + np.testing.assert_allclose(a, b, equal_nan=True, err_msg=format_msg(elem_name)) + elif ( # Structured dtype + not exact + and hasattr(a, "dtype") + and hasattr(b, "dtype") + and len(a.dtype) > 1 + and len(b.dtype) > 0 + ): + # Reshaping to allow >2d arrays + assert a.shape == b.shape, format_msg(elem_name) + assert_equal( + pd.DataFrame(a.reshape(-1)), + pd.DataFrame(b.reshape(-1)), + exact=exact, + elem_name=elem_name, + ) + else: + assert np.all(a == b), format_msg(elem_name) + + +@assert_equal.register(ArrayView) +def assert_equal_arrayview( + a: ArrayView, b: object, *, exact: bool = False, elem_name: str | None = None +): + assert_equal(asarray(a), asarray(b), exact=exact, elem_name=elem_name) + + +@assert_equal.register(BaseCompressedSparseDataset) +@assert_equal.register(sparse.spmatrix) +@assert_equal.register(CSArray) +def assert_equal_sparse( + a: BaseCompressedSparseDataset | sparse.spmatrix | CSArray, + b: object, + *, + exact: bool = False, + elem_name: str | None = None, +): + if exact and sparse.issparse(b) and hasattr(a, "indptr") and hasattr(b, "indptr"): + assert a.indptr.dtype == b.indptr.dtype, f"{elem_name}: indptr dtype mismatch" + assert a.indices.dtype == b.indices.dtype, ( + f"{elem_name}: indices dtype mismatch" + ) + a = asarray(a) + assert_equal(b, a, exact=exact, elem_name=elem_name) + + +@assert_equal.register(CupySparseMatrix) +def assert_equal_cupy_sparse( + a: CupySparseMatrix, b: object, *, exact: bool = False, elem_name: str | None = None +): + a = a.toarray() + assert_equal(b, a, exact=exact, elem_name=elem_name) + + +@assert_equal.register(h5py.Dataset) +@assert_equal.register(ZarrArray) +def assert_equal_h5py_dataset( + a: ArrayStorageType, b: object, *, exact: bool = False, elem_name: str | None = None +): + a = asarray(a) + assert_equal(b, a, exact=exact, elem_name=elem_name) + + +@assert_equal.register(DaskArray) +def assert_equal_dask_array( + a: DaskArray, b: object, *, exact: bool = False, elem_name: str | None = None +): + assert_equal(b, a.compute(), exact=exact, elem_name=elem_name) + + +@assert_equal.register(pd.DataFrame) +def are_equal_dataframe( + a: pd.DataFrame, b: object, *, exact: bool = False, elem_name: str | None = None +): + if not isinstance(b, pd.DataFrame): + assert_equal(b, a, exact=exact, elem_name=elem_name) # , a.values maybe? + + report_name(pd.testing.assert_frame_equal)( + a, + b, + check_exact=exact, + check_column_type=exact, + check_index_type=exact, + _elem_name=elem_name, + check_frame_type=False, + ) + + +@assert_equal.register(Dataset2D) +def are_equal_dataset2d( + a: Dataset2D, b: object, *, exact: bool = False, elem_name: str | None = None +): + a.equals(b) + + +@assert_equal.register(AwkArray) +def assert_equal_awkarray( + a: AwkArray, b: object, *, exact: bool = False, elem_name: str | None = None +): + import awkward as ak + + if exact: + assert isinstance(b, AwkArray) + assert a.type == b.type, f"{a.type} != {b.type}, {format_msg(elem_name)}" + assert ak.to_list(a) == ak.to_list(b), format_msg(elem_name) + + +@assert_equal.register(Mapping) +def assert_equal_mapping( + a: Mapping, b: object, *, exact: bool = False, elem_name: str | None = None +): + assert isinstance(b, Mapping) + assert set(a) == set(b), format_msg(elem_name) + for k in a: + if elem_name is None: + elem_name = "" + assert_equal(a[k], b[k], exact=exact, elem_name=f"{elem_name}/{k}") + + +@assert_equal.register(AlignedMappingBase) +def assert_equal_aligned_mapping( + a: AlignedMappingBase, + b: object, + *, + exact: bool = False, + elem_name: str | None = None, +): + assert isinstance(b, AlignedMappingBase) + a_indices = (a.parent.obs_names, a.parent.var_names) + b_indices = (b.parent.obs_names, b.parent.var_names) + for axis_idx in a.axes: + assert_equal( + a_indices[axis_idx], b_indices[axis_idx], exact=exact, elem_name=axis_idx + ) + assert a.attrname == b.attrname, format_msg(elem_name) + assert_equal_mapping(a, b, exact=exact, elem_name=elem_name) + + +@assert_equal.register(pd.Index) +def assert_equal_index( + a: pd.Index, b: object, *, exact: bool = False, elem_name: str | None = None +): + params = dict(check_categorical=False) if not exact else {} + report_name(pd.testing.assert_index_equal)( + a, b, check_names=False, **params, _elem_name=elem_name + ) + + +@assert_equal.register(pd.api.extensions.ExtensionArray) +def assert_equal_extension_array( + a: pd.api.extensions.ExtensionArray, + b: object, + *, + exact: bool = False, + elem_name: str | None = None, +): + report_name(pd.testing.assert_extension_array_equal)( + a, + b, + check_dtype=exact, + check_exact=exact, + _elem_name=elem_name, + ) + + +@assert_equal.register(XDataArray) +def assert_equal_xarray( + a: XDataArray, b: object, *, exact: bool = False, elem_name: str | None = None +): + report_name(a.equals)(b, _elem_name=elem_name) + + +@assert_equal.register(Raw) +def assert_equal_raw( + a: Raw, b: object, *, exact: bool = False, elem_name: str | None = None +): + def assert_is_not_none(x): # can't put an assert in a lambda + assert x is not None + + report_name(assert_is_not_none)(b, _elem_name=elem_name) + for attr in ["X", "var", "varm", "obs_names"]: + assert_equal( + getattr(a, attr), + getattr(b, attr), + exact=exact, + elem_name=f"{elem_name}/{attr}", + ) + + +@assert_equal.register(AnnData) +def assert_adata_equal( + a: AnnData, b: object, *, exact: bool = False, elem_name: str | None = None +): + """\ + Check whether two AnnData objects are equivalent, + raising an AssertionError if they aren’t. + + Params + ------ + a + b + exact + Whether comparisons should be exact or not. This has a somewhat flexible + meaning and should probably get refined in the future. + """ + + def fmt_name(x): + if elem_name is None: + return x + else: + return f"{elem_name}/{x}" + + assert isinstance(b, AnnData) + + # There may be issues comparing views, since np.allclose + # can modify ArrayViews if they contain `nan`s + assert_equal(a.obs_names, b.obs_names, exact=exact, elem_name=fmt_name("obs_names")) + assert_equal(a.var_names, b.var_names, exact=exact, elem_name=fmt_name("var_names")) + if not exact: + # Reorder all elements if necessary + idx = [slice(None), slice(None)] + # Since it’s a pain to compare a list of pandas objects + change_flag = False + if not np.all(a.obs_names == b.obs_names): + idx[0] = a.obs_names + change_flag = True + if not np.all(a.var_names == b.var_names): + idx[1] = a.var_names + change_flag = True + if change_flag: + b = b[tuple(idx)].copy() + for attr in [ + "X", + "obs", + "var", + "obsm", + "varm", + "layers", + "uns", + "obsp", + "varp", + "raw", + ]: + assert_equal( + getattr(a, attr), + getattr(b, attr), + exact=exact, + elem_name=fmt_name(attr), + ) + + +def _half_chunk_size(a: tuple[int, ...]) -> tuple[int, ...]: + def half_rounded_up(x): + div, mod = divmod(x, 2) + return div + (mod > 0) + + return tuple(half_rounded_up(x) for x in a) + + +@singledispatch +def as_dense_dask_array(a): + import dask.array as da + + a = asarray(a) + return da.asarray(a, chunks=_half_chunk_size(a.shape)) + + +@as_dense_dask_array.register(CSMatrix) +def _(a): + return as_dense_dask_array(a.toarray()) + + +@as_dense_dask_array.register(DaskArray) +def _(a): + return a.map_blocks(asarray, dtype=a.dtype, meta=np.ndarray) + + +@singledispatch +def _as_sparse_dask( + a: NDArray | CSArray | CSMatrix | DaskArray, + *, + typ: type[CSArray | CSMatrix | CupyCSRMatrix], + chunks: tuple[int, ...] | None = None, +) -> DaskArray: + """Convert a to a sparse dask array, preserving sparse format and container (`cs{rc}_{array,matrix}`).""" + raise NotImplementedError + + +@_as_sparse_dask.register(CSArray | CSMatrix | np.ndarray) +def _( + a: CSArray | CSMatrix | NDArray, + *, + typ: type[CSArray | CSMatrix | CupyCSRMatrix], + chunks: tuple[int, ...] | None = None, +) -> DaskArray: + import dask.array as da + + chunks = _half_chunk_size(a.shape) if chunks is None else chunks + return da.from_array(_as_sparse_dask_inner(a, typ=typ), chunks=chunks) + + +@_as_sparse_dask.register(DaskArray) +def _( + a: DaskArray, + *, + typ: type[CSArray | CSMatrix | CupyCSRMatrix], + chunks: tuple[int, ...] | None = None, +) -> DaskArray: + assert chunks is None # TODO: if needed we can add a .rechunk(chunks) + return a.map_blocks(_as_sparse_dask_inner, typ=typ, dtype=a.dtype, meta=typ((2, 2))) + + +def _as_sparse_dask_inner( + a: NDArray | CSArray | CSMatrix, *, typ: type[CSArray | CSMatrix | CupyCSRMatrix] +) -> CSArray | CSMatrix: + """Convert into a a sparse container that dask supports (or complain).""" + if issubclass(typ, CSArray): # convert sparray to spmatrix + msg = "AnnData doesn't support `cs_{r,c}_array` inside Dask" + raise TypeError(msg) + if issubclass(typ, CupySparseMatrix): + a = as_cupy(a) # can’t Cupy sparse constructors don’t accept numpy ndarrays + return typ(a) + + +as_sparse_dask_matrix = partial(_as_sparse_dask, typ=sparse.csr_matrix) + + +@singledispatch +def as_dense_cupy_dask_array(a): + import cupy as cp + + return as_dense_dask_array(a).map_blocks( + cp.array, meta=cp.array((1.0), dtype=a.dtype), dtype=a.dtype + ) + + +@as_dense_cupy_dask_array.register(CupyArray) +def _(a): + import cupy as cp + import dask.array as da + + return da.from_array( + a, + chunks=_half_chunk_size(a.shape), + meta=cp.array((1.0), dtype=a.dtype), + ) + + +@as_dense_cupy_dask_array.register(DaskArray) +def _(a): + import cupy as cp + + if isinstance(a._meta, cp.ndarray): + return a.copy() + return a.map_blocks( + partial(as_cupy, typ=CupyArray), + dtype=a.dtype, + meta=cp.array((1.0), dtype=a.dtype), + ) + + +try: + import cupyx.scipy.sparse as cpsparse + + format_to_memory_class = {"csr": cpsparse.csr_matrix, "csc": cpsparse.csc_matrix} +except ImportError: + format_to_memory_class = {} + + +@singledispatch +def as_cupy_sparse_dask_array(a, format="csr") -> DaskArray: + chunk_rows, _ = _half_chunk_size(a.shape) + return _as_sparse_dask( + a, typ=format_to_memory_class[format], chunks=(chunk_rows, -1) + ) + + +@as_cupy_sparse_dask_array.register(CupyArray) +@as_cupy_sparse_dask_array.register(CupySparseMatrix) +def _(a, format="csr"): + import dask.array as da + + memory_class = format_to_memory_class[format] + chunk_rows, _ = _half_chunk_size(a.shape) + return da.from_array(memory_class(a), chunks=(chunk_rows, -1)) + + +@as_cupy_sparse_dask_array.register(DaskArray) +def _(a, format="csr"): + memory_class = format_to_memory_class[format] + if isinstance(a._meta, memory_class): + return a.copy() + return a.rechunk((a.chunks[0], -1)).map_blocks( + partial(as_cupy, typ=memory_class), dtype=a.dtype + ) + + +def resolve_cupy_type(val): + input_typ = type(val) if not isinstance(val, type) else val + + if issubclass(input_typ, np.ndarray): + typ = CupyArray + elif issubclass(input_typ, sparse.csr_matrix | sparse.csr_array): + typ = CupyCSRMatrix + elif issubclass(input_typ, sparse.csc_matrix | sparse.csc_array): + typ = CupyCSCMatrix + else: + msg = f"No default target type for input type {input_typ}" + raise NotImplementedError(msg) + return typ + + +@singledispatch +def as_cupy(val, typ=None): + """ + Rough conversion function + + Will try to infer target type from input type if not specified. + """ + if typ is None: + typ = resolve_cupy_type(val) + + if issubclass(typ, CupyArray): + import cupy as cp + + if isinstance(val, CSMatrix | CSArray): + val = val.toarray() + return cp.array(val) + elif issubclass(typ, CupyCSRMatrix): + import cupy as cp + import cupyx.scipy.sparse as cpsparse + + if isinstance(val, np.ndarray): + return cpsparse.csr_matrix(cp.array(val)) + else: + return cpsparse.csr_matrix(val) + elif issubclass(typ, CupyCSCMatrix): + import cupy as cp + import cupyx.scipy.sparse as cpsparse + + if isinstance(val, np.ndarray): + return cpsparse.csc_matrix(cp.array(val)) + else: + return cpsparse.csc_matrix(val) + else: + msg = f"Conversion from {type(val)} to {typ} not implemented" + raise NotImplementedError(msg) + + +# TODO: test +@as_cupy.register(DaskArray) +def as_cupy_dask(a, typ=None): + if typ is None: + typ = resolve_cupy_type(a._meta) + return a.map_blocks(partial(as_cupy, typ=typ), dtype=a.dtype) + + +@singledispatch +def shares_memory(x, y) -> bool: + return np.shares_memory(x, y) + + +@shares_memory.register(CSMatrix) +def shares_memory_sparse(x, y): + return ( + np.shares_memory(x.data, y.data) + and np.shares_memory(x.indices, y.indices) + and np.shares_memory(x.indptr, y.indptr) + ) + + +BASE_MATRIX_PARAMS = [ + pytest.param(asarray, id="np_array"), + pytest.param(sparse.csr_matrix, id="scipy_csr_matrix"), + pytest.param(sparse.csc_matrix, id="scipy_csc_matrix"), + pytest.param(sparse.csr_array, id="scipy_csr_array"), + pytest.param(sparse.csc_array, id="scipy_csc_array"), +] + +DASK_MATRIX_PARAMS = [ + pytest.param(as_dense_dask_array, id="dense_dask_array"), + pytest.param(as_sparse_dask_matrix, id="sparse_dask_matrix"), +] + +CUPY_MATRIX_PARAMS = [ + pytest.param( + partial(as_cupy, typ=CupyArray), id="cupy_array", marks=pytest.mark.gpu + ), + pytest.param( + partial(as_cupy, typ=CupyCSRMatrix), + id="cupy_csr", + marks=pytest.mark.gpu, + ), + pytest.param( + partial(as_cupy, typ=CupyCSCMatrix), + id="cupy_csc", + marks=pytest.mark.gpu, + ), +] + +DASK_CUPY_MATRIX_PARAMS = [ + pytest.param( + as_dense_cupy_dask_array, + id="cupy_dense_dask_array", + marks=pytest.mark.gpu, + ), + pytest.param( + as_cupy_sparse_dask_array, id="cupy_csr_dask_array", marks=pytest.mark.gpu + ), +] + +if is_zarr_v2(): + from zarr.storage import DirectoryStore as LocalStore +else: + from zarr.storage import LocalStore + + +class AccessTrackingStoreBase(LocalStore): + _access_count: Counter[str] + _accessed: defaultdict[str, set] + _accessed_keys: defaultdict[str, list[str]] + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._access_count = Counter() + self._accessed = defaultdict(set) + self._accessed_keys = defaultdict(list) + + self._read_only = True + + def _check_and_track_key(self, key: str): + for tracked in self._access_count: + if tracked in key: + self._access_count[tracked] += 1 + self._accessed[tracked].add(key) + self._accessed_keys[tracked] += [key] + + def get_access_count(self, key: str) -> int: + # access defaultdict when value is not there causes key to be there, + # which causes it to be tracked + if key not in self._access_count: + msg = f"{key} not found among access count" + raise KeyError(msg) + return self._access_count[key] + + def get_subkeys_accessed(self, key: str) -> set[str]: + if key not in self._accessed: + msg = f"{key} not found among accessed" + raise KeyError(msg) + return self._accessed[key] + + def get_accessed_keys(self, key: str) -> list[str]: + if key not in self._accessed_keys: + msg = f"{key} not found among accessed keys" + raise KeyError(msg) + return self._accessed_keys[key] + + def initialize_key_trackers(self, keys_to_track: Iterable[str]) -> None: + for k in keys_to_track: + self._access_count[k] = 0 + self._accessed_keys[k] = [] + self._accessed[k] = set() + + def reset_key_trackers(self) -> None: + self.initialize_key_trackers(self._access_count.keys()) + + def assert_access_count(self, key: str, count: int) -> None: + __tracebackhide__ = True + keys_accessed = self.get_subkeys_accessed(key) + access_count = self.get_access_count(key) + assert self.get_access_count(key) == count, ( + f"Found {access_count} accesses at {keys_accessed}" + ) + + +if is_zarr_v2(): + + class AccessTrackingStore(AccessTrackingStoreBase): + def __getitem__(self, key: str) -> bytes: + self._check_and_track_key(key) + return super().__getitem__(key) + +else: + + class AccessTrackingStore(AccessTrackingStoreBase): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs, read_only=True) + + async def get( + self, + key: str, + prototype: BufferPrototype | None = None, + byte_range: ByteRequest | None = None, + ) -> object: + self._check_and_track_key(key) + return await super().get(key, prototype=prototype, byte_range=byte_range) + + +def get_multiindex_columns_df(shape: tuple[int, int]) -> pd.DataFrame: + return pd.DataFrame( + np.random.rand(shape[0], shape[1]), + columns=pd.MultiIndex.from_tuples( + list(itertools.product(["a"], range(shape[1] - (shape[1] // 2)))) + + list(itertools.product(["b"], range(shape[1] // 2))) + ), + ) + + +def visititems_zarr( + z: ZarrGroup, visitor: Callable[[str, ZarrGroup | zarr.Array], None] +) -> None: + for key in z: + maybe_group = z[key] + if isinstance(maybe_group, ZarrGroup): + visititems_zarr(maybe_group, visitor) + else: + visitor(key, maybe_group) + + +def check_all_sharded(g: ZarrGroup): + def visit(key: str, arr: zarr.Array | zarr.Group): + # Check for recarray via https://numpy.org/doc/stable/user/basics.rec.html#manipulating-and-displaying-structured-datatypes + if isinstance(arr, zarr.Array) and arr.shape != () and arr.dtype.names is None: + assert arr.shards is not None + + visititems_zarr(g, visitor=visit) diff --git a/.venv/lib/python3.11/site-packages/anndata/types.py b/.venv/lib/python3.11/site-packages/anndata/types.py new file mode 100644 index 0000000000000000000000000000000000000000..8285cf53c17d54f51f641b32e26f859c3890b67e --- /dev/null +++ b/.venv/lib/python3.11/site-packages/anndata/types.py @@ -0,0 +1,19 @@ +from __future__ import annotations + +from warnings import warn + + +def __getattr__(key: str): + match key: + case "ExtensionNamespace": + from scverse_misc import ExtensionNamespace + + msg = ( + "Importing ExtensionNamespace from `types` is deprecated. " + "Please use scverse_misc instead." + ) + warn(msg, FutureWarning, stacklevel=2) + return ExtensionNamespace + case _: + msg = f"types has no attribute {key!r}" + raise AttributeError(msg) diff --git a/.venv/lib/python3.11/site-packages/anndata/typing.py b/.venv/lib/python3.11/site-packages/anndata/typing.py new file mode 100644 index 0000000000000000000000000000000000000000..25e279248616a3df6b4a5d77b40609690b9990b5 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/anndata/typing.py @@ -0,0 +1,65 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +import numpy as np +import pandas as pd +from numpy import ma + +from . import abc +from ._core.anndata import AnnData +from .compat import ( + AwkArray, + CSArray, + CSMatrix, + CupyArray, + CupySparseMatrix, + DaskArray, + H5Array, + XDataArray, + ZappyArray, + ZarrArray, +) +from .compat import Index as _Index + +if TYPE_CHECKING: + from typing import TypeAlias + + +__all__ = ["AxisStorable", "Index", "RWAble"] + + +Index = _Index +"""1D or 2D index an :class:`~anndata.AnnData` object can be sliced with.""" + +XDataType: TypeAlias = ( + np.ndarray + | ma.MaskedArray + | CSMatrix + | CSArray + | H5Array + | ZarrArray + | ZappyArray + | abc.CSRDataset + | abc.CSCDataset + | DaskArray + | CupyArray + | CupySparseMatrix +) +ArrayDataStructureTypes: TypeAlias = XDataType | AwkArray | XDataArray + + +InMemoryArrayOrScalarType: TypeAlias = ( + pd.DataFrame | np.number | str | ArrayDataStructureTypes +) + + +AxisStorable: TypeAlias = ( + InMemoryArrayOrScalarType | dict[str, "AxisStorable"] | list["AxisStorable"] +) +"""A serializable object, excluding :class:`anndata.AnnData` objects i.e., something that can be stored in `uns` or `obsm`.""" + +RWAble: TypeAlias = ( + AxisStorable | AnnData | pd.Categorical | pd.api.extensions.ExtensionArray +) +"""A superset of :type:`anndata.typing.AxisStorable` (i.e., including :class:`anndata.AnnData`) which is everything can be read/written by :func:`anndata.io.read_elem` and :func:`anndata.io.write_elem`.""" diff --git a/.venv/lib/python3.11/site-packages/anndata/utils.py b/.venv/lib/python3.11/site-packages/anndata/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f88c3438a4a445097aae3baf97a90bc8fb7f1169 --- /dev/null +++ b/.venv/lib/python3.11/site-packages/anndata/utils.py @@ -0,0 +1,407 @@ +from __future__ import annotations + +import re +import warnings +from functools import singledispatch +from typing import TYPE_CHECKING + +import h5py +import numpy as np +import pandas as pd +from scipy import sparse + +import anndata + +from ._core.sparse_dataset import BaseCompressedSparseDataset +from .compat import CSArray, CupyArray, CupySparseMatrix, DaskArray +from .logging import get_logger + +if TYPE_CHECKING: + from collections.abc import Iterable, Mapping, Sequence + from typing import Any, Literal, LiteralString + +logger = get_logger(__name__) + + +def import_name(full_name: str) -> Any: + from importlib import import_module + + parts = full_name.split(".") + obj = import_module(parts[0]) + for _i, name in enumerate(parts[1:]): + i = _i + try: + obj = import_module(f"{obj.__name__}.{name}") + except ModuleNotFoundError: + break + else: + i = len(parts) + for name in parts[i + 1 :]: + try: + obj = getattr(obj, name) + except AttributeError as e: + msg = f"{parts[:i]}, {parts[i + 1 :]}, {obj} {name}" + raise RuntimeError(msg) from e + return obj + + +@singledispatch +def asarray(x): + """Convert x to a numpy array""" + return np.asarray(x) + + +@asarray.register(CSArray) +@asarray.register(sparse.spmatrix) +def asarray_sparse(x): + return x.toarray() + + +@asarray.register(BaseCompressedSparseDataset) +def asarray_sparse_dataset(x): + return asarray(x.to_memory()) + + +@asarray.register(h5py.Dataset) +def asarray_h5py_dataset(x): + return x[...] + + +@asarray.register(CupyArray) +def asarray_cupy(x): + return x.get() + + +@asarray.register(CupySparseMatrix) +def asarray_cupy_sparse(x): + return x.toarray().get() + + +@asarray.register(DaskArray) +def asarray_dask(x): + return asarray(x.compute()) + + +@singledispatch +def convert_to_dict(obj) -> dict: + return dict(obj) + + +@convert_to_dict.register(dict) +def convert_to_dict_dict(obj: dict): + return obj + + +@convert_to_dict.register(np.ndarray) +def convert_to_dict_ndarray(obj: np.ndarray): + if obj.dtype.fields is None: + msg = ( + "Can only convert np.ndarray with compound dtypes to dict, " + f"passed array had “{obj.dtype}”." + ) + raise TypeError(msg) + return {k: obj[k] for k in obj.dtype.fields} + + +@convert_to_dict.register(type(None)) +def convert_to_dict_nonetype(obj: None): + return dict() + + +@singledispatch +def axis_len(x, axis: Literal[0, 1]) -> int | None: + """\ + Return the size of an array in dimension `axis`. + + Returns None if `x` is an awkward array with variable length in the requested dimension. + """ + return x.shape[axis] + + +try: + from .compat import awkward as ak + + def _size_at_depth(layout, depth, lateral_context, **kwargs): + """Callback function for dim_len_awkward, resolving the dim_len for a given level""" + if layout.is_numpy: + # if it's an embedded rectilinear array, we have to deal with its shape + # which might not be 1-dimensional + shape = (0,) if layout.is_unknown else layout.shape + numpy_axis = lateral_context["axis"] - depth + 1 + if not (1 <= numpy_axis < len(shape)): + msg = f"axis={lateral_context['axis']} is too deep" + raise TypeError(msg) + lateral_context["out"] = shape[numpy_axis] + return ak.contents.EmptyArray() + + elif layout.is_list and depth == lateral_context["axis"]: + if layout.parameter("__array__") in {"string", "bytestring"}: + # Strings are implemented like an array of lists of uint8 (ListType(NumpyType(...))) + # which results in an extra hierarchy-level that shouldn't show up in dim_len + # See https://github.com/scikit-hep/awkward/discussions/1654#discussioncomment-3736747 + msg = f"axis={lateral_context['axis']} is too deep" + raise TypeError(msg) + + if layout.is_regular: + # if it's a regular list, you want the size + lateral_context["out"] = layout.size + else: + # if it's an irregular list, you want a null token + lateral_context["out"] = -1 + return ak.contents.EmptyArray() + + elif layout.is_record and depth == lateral_context["axis"]: + lateral_context["out"] = len(layout.fields) + return ak.contents.EmptyArray() + + elif layout.is_record: + # currently, we don't recurse into records + # in theory we could, just not sure how to do it at the moment + # Would need to consider cases like: scalars, unevenly sized values + msg = f"Cannot recurse into record type found at axis={lateral_context['axis']}" + raise TypeError(msg) + + elif layout.is_union: + # if it's a union, you could get the result of each union branch + # separately and see if they're all the same; if not, it's an error + result = None + for content in layout.contents: + context = {"axis": lateral_context["axis"]} + ak.transform( + _size_at_depth, + content, + lateral_context=context, + ) + if result is None: + result = context["out"] + elif result != context["out"]: + # Union branches have different lengths -> return null token + lateral_context["out"] = -1 + return ak.contents.EmptyArray() + lateral_context["out"] = result + return ak.contents.EmptyArray() + + @axis_len.register(ak.Array) + def axis_len_awkward(array, axis: Literal[0, 1]) -> int | None: + """Get the length of an awkward array in a given axis + + Returns None if the axis is of variable length. + + Code adapted from @jpivarski's solution in https://github.com/scikit-hep/awkward/discussions/1654#discussioncomment-3521574 + """ + if axis < 0: # negative axis is another can of worms... maybe later + msg = "Does not support negative axis" + raise NotImplementedError(msg) + elif axis == 0: + return len(array) + else: + # communicate with the recursive function using a context (lateral) + context = {"axis": axis} + + # "transform" but we don't care what kind of array it returns + ak.transform( + _size_at_depth, + array, + lateral_context=context, + ) + + # Use `None` as null token. + return None if context["out"] == -1 else context["out"] + + @asarray.register(ak.Array) + def asarray_awkward(x): + return x + +except ImportError: + pass + + +def make_index_unique(index: pd.Index[str], join: str = "-") -> pd.Index[str]: + """ + Makes the index unique by appending a number string to each duplicate index element: + '1', '2', etc. + + If a tentative name created by the algorithm already exists in the index, it tries + the next integer in the sequence. + + The first occurrence of a non-unique value is ignored. + + Parameters + ---------- + join + The connecting string between name and integer. + + Examples + -------- + >>> from anndata import AnnData + >>> adata = AnnData(np.ones((2, 3)), var=pd.DataFrame(index=["a", "a", "b"])) + >>> adata.var_names.astype("string") + Index(['a', 'a', 'b'], dtype='string') + >>> adata.var_names_make_unique() + >>> adata.var_names.astype("string") + Index(['a', 'a-1', 'b'], dtype='string') + """ + if index.is_unique: + return index + from collections import Counter + + values = index.array.copy() + indices_dup = index.duplicated(keep="first") & ~index.isna() + values_dup = values[indices_dup] + values_set = set(values) + counter = Counter() + issue_interpretation_warning = False + example_colliding_values = [] + for i, v in enumerate(values_dup): + while True: + counter[v] += 1 + tentative_new_name = v + join + str(counter[v]) + if tentative_new_name not in values_set: + values_set.add(tentative_new_name) + values_dup[i] = tentative_new_name + break + issue_interpretation_warning = True + if len(example_colliding_values) < 5: + example_colliding_values.append(tentative_new_name) + + if issue_interpretation_warning: + msg = ( + f"Suffix used ({join}[0-9]+) to deduplicate index values may make index values difficult to interpret. " + "There values with a similar suffixes in the index. " + "Consider using a different delimiter by passing `join={delimiter}`. " + "Example key collisions generated by the make_index_unique algorithm: " + f"{example_colliding_values}" + ) + # 3: caller -> 2: `{obs,var}_names_make_unique` -> 1: here + warnings.warn(msg, UserWarning, stacklevel=3) + values[indices_dup] = values_dup + index = pd.Index(values, name=index.name) + return index + + +def join_english(words: Iterable[str], conjunction: str = "or") -> str: + words = list(words) # no need to be efficient + if len(words) == 0: + return "" + if len(words) == 1: + return words[0] + if len(words) == 2: + return f"{words[0]} {conjunction} {words[1]}" + return ", ".join(words[:-1]) + f", {conjunction} {words[-1]}" + + +def warn_names_duplicates(attr: str): + names = "Observation" if attr == "obs" else "Variable" + warnings.warn( + f"{names} names are not unique. " + f"To make them unique, call `.{attr}_names_make_unique`.", + UserWarning, + stacklevel=2, + ) + + +def ensure_df_homogeneous( + df: pd.DataFrame, name: str +) -> np.ndarray | sparse.csr_matrix: + # TODO: rename this function, I would not expect this to return a non-dataframe + if all(isinstance(dt, pd.SparseDtype) for dt in df.dtypes): + arr = df.sparse.to_coo().tocsr() + else: + arr = df.to_numpy() + if df.dtypes.nunique() != 1: + msg = f"{name} converted to numpy array with dtype {arr.dtype}" + # 4: caller -> 3: `AnnData.__init__` -> 2: `_init_as_actual` → 1: here + warnings.warn(msg, UserWarning, stacklevel=4) + return arr + + +def convert_dictionary_to_structured_array(source: Mapping[str, Sequence[Any]]): + names = list(source.keys()) + try: # transform to byte-strings + cols = [ + np.asarray(col) + if np.array(col[0]).dtype.char not in {"U", "S"} + else np.asarray(col).astype("U") + for col in source.values() + ] + except UnicodeEncodeError as e: + msg = ( + "Currently only support ascii strings. " + "Don’t use “ö” etc. for sample annotation." + ) + raise ValueError(msg) from e + + # if old_index_key not in source: + # names.append(new_index_key) + # cols.append(np.arange(len(cols[0]) if cols else n_row).astype("U")) + # else: + # names[names.index(old_index_key)] = new_index_key + # cols[names.index(old_index_key)] = cols[names.index(old_index_key)].astype("U") + dtype_list = list( + zip( + names, + [str(c.dtype) for c in cols], + [(c.shape[1],) for c in cols], + strict=True, + ) + ) + # might be unnecessary + dtype = np.dtype(dtype_list) + + arr = np.zeros((len(cols[0]),), dtype) + # here, we do not want to call BoundStructArray.__getitem__ + # but np.ndarray.__getitem__, therefore we avoid the following line + # arr = np.ndarray.__new__(cls, (len(cols[0]),), dtype) + for i, name in enumerate(dtype.names): + arr[name] = np.array(cols[i], dtype=dtype_list[i][1]) + + return arr + + +def warn_once(msg: str, category: type[Warning], stacklevel: int = 1): + warnings.warn(msg, category, stacklevel=stacklevel) + # Prevent from showing up every time an awkward array is used + # You'd think `'once'` works, but it doesn't at the repl and in notebooks + warnings.filterwarnings("ignore", category=category, message=re.escape(msg)) + + +def deprecation_msg( + name: LiteralString, new_name: LiteralString, add_msg: LiteralString | None = None +) -> LiteralString: + msg = f"Use {new_name} instead of {name}." + if add_msg is not None: + msg += f" {add_msg}" + return msg + + +def raise_value_error_if_multiindex_columns(df: pd.DataFrame, attr: str): + if isinstance(df.columns, pd.MultiIndex): + msg = ( + "MultiIndex columns are not supported in AnnData. " + f"Please use a single-level index for {attr}." + ) + raise ValueError(msg) + + +def module_get_attr_redirect( + attr_name: str, + deprecated_mapping: Mapping[str, str], + old_module_path: str | None = None, +) -> Any: + full_old_module_path = ( + f"anndata{'.' + old_module_path if old_module_path is not None else ''}" + ) + if new_path := deprecated_mapping.get(attr_name): + msg = ( + f"Importing {attr_name} from `{full_old_module_path}` is deprecated. " + f"Import anndata.{new_path} instead." + ) + warnings.warn(msg, FutureWarning, stacklevel=2) + # hacky import_object_by_name, but we test all these + mod = anndata + while "." in new_path: + mod_name, new_path = new_path.split(".", 1) + mod = getattr(mod, mod_name) + return getattr(mod, new_path) + msg = f"module {full_old_module_path} has no attribute {attr_name!r}" + raise AttributeError(msg)