assassinlike commited on
Commit
fdfa2b4
·
verified ·
1 Parent(s): 42ddc9d

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. data/diffusion/.venv/.gitignore +1 -0
  2. data/diffusion/.venv/.lock +0 -0
  3. data/diffusion/.venv/CACHEDIR.TAG +1 -0
  4. data/diffusion/.venv/bin/activate +130 -0
  5. data/diffusion/.venv/bin/activate.bat +71 -0
  6. data/diffusion/.venv/bin/activate.csh +76 -0
  7. data/diffusion/.venv/bin/activate.fish +124 -0
  8. data/diffusion/.venv/bin/activate.nu +102 -0
  9. data/diffusion/.venv/bin/activate.ps1 +82 -0
  10. data/diffusion/.venv/bin/activate_this.py +59 -0
  11. data/diffusion/.venv/bin/deactivate.bat +39 -0
  12. data/diffusion/.venv/bin/diffusers-cli +10 -0
  13. data/diffusion/.venv/bin/idna +10 -0
  14. data/diffusion/.venv/bin/normalizer +10 -0
  15. data/diffusion/.venv/bin/pydoc.bat +22 -0
  16. data/diffusion/.venv/bin/tqdm +10 -0
  17. data/diffusion/.venv/lib/python3.11/site-packages/_virtualenv.py +101 -0
  18. data/diffusion/.venv/lib/python3.11/site-packages/charset_normalizer-3.4.9.dist-info/INSTALLER +1 -0
  19. data/diffusion/.venv/lib/python3.11/site-packages/charset_normalizer-3.4.9.dist-info/METADATA +827 -0
  20. data/diffusion/.venv/lib/python3.11/site-packages/charset_normalizer-3.4.9.dist-info/RECORD +25 -0
  21. data/diffusion/.venv/lib/python3.11/site-packages/charset_normalizer-3.4.9.dist-info/REQUESTED +0 -0
  22. data/diffusion/.venv/lib/python3.11/site-packages/charset_normalizer-3.4.9.dist-info/WHEEL +7 -0
  23. data/diffusion/.venv/lib/python3.11/site-packages/charset_normalizer-3.4.9.dist-info/entry_points.txt +2 -0
  24. data/diffusion/.venv/lib/python3.11/site-packages/charset_normalizer-3.4.9.dist-info/top_level.txt +2 -0
  25. data/diffusion/.venv/lib/python3.11/site-packages/filelock/__init__.py +93 -0
  26. data/diffusion/.venv/lib/python3.11/site-packages/filelock/_api.py +645 -0
  27. data/diffusion/.venv/lib/python3.11/site-packages/filelock/_async_read_write.py +216 -0
  28. data/diffusion/.venv/lib/python3.11/site-packages/filelock/_error.py +28 -0
  29. data/diffusion/.venv/lib/python3.11/site-packages/filelock/_read_write.py +385 -0
  30. data/diffusion/.venv/lib/python3.11/site-packages/filelock/_soft.py +243 -0
  31. data/diffusion/.venv/lib/python3.11/site-packages/filelock/_unix.py +114 -0
  32. data/diffusion/.venv/lib/python3.11/site-packages/filelock/_util.py +95 -0
  33. data/diffusion/.venv/lib/python3.11/site-packages/filelock/_windows.py +111 -0
  34. data/diffusion/.venv/lib/python3.11/site-packages/filelock/asyncio.py +414 -0
  35. data/diffusion/.venv/lib/python3.11/site-packages/filelock/py.typed +0 -0
  36. data/diffusion/.venv/lib/python3.11/site-packages/filelock/version.py +24 -0
  37. data/diffusion/.venv/lib/python3.11/site-packages/idna-3.18.dist-info/INSTALLER +1 -0
  38. data/diffusion/.venv/lib/python3.11/site-packages/idna-3.18.dist-info/METADATA +155 -0
  39. data/diffusion/.venv/lib/python3.11/site-packages/idna-3.18.dist-info/RECORD +19 -0
  40. data/diffusion/.venv/lib/python3.11/site-packages/idna-3.18.dist-info/REQUESTED +0 -0
  41. data/diffusion/.venv/lib/python3.11/site-packages/idna-3.18.dist-info/WHEEL +4 -0
  42. data/diffusion/.venv/lib/python3.11/site-packages/idna-3.18.dist-info/entry_points.txt +3 -0
  43. data/diffusion/.venv/lib/python3.11/site-packages/setuptools/_core_metadata.py +337 -0
  44. data/diffusion/.venv/lib/python3.11/site-packages/setuptools/_imp.py +87 -0
  45. data/diffusion/.venv/lib/python3.11/site-packages/setuptools/build_meta.py +556 -0
  46. data/diffusion/.venv/lib/python3.11/site-packages/setuptools/cli.exe +0 -0
  47. data/diffusion/.venv/lib/python3.11/site-packages/setuptools/dist.py +1124 -0
  48. data/diffusion/.venv/lib/python3.11/site-packages/setuptools/glob.py +185 -0
  49. data/diffusion/.venv/lib/python3.11/site-packages/setuptools/gui-32.exe +0 -0
  50. data/diffusion/.venv/lib/python3.11/site-packages/setuptools/gui-64.exe +0 -0
data/diffusion/.venv/.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ *
data/diffusion/.venv/.lock ADDED
File without changes
data/diffusion/.venv/CACHEDIR.TAG ADDED
@@ -0,0 +1 @@
 
 
1
+ Signature: 8a477f597d28d172789f06886806bc55
data/diffusion/.venv/bin/activate ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2020-202x The virtualenv developers
2
+ #
3
+ # Permission is hereby granted, free of charge, to any person obtaining
4
+ # a copy of this software and associated documentation files (the
5
+ # "Software"), to deal in the Software without restriction, including
6
+ # without limitation the rights to use, copy, modify, merge, publish,
7
+ # distribute, sublicense, and/or sell copies of the Software, and to
8
+ # permit persons to whom the Software is furnished to do so, subject to
9
+ # the following conditions:
10
+ #
11
+ # The above copyright notice and this permission notice shall be
12
+ # included in all copies or substantial portions of the Software.
13
+ #
14
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
+
22
+ # This file must be used with "source bin/activate" *from bash*
23
+ # you cannot run it directly
24
+
25
+ if ! [ -z "${SCRIPT_PATH+_}" ] ; then
26
+ _OLD_SCRIPT_PATH="$SCRIPT_PATH"
27
+ fi
28
+
29
+ # Get script path (only used if environment is relocatable).
30
+ if [ -n "${BASH_VERSION:+x}" ] ; then
31
+ SCRIPT_PATH="${BASH_SOURCE[0]}"
32
+ if [ "$SCRIPT_PATH" = "$0" ]; then
33
+ # Only bash has a reasonably robust check for source'dness.
34
+ echo "You must source this script: \$ source $0" >&2
35
+ exit 33
36
+ fi
37
+ elif [ -n "${ZSH_VERSION:+x}" ] ; then
38
+ SCRIPT_PATH="${(%):-%x}"
39
+ elif [ -n "${KSH_VERSION:+x}" ] ; then
40
+ SCRIPT_PATH="${.sh.file}"
41
+ fi
42
+
43
+ deactivate () {
44
+ unset -f pydoc >/dev/null 2>&1 || true
45
+
46
+ # reset old environment variables
47
+ # ! [ -z ${VAR+_} ] returns true if VAR is declared at all
48
+ if ! [ -z "${_OLD_VIRTUAL_PATH:+_}" ] ; then
49
+ PATH="$_OLD_VIRTUAL_PATH"
50
+ export PATH
51
+ unset _OLD_VIRTUAL_PATH
52
+ fi
53
+ if ! [ -z "${_OLD_VIRTUAL_PYTHONHOME+_}" ] ; then
54
+ PYTHONHOME="$_OLD_VIRTUAL_PYTHONHOME"
55
+ export PYTHONHOME
56
+ unset _OLD_VIRTUAL_PYTHONHOME
57
+ fi
58
+
59
+ # The hash command must be called to get it to forget past
60
+ # commands. Without forgetting past commands the $PATH changes
61
+ # we made may not be respected
62
+ hash -r 2>/dev/null
63
+
64
+ if ! [ -z "${_OLD_VIRTUAL_PS1+_}" ] ; then
65
+ PS1="$_OLD_VIRTUAL_PS1"
66
+ export PS1
67
+ unset _OLD_VIRTUAL_PS1
68
+ fi
69
+
70
+ unset VIRTUAL_ENV
71
+ unset VIRTUAL_ENV_PROMPT
72
+ if [ ! "${1-}" = "nondestructive" ] ; then
73
+ # Self destruct!
74
+ unset -f deactivate
75
+ fi
76
+ }
77
+
78
+ # unset irrelevant variables
79
+ deactivate nondestructive
80
+
81
+ VIRTUAL_ENV='/zfspool/zangyihe/diffusion/.venv'
82
+ if ([ "$OSTYPE" = "cygwin" ] || [ "$OSTYPE" = "msys" ]) && $(command -v cygpath &> /dev/null) ; then
83
+ VIRTUAL_ENV=$(cygpath -u "$VIRTUAL_ENV")
84
+ fi
85
+ export VIRTUAL_ENV
86
+
87
+ # Unset the `SCRIPT_PATH` variable, now that the `VIRTUAL_ENV` variable
88
+ # has been set. This is important for relocatable environments.
89
+ if ! [ -z "${_OLD_SCRIPT_PATH+_}" ] ; then
90
+ SCRIPT_PATH="$_OLD_SCRIPT_PATH"
91
+ export SCRIPT_PATH
92
+ unset _OLD_SCRIPT_PATH
93
+ else
94
+ unset SCRIPT_PATH
95
+ fi
96
+
97
+ _OLD_VIRTUAL_PATH="$PATH"
98
+ PATH="$VIRTUAL_ENV/bin:$PATH"
99
+ export PATH
100
+
101
+ if [ "x" != x ] ; then
102
+ VIRTUAL_ENV_PROMPT=""
103
+ else
104
+ VIRTUAL_ENV_PROMPT=$(basename "$VIRTUAL_ENV")
105
+ fi
106
+ export VIRTUAL_ENV_PROMPT
107
+
108
+ # unset PYTHONHOME if set
109
+ if ! [ -z "${PYTHONHOME+_}" ] ; then
110
+ _OLD_VIRTUAL_PYTHONHOME="$PYTHONHOME"
111
+ unset PYTHONHOME
112
+ fi
113
+
114
+ if [ -z "${VIRTUAL_ENV_DISABLE_PROMPT-}" ] ; then
115
+ _OLD_VIRTUAL_PS1="${PS1-}"
116
+ PS1="(${VIRTUAL_ENV_PROMPT}) ${PS1-}"
117
+ export PS1
118
+ fi
119
+
120
+ # Make sure to unalias pydoc if it's already there
121
+ alias pydoc 2>/dev/null >/dev/null && unalias pydoc || true
122
+
123
+ pydoc () {
124
+ python -m pydoc "$@"
125
+ }
126
+
127
+ # The hash command must be called to get it to forget past
128
+ # commands. Without forgetting past commands the $PATH changes
129
+ # we made may not be respected
130
+ hash -r 2>/dev/null || true
data/diffusion/.venv/bin/activate.bat ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @REM Copyright (c) 2020-202x The virtualenv developers
2
+ @REM
3
+ @REM Permission is hereby granted, free of charge, to any person obtaining
4
+ @REM a copy of this software and associated documentation files (the
5
+ @REM "Software"), to deal in the Software without restriction, including
6
+ @REM without limitation the rights to use, copy, modify, merge, publish,
7
+ @REM distribute, sublicense, and/or sell copies of the Software, and to
8
+ @REM permit persons to whom the Software is furnished to do so, subject to
9
+ @REM the following conditions:
10
+ @REM
11
+ @REM The above copyright notice and this permission notice shall be
12
+ @REM included in all copies or substantial portions of the Software.
13
+ @REM
14
+ @REM THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ @REM EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ @REM MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ @REM NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ @REM LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ @REM OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ @REM WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
+
22
+ @REM This file is UTF-8 encoded, so we need to update the current code page while executing it
23
+ @for /f "tokens=2 delims=:." %%a in ('"%SystemRoot%\System32\chcp.com"') do @set _OLD_CODEPAGE=%%a
24
+
25
+ @if defined _OLD_CODEPAGE (
26
+ "%SystemRoot%\System32\chcp.com" 65001 > nul
27
+ )
28
+
29
+ @for %%i in ("/zfspool/zangyihe/diffusion/.venv") do @set "VIRTUAL_ENV=%%~fi"
30
+
31
+ @set "VIRTUAL_ENV_PROMPT="
32
+ @if NOT DEFINED VIRTUAL_ENV_PROMPT (
33
+ @for %%d in ("%VIRTUAL_ENV%") do @set "VIRTUAL_ENV_PROMPT=%%~nxd"
34
+ )
35
+
36
+ @if defined _OLD_VIRTUAL_PROMPT (
37
+ @set "PROMPT=%_OLD_VIRTUAL_PROMPT%"
38
+ ) else (
39
+ @if not defined PROMPT (
40
+ @set "PROMPT=$P$G"
41
+ )
42
+ @if not defined VIRTUAL_ENV_DISABLE_PROMPT (
43
+ @set "_OLD_VIRTUAL_PROMPT=%PROMPT%"
44
+ )
45
+ )
46
+ @if not defined VIRTUAL_ENV_DISABLE_PROMPT (
47
+ @set "PROMPT=(%VIRTUAL_ENV_PROMPT%) %PROMPT%"
48
+ )
49
+
50
+ @REM Don't use () to avoid problems with them in %PATH%
51
+ @if defined _OLD_VIRTUAL_PYTHONHOME @goto ENDIFVHOME
52
+ @set "_OLD_VIRTUAL_PYTHONHOME=%PYTHONHOME%"
53
+ :ENDIFVHOME
54
+
55
+ @set PYTHONHOME=
56
+
57
+ @REM if defined _OLD_VIRTUAL_PATH (
58
+ @if not defined _OLD_VIRTUAL_PATH @goto ENDIFVPATH1
59
+ @set "PATH=%_OLD_VIRTUAL_PATH%"
60
+ :ENDIFVPATH1
61
+ @REM ) else (
62
+ @if defined _OLD_VIRTUAL_PATH @goto ENDIFVPATH2
63
+ @set "_OLD_VIRTUAL_PATH=%PATH%"
64
+ :ENDIFVPATH2
65
+
66
+ @set "PATH=%VIRTUAL_ENV%\bin;%PATH%"
67
+
68
+ @if defined _OLD_CODEPAGE (
69
+ "%SystemRoot%\System32\chcp.com" %_OLD_CODEPAGE% > nul
70
+ @set _OLD_CODEPAGE=
71
+ )
data/diffusion/.venv/bin/activate.csh ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2020-202x The virtualenv developers
2
+ #
3
+ # Permission is hereby granted, free of charge, to any person obtaining
4
+ # a copy of this software and associated documentation files (the
5
+ # "Software"), to deal in the Software without restriction, including
6
+ # without limitation the rights to use, copy, modify, merge, publish,
7
+ # distribute, sublicense, and/or sell copies of the Software, and to
8
+ # permit persons to whom the Software is furnished to do so, subject to
9
+ # the following conditions:
10
+ #
11
+ # The above copyright notice and this permission notice shall be
12
+ # included in all copies or substantial portions of the Software.
13
+ #
14
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
+
22
+ # This file must be used with "source bin/activate.csh" *from csh*.
23
+ # You cannot run it directly.
24
+ # Created by Davide Di Blasi <davidedb@gmail.com>.
25
+
26
+ set newline='\
27
+ '
28
+
29
+ alias deactivate 'test $?_OLD_VIRTUAL_PATH != 0 && setenv PATH "$_OLD_VIRTUAL_PATH:q" && unset _OLD_VIRTUAL_PATH; rehash; test $?_OLD_VIRTUAL_PROMPT != 0 && set prompt="$_OLD_VIRTUAL_PROMPT:q" && unset _OLD_VIRTUAL_PROMPT; unsetenv VIRTUAL_ENV; unsetenv VIRTUAL_ENV_PROMPT; test "\!:*" != "nondestructive" && unalias deactivate && unalias pydoc'
30
+
31
+ # Unset irrelevant variables.
32
+ deactivate nondestructive
33
+
34
+ setenv VIRTUAL_ENV '/zfspool/zangyihe/diffusion/.venv'
35
+
36
+ set _OLD_VIRTUAL_PATH="$PATH:q"
37
+ setenv PATH "$VIRTUAL_ENV:q/bin:$PATH:q"
38
+
39
+
40
+
41
+ if ('' != "") then
42
+ setenv VIRTUAL_ENV_PROMPT ''
43
+ else
44
+ setenv VIRTUAL_ENV_PROMPT "$VIRTUAL_ENV:t:q"
45
+ endif
46
+
47
+ if ( $?VIRTUAL_ENV_DISABLE_PROMPT ) then
48
+ if ( $VIRTUAL_ENV_DISABLE_PROMPT == "" ) then
49
+ set do_prompt = "1"
50
+ else
51
+ set do_prompt = "0"
52
+ endif
53
+ else
54
+ set do_prompt = "1"
55
+ endif
56
+
57
+ if ( $do_prompt == "1" ) then
58
+ # Could be in a non-interactive environment,
59
+ # in which case, $prompt is undefined and we wouldn't
60
+ # care about the prompt anyway.
61
+ if ( $?prompt ) then
62
+ set _OLD_VIRTUAL_PROMPT="$prompt:q"
63
+ if ( "$prompt:q" =~ *"$newline:q"* ) then
64
+ :
65
+ else
66
+ set prompt = '('"$VIRTUAL_ENV_PROMPT:q"') '"$prompt:q"
67
+ endif
68
+ endif
69
+ endif
70
+
71
+ unset env_name
72
+ unset do_prompt
73
+
74
+ alias pydoc python -m pydoc
75
+
76
+ rehash
data/diffusion/.venv/bin/activate.fish ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2020-202x The virtualenv developers
2
+ #
3
+ # Permission is hereby granted, free of charge, to any person obtaining
4
+ # a copy of this software and associated documentation files (the
5
+ # "Software"), to deal in the Software without restriction, including
6
+ # without limitation the rights to use, copy, modify, merge, publish,
7
+ # distribute, sublicense, and/or sell copies of the Software, and to
8
+ # permit persons to whom the Software is furnished to do so, subject to
9
+ # the following conditions:
10
+ #
11
+ # The above copyright notice and this permission notice shall be
12
+ # included in all copies or substantial portions of the Software.
13
+ #
14
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
+
22
+ # This file must be used using `source bin/activate.fish` *within a running fish ( http://fishshell.com ) session*.
23
+ # Do not run it directly.
24
+
25
+ function _bashify_path -d "Converts a fish path to something bash can recognize"
26
+ set fishy_path $argv
27
+ set bashy_path $fishy_path[1]
28
+ for path_part in $fishy_path[2..-1]
29
+ set bashy_path "$bashy_path:$path_part"
30
+ end
31
+ echo $bashy_path
32
+ end
33
+
34
+ function _fishify_path -d "Converts a bash path to something fish can recognize"
35
+ echo $argv | tr ':' '\n'
36
+ end
37
+
38
+ function deactivate -d 'Exit virtualenv mode and return to the normal environment.'
39
+ # reset old environment variables
40
+ if test -n "$_OLD_VIRTUAL_PATH"
41
+ # https://github.com/fish-shell/fish-shell/issues/436 altered PATH handling
42
+ if test (string sub -s 1 -l 1 $FISH_VERSION) -lt 3
43
+ set -gx PATH (_fishify_path "$_OLD_VIRTUAL_PATH")
44
+ else
45
+ set -gx PATH $_OLD_VIRTUAL_PATH
46
+ end
47
+ set -e _OLD_VIRTUAL_PATH
48
+ end
49
+
50
+ if test -n "$_OLD_VIRTUAL_PYTHONHOME"
51
+ set -gx PYTHONHOME "$_OLD_VIRTUAL_PYTHONHOME"
52
+ set -e _OLD_VIRTUAL_PYTHONHOME
53
+ end
54
+
55
+ if test -n "$_OLD_FISH_PROMPT_OVERRIDE"
56
+ and functions -q _old_fish_prompt
57
+ # Set an empty local `$fish_function_path` to allow the removal of `fish_prompt` using `functions -e`.
58
+ set -l fish_function_path
59
+
60
+ # Erase virtualenv's `fish_prompt` and restore the original.
61
+ functions -e fish_prompt
62
+ functions -c _old_fish_prompt fish_prompt
63
+ functions -e _old_fish_prompt
64
+ set -e _OLD_FISH_PROMPT_OVERRIDE
65
+ end
66
+
67
+ set -e VIRTUAL_ENV
68
+ set -e VIRTUAL_ENV_PROMPT
69
+
70
+ if test "$argv[1]" != 'nondestructive'
71
+ # Self-destruct!
72
+ functions -e pydoc
73
+ functions -e deactivate
74
+ functions -e _bashify_path
75
+ functions -e _fishify_path
76
+ end
77
+ end
78
+
79
+ # Unset irrelevant variables.
80
+ deactivate nondestructive
81
+
82
+ set -gx VIRTUAL_ENV '/zfspool/zangyihe/diffusion/.venv'
83
+
84
+ # https://github.com/fish-shell/fish-shell/issues/436 altered PATH handling
85
+ if test (string sub -s 1 -l 1 $FISH_VERSION) -lt 3
86
+ set -gx _OLD_VIRTUAL_PATH (_bashify_path $PATH)
87
+ else
88
+ set -gx _OLD_VIRTUAL_PATH $PATH
89
+ end
90
+ set -gx PATH "$VIRTUAL_ENV"'/bin' $PATH
91
+
92
+ # Prompt override provided?
93
+ # If not, just use the environment name.
94
+ if test -n ''
95
+ set -gx VIRTUAL_ENV_PROMPT ''
96
+ else
97
+ set -gx VIRTUAL_ENV_PROMPT (basename "$VIRTUAL_ENV")
98
+ end
99
+
100
+ # Unset `$PYTHONHOME` if set.
101
+ if set -q PYTHONHOME
102
+ set -gx _OLD_VIRTUAL_PYTHONHOME $PYTHONHOME
103
+ set -e PYTHONHOME
104
+ end
105
+
106
+ function pydoc
107
+ python -m pydoc $argv
108
+ end
109
+
110
+ if test -z "$VIRTUAL_ENV_DISABLE_PROMPT"
111
+ # Copy the current `fish_prompt` function as `_old_fish_prompt`.
112
+ functions -c fish_prompt _old_fish_prompt
113
+
114
+ function fish_prompt
115
+ # Run the user's prompt first; it might depend on (pipe)status.
116
+ set -l prompt (_old_fish_prompt)
117
+
118
+ printf '(%s) ' $VIRTUAL_ENV_PROMPT
119
+
120
+ string join -- \n $prompt # handle multi-line prompts
121
+ end
122
+
123
+ set -gx _OLD_FISH_PROMPT_OVERRIDE "$VIRTUAL_ENV"
124
+ end
data/diffusion/.venv/bin/activate.nu ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2020-202x The virtualenv developers
2
+ #
3
+ # Permission is hereby granted, free of charge, to any person obtaining
4
+ # a copy of this software and associated documentation files (the
5
+ # "Software"), to deal in the Software without restriction, including
6
+ # without limitation the rights to use, copy, modify, merge, publish,
7
+ # distribute, sublicense, and/or sell copies of the Software, and to
8
+ # permit persons to whom the Software is furnished to do so, subject to
9
+ # the following conditions:
10
+ #
11
+ # The above copyright notice and this permission notice shall be
12
+ # included in all copies or substantial portions of the Software.
13
+ #
14
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
+
22
+ # virtualenv activation module:
23
+ # - Activate with `overlay use activate.nu`
24
+ # - Deactivate with `deactivate`, as usual
25
+ #
26
+ # To customize the overlay name, you can call `overlay use activate.nu as foo`, but then simply `deactivate` won't work
27
+ # because it is just an alias to hide the "activate" overlay. You'd need to call `overlay hide foo` manually.
28
+
29
+ module warning {
30
+ export-env {
31
+ const file = path self
32
+ error make -u {
33
+ msg: $"`($file | path basename)` is meant to be used with `overlay use`, not `source`"
34
+ }
35
+ }
36
+
37
+ }
38
+
39
+ use warning
40
+
41
+ export-env {
42
+
43
+ let nu_ver = (version | get version | split row '.' | take 2 | each { into int })
44
+ if $nu_ver.0 == 0 and $nu_ver.1 < 106 {
45
+ error make {
46
+ msg: 'virtualenv Nushell activation requires Nushell 0.106 or greater.'
47
+ }
48
+ }
49
+
50
+ def is-string [x] {
51
+ ($x | describe) == 'string'
52
+ }
53
+
54
+ def has-env [...names] {
55
+ $names | each {|n| $n in $env } | all {|i| $i }
56
+ }
57
+
58
+ def is-env-true [name: string] {
59
+ if (has-env $name) {
60
+ let val = ($env | get --optional $name)
61
+ if ($val | describe) == 'bool' {
62
+ $val
63
+ } else {
64
+ not ($val | is-empty)
65
+ }
66
+ } else {
67
+ false
68
+ }
69
+ }
70
+
71
+ let virtual_env = '/zfspool/zangyihe/diffusion/.venv'
72
+ let bin = 'bin'
73
+ let path_name = if (has-env 'Path') { 'Path' } else { 'PATH' }
74
+ let venv_path = ([$virtual_env $bin] | path join)
75
+ let new_path = ($env | get $path_name | prepend $venv_path)
76
+ let virtual_env_prompt = if ('' | is-empty) {
77
+ ($virtual_env | path basename)
78
+ } else {
79
+ ''
80
+ }
81
+ let new_env = { $path_name: $new_path VIRTUAL_ENV: $virtual_env VIRTUAL_ENV_PROMPT: $virtual_env_prompt }
82
+ let old_prompt_command = if (has-env 'PROMPT_COMMAND') { $env.PROMPT_COMMAND } else { '' }
83
+ let new_env = if (is-env-true 'VIRTUAL_ENV_DISABLE_PROMPT') {
84
+ $new_env
85
+ } else {
86
+ let virtual_prefix = $'(char lparen)($virtual_env_prompt)(char rparen) '
87
+ let new_prompt = if (has-env 'PROMPT_COMMAND') {
88
+ if ('closure' in ($old_prompt_command | describe)) {
89
+ {|| $'($virtual_prefix)(do $old_prompt_command)' }
90
+ } else {
91
+ {|| $'($virtual_prefix)($old_prompt_command)' }
92
+ }
93
+ } else {
94
+ {|| $'($virtual_prefix)' }
95
+ }
96
+ $new_env | merge { PROMPT_COMMAND: $new_prompt VIRTUAL_PREFIX: $virtual_prefix }
97
+ }
98
+ load-env $new_env
99
+ }
100
+
101
+ export alias pydoc = python -m pydoc
102
+ export alias deactivate = overlay hide activate
data/diffusion/.venv/bin/activate.ps1 ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2020-202x The virtualenv developers
2
+ #
3
+ # Permission is hereby granted, free of charge, to any person obtaining
4
+ # a copy of this software and associated documentation files (the
5
+ # "Software"), to deal in the Software without restriction, including
6
+ # without limitation the rights to use, copy, modify, merge, publish,
7
+ # distribute, sublicense, and/or sell copies of the Software, and to
8
+ # permit persons to whom the Software is furnished to do so, subject to
9
+ # the following conditions:
10
+ #
11
+ # The above copyright notice and this permission notice shall be
12
+ # included in all copies or substantial portions of the Software.
13
+ #
14
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
+
22
+ $script:THIS_PATH = $myinvocation.mycommand.path
23
+ $script:BASE_DIR = Split-Path (Resolve-Path "$THIS_PATH/..") -Parent
24
+
25
+ function global:deactivate([switch] $NonDestructive) {
26
+ if (Test-Path variable:_OLD_VIRTUAL_PATH) {
27
+ $env:PATH = $variable:_OLD_VIRTUAL_PATH
28
+ Remove-Variable "_OLD_VIRTUAL_PATH" -Scope global
29
+ }
30
+
31
+ if (Test-Path function:_old_virtual_prompt) {
32
+ $function:prompt = $function:_old_virtual_prompt
33
+ Remove-Item function:\_old_virtual_prompt
34
+ }
35
+
36
+ if ($env:VIRTUAL_ENV) {
37
+ Remove-Item env:VIRTUAL_ENV -ErrorAction SilentlyContinue
38
+ }
39
+
40
+ if ($env:VIRTUAL_ENV_PROMPT) {
41
+ Remove-Item env:VIRTUAL_ENV_PROMPT -ErrorAction SilentlyContinue
42
+ }
43
+
44
+ if (!$NonDestructive) {
45
+ # Self destruct!
46
+ Remove-Item function:deactivate
47
+ Remove-Item function:pydoc
48
+ }
49
+ }
50
+
51
+ function global:pydoc {
52
+ python -m pydoc $args
53
+ }
54
+
55
+ # unset irrelevant variables
56
+ deactivate -nondestructive
57
+
58
+ $VIRTUAL_ENV = $BASE_DIR
59
+ $env:VIRTUAL_ENV = $VIRTUAL_ENV
60
+
61
+ if ("" -ne "") {
62
+ $env:VIRTUAL_ENV_PROMPT = ""
63
+ }
64
+ else {
65
+ $env:VIRTUAL_ENV_PROMPT = $( Split-Path $env:VIRTUAL_ENV -Leaf )
66
+ }
67
+
68
+ New-Variable -Scope global -Name _OLD_VIRTUAL_PATH -Value $env:PATH
69
+
70
+ $env:PATH = "$env:VIRTUAL_ENV/bin:" + $env:PATH
71
+ if (!$env:VIRTUAL_ENV_DISABLE_PROMPT) {
72
+ function global:_old_virtual_prompt {
73
+ ""
74
+ }
75
+ $function:_old_virtual_prompt = $function:prompt
76
+
77
+ function global:prompt {
78
+ # Add the custom prefix to the existing prompt
79
+ $previous_prompt_value = & $function:_old_virtual_prompt
80
+ ("(" + $env:VIRTUAL_ENV_PROMPT + ") " + $previous_prompt_value)
81
+ }
82
+ }
data/diffusion/.venv/bin/activate_this.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2020-202x The virtualenv developers
2
+ #
3
+ # Permission is hereby granted, free of charge, to any person obtaining
4
+ # a copy of this software and associated documentation files (the
5
+ # "Software"), to deal in the Software without restriction, including
6
+ # without limitation the rights to use, copy, modify, merge, publish,
7
+ # distribute, sublicense, and/or sell copies of the Software, and to
8
+ # permit persons to whom the Software is furnished to do so, subject to
9
+ # the following conditions:
10
+ #
11
+ # The above copyright notice and this permission notice shall be
12
+ # included in all copies or substantial portions of the Software.
13
+ #
14
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
+
22
+ """
23
+ Activate virtualenv for current interpreter:
24
+
25
+ import runpy
26
+ runpy.run_path(this_file)
27
+
28
+ This can be used when you must use an existing Python interpreter, not the virtualenv bin/python.
29
+ """ # noqa: D415
30
+
31
+ from __future__ import annotations
32
+
33
+ import os
34
+ import site
35
+ import sys
36
+
37
+ try:
38
+ abs_file = os.path.abspath(__file__)
39
+ except NameError as exc:
40
+ msg = "You must use import runpy; runpy.run_path(this_file)"
41
+ raise AssertionError(msg) from exc
42
+
43
+ bin_dir = os.path.dirname(abs_file)
44
+ base = bin_dir[: -len("bin") - 1] # strip away the bin part from the __file__, plus the path separator
45
+
46
+ # prepend bin to PATH (this file is inside the bin directory)
47
+ os.environ["PATH"] = os.pathsep.join([bin_dir, *os.environ.get("PATH", "").split(os.pathsep)])
48
+ os.environ["VIRTUAL_ENV"] = base # virtual env is right above bin directory
49
+ os.environ["VIRTUAL_ENV_PROMPT"] = "" or os.path.basename(base) # noqa: SIM222
50
+
51
+ # add the virtual environments libraries to the host python import mechanism
52
+ prev_length = len(sys.path)
53
+ for lib in "../lib/python3.11/site-packages".split(os.pathsep):
54
+ path = os.path.realpath(os.path.join(bin_dir, lib))
55
+ site.addsitedir(path)
56
+ sys.path[:] = sys.path[prev_length:] + sys.path[0:prev_length]
57
+
58
+ sys.real_prefix = sys.prefix
59
+ sys.prefix = base
data/diffusion/.venv/bin/deactivate.bat ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @REM Copyright (c) 2020-202x The virtualenv developers
2
+ @REM
3
+ @REM Permission is hereby granted, free of charge, to any person obtaining
4
+ @REM a copy of this software and associated documentation files (the
5
+ @REM "Software"), to deal in the Software without restriction, including
6
+ @REM without limitation the rights to use, copy, modify, merge, publish,
7
+ @REM distribute, sublicense, and/or sell copies of the Software, and to
8
+ @REM permit persons to whom the Software is furnished to do so, subject to
9
+ @REM the following conditions:
10
+ @REM
11
+ @REM The above copyright notice and this permission notice shall be
12
+ @REM included in all copies or substantial portions of the Software.
13
+ @REM
14
+ @REM THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ @REM EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ @REM MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ @REM NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ @REM LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ @REM OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ @REM WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
+
22
+ @set VIRTUAL_ENV=
23
+ @set VIRTUAL_ENV_PROMPT=
24
+
25
+ @REM Don't use () to avoid problems with them in %PATH%
26
+ @if not defined _OLD_VIRTUAL_PROMPT @goto ENDIFVPROMPT
27
+ @set "PROMPT=%_OLD_VIRTUAL_PROMPT%"
28
+ @set _OLD_VIRTUAL_PROMPT=
29
+ :ENDIFVPROMPT
30
+
31
+ @if not defined _OLD_VIRTUAL_PYTHONHOME @goto ENDIFVHOME
32
+ @set "PYTHONHOME=%_OLD_VIRTUAL_PYTHONHOME%"
33
+ @set _OLD_VIRTUAL_PYTHONHOME=
34
+ :ENDIFVHOME
35
+
36
+ @if not defined _OLD_VIRTUAL_PATH @goto ENDIFVPATH
37
+ @set "PATH=%_OLD_VIRTUAL_PATH%"
38
+ @set _OLD_VIRTUAL_PATH=
39
+ :ENDIFVPATH
data/diffusion/.venv/bin/diffusers-cli ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/zfspool/zangyihe/diffusion/.venv/bin/python
2
+ # -*- coding: utf-8 -*-
3
+ import sys
4
+ from diffusers.commands.diffusers_cli import main
5
+ if __name__ == "__main__":
6
+ if sys.argv[0].endswith("-script.pyw"):
7
+ sys.argv[0] = sys.argv[0][:-11]
8
+ elif sys.argv[0].endswith(".exe"):
9
+ sys.argv[0] = sys.argv[0][:-4]
10
+ sys.exit(main())
data/diffusion/.venv/bin/idna ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/zfspool/zangyihe/diffusion/.venv/bin/python
2
+ # -*- coding: utf-8 -*-
3
+ import sys
4
+ from idna.cli import main
5
+ if __name__ == "__main__":
6
+ if sys.argv[0].endswith("-script.pyw"):
7
+ sys.argv[0] = sys.argv[0][:-11]
8
+ elif sys.argv[0].endswith(".exe"):
9
+ sys.argv[0] = sys.argv[0][:-4]
10
+ sys.exit(main())
data/diffusion/.venv/bin/normalizer ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/zfspool/zangyihe/diffusion/.venv/bin/python
2
+ # -*- coding: utf-8 -*-
3
+ import sys
4
+ from charset_normalizer.cli import cli_detect
5
+ if __name__ == "__main__":
6
+ if sys.argv[0].endswith("-script.pyw"):
7
+ sys.argv[0] = sys.argv[0][:-11]
8
+ elif sys.argv[0].endswith(".exe"):
9
+ sys.argv[0] = sys.argv[0][:-4]
10
+ sys.exit(cli_detect())
data/diffusion/.venv/bin/pydoc.bat ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @REM Copyright (c) 2020-202x The virtualenv developers
2
+ @REM
3
+ @REM Permission is hereby granted, free of charge, to any person obtaining
4
+ @REM a copy of this software and associated documentation files (the
5
+ @REM "Software"), to deal in the Software without restriction, including
6
+ @REM without limitation the rights to use, copy, modify, merge, publish,
7
+ @REM distribute, sublicense, and/or sell copies of the Software, and to
8
+ @REM permit persons to whom the Software is furnished to do so, subject to
9
+ @REM the following conditions:
10
+ @REM
11
+ @REM The above copyright notice and this permission notice shall be
12
+ @REM included in all copies or substantial portions of the Software.
13
+ @REM
14
+ @REM THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ @REM EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ @REM MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ @REM NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ @REM LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ @REM OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ @REM WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
+
22
+ python.exe -m pydoc %*
data/diffusion/.venv/bin/tqdm ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/zfspool/zangyihe/diffusion/.venv/bin/python
2
+ # -*- coding: utf-8 -*-
3
+ import sys
4
+ from tqdm.cli import main
5
+ if __name__ == "__main__":
6
+ if sys.argv[0].endswith("-script.pyw"):
7
+ sys.argv[0] = sys.argv[0][:-11]
8
+ elif sys.argv[0].endswith(".exe"):
9
+ sys.argv[0] = sys.argv[0][:-4]
10
+ sys.exit(main())
data/diffusion/.venv/lib/python3.11/site-packages/_virtualenv.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Patches that are applied at runtime to the virtual environment."""
2
+
3
+ import os
4
+ import sys
5
+
6
+ VIRTUALENV_PATCH_FILE = os.path.join(__file__)
7
+
8
+
9
+ def patch_dist(dist):
10
+ """
11
+ Distutils allows user to configure some arguments via a configuration file:
12
+ https://docs.python.org/3.11/install/index.html#distutils-configuration-files.
13
+
14
+ Some of this arguments though don't make sense in context of the virtual environment files, let's fix them up.
15
+ """ # noqa: D205
16
+ # we cannot allow some install config as that would get packages installed outside of the virtual environment
17
+ old_parse_config_files = dist.Distribution.parse_config_files
18
+
19
+ def parse_config_files(self, *args, **kwargs):
20
+ result = old_parse_config_files(self, *args, **kwargs)
21
+ install = self.get_option_dict("install")
22
+
23
+ if "prefix" in install: # the prefix governs where to install the libraries
24
+ install["prefix"] = VIRTUALENV_PATCH_FILE, os.path.abspath(sys.prefix)
25
+ for base in ("purelib", "platlib", "headers", "scripts", "data"):
26
+ key = f"install_{base}"
27
+ if key in install: # do not allow global configs to hijack venv paths
28
+ install.pop(key, None)
29
+ return result
30
+
31
+ dist.Distribution.parse_config_files = parse_config_files
32
+
33
+
34
+ # Import hook that patches some modules to ignore configuration values that break package installation in case
35
+ # of virtual environments.
36
+ _DISTUTILS_PATCH = "distutils.dist", "setuptools.dist"
37
+ # https://docs.python.org/3/library/importlib.html#setting-up-an-importer
38
+
39
+
40
+ class _Finder:
41
+ """A meta path finder that allows patching the imported distutils modules."""
42
+
43
+ fullname = None
44
+
45
+ # lock[0] is threading.Lock(), but initialized lazily to avoid importing threading very early at startup,
46
+ # because there are gevent-based applications that need to be first to import threading by themselves.
47
+ # See https://github.com/pypa/virtualenv/issues/1895 for details.
48
+ lock = [] # noqa: RUF012
49
+
50
+ def find_spec(self, fullname, path, target=None): # noqa: ARG002
51
+ if fullname in _DISTUTILS_PATCH and self.fullname is None:
52
+ # initialize lock[0] lazily
53
+ if len(self.lock) == 0:
54
+ import threading
55
+
56
+ lock = threading.Lock()
57
+ # there is possibility that two threads T1 and T2 are simultaneously running into find_spec,
58
+ # observing .lock as empty, and further going into hereby initialization. However due to the GIL,
59
+ # list.append() operation is atomic and this way only one of the threads will "win" to put the lock
60
+ # - that every thread will use - into .lock[0].
61
+ # https://docs.python.org/3/faq/library.html#what-kinds-of-global-value-mutation-are-thread-safe
62
+ self.lock.append(lock)
63
+
64
+ from functools import partial
65
+ from importlib.util import find_spec
66
+
67
+ with self.lock[0]:
68
+ self.fullname = fullname
69
+ try:
70
+ spec = find_spec(fullname, path)
71
+ if spec is not None:
72
+ # https://www.python.org/dev/peps/pep-0451/#how-loading-will-work
73
+ is_new_api = hasattr(spec.loader, "exec_module")
74
+ func_name = "exec_module" if is_new_api else "load_module"
75
+ old = getattr(spec.loader, func_name)
76
+ func = self.exec_module if is_new_api else self.load_module
77
+ if old is not func:
78
+ try: # noqa: SIM105
79
+ setattr(spec.loader, func_name, partial(func, old))
80
+ except AttributeError:
81
+ pass # C-Extension loaders are r/o such as zipimporter with <3.7
82
+ return spec
83
+ finally:
84
+ self.fullname = None
85
+ return None
86
+
87
+ @staticmethod
88
+ def exec_module(old, module):
89
+ old(module)
90
+ if module.__name__ in _DISTUTILS_PATCH:
91
+ patch_dist(module)
92
+
93
+ @staticmethod
94
+ def load_module(old, name):
95
+ module = old(name)
96
+ if module.__name__ in _DISTUTILS_PATCH:
97
+ patch_dist(module)
98
+ return module
99
+
100
+
101
+ sys.meta_path.insert(0, _Finder())
data/diffusion/.venv/lib/python3.11/site-packages/charset_normalizer-3.4.9.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ uv
data/diffusion/.venv/lib/python3.11/site-packages/charset_normalizer-3.4.9.dist-info/METADATA ADDED
@@ -0,0 +1,827 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: charset-normalizer
3
+ Version: 3.4.9
4
+ Summary: The Real First Universal Charset Detector. Open, modern and actively maintained alternative to Chardet.
5
+ Author-email: "Ahmed R. TAHRI" <tahri.ahmed@proton.me>
6
+ Maintainer-email: "Ahmed R. TAHRI" <tahri.ahmed@proton.me>
7
+ License: MIT
8
+ Project-URL: Changelog, https://github.com/jawah/charset_normalizer/blob/master/CHANGELOG.md
9
+ Project-URL: Documentation, https://charset-normalizer.readthedocs.io/
10
+ Project-URL: Code, https://github.com/jawah/charset_normalizer
11
+ Project-URL: Issue tracker, https://github.com/jawah/charset_normalizer/issues
12
+ Keywords: encoding,charset,charset-detector,detector,normalization,unicode,chardet,detect
13
+ Classifier: Development Status :: 5 - Production/Stable
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.7
19
+ Classifier: Programming Language :: Python :: 3.8
20
+ Classifier: Programming Language :: Python :: 3.9
21
+ Classifier: Programming Language :: Python :: 3.10
22
+ Classifier: Programming Language :: Python :: 3.11
23
+ Classifier: Programming Language :: Python :: 3.12
24
+ Classifier: Programming Language :: Python :: 3.13
25
+ Classifier: Programming Language :: Python :: 3.14
26
+ Classifier: Programming Language :: Python :: 3 :: Only
27
+ Classifier: Programming Language :: Python :: Implementation :: CPython
28
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
29
+ Classifier: Programming Language :: Python :: Free Threading :: 4 - Resilient
30
+ Classifier: Topic :: Text Processing :: Linguistic
31
+ Classifier: Topic :: Utilities
32
+ Classifier: Typing :: Typed
33
+ Requires-Python: >=3.7
34
+ Description-Content-Type: text/markdown
35
+ License-File: LICENSE
36
+ Provides-Extra: unicode-backport
37
+ Dynamic: license-file
38
+
39
+ <h1 align="center">Charset Detection, for Everyone 👋</h1>
40
+
41
+ <p align="center">
42
+ <sup>The Real First Universal Charset Detector</sup><br>
43
+ <a href="https://pypi.org/project/charset-normalizer">
44
+ <img src="https://img.shields.io/pypi/pyversions/charset_normalizer.svg?orange=blue" />
45
+ </a>
46
+ <a href="https://pepy.tech/project/charset-normalizer/">
47
+ <img alt="Download Count Total" src="https://static.pepy.tech/badge/charset-normalizer/month" />
48
+ </a>
49
+ <a href="https://bestpractices.coreinfrastructure.org/projects/7297">
50
+ <img src="https://bestpractices.coreinfrastructure.org/projects/7297/badge">
51
+ </a>
52
+ </p>
53
+ <p align="center">
54
+ <sup><i>Featured Packages</i></sup><br>
55
+ <a href="https://github.com/jawah/niquests">
56
+ <img alt="Static Badge" src="https://img.shields.io/badge/Niquests-Most_Advanced_HTTP_Client-cyan">
57
+ </a>
58
+ <a href="https://github.com/jawah/wassima">
59
+ <img alt="Static Badge" src="https://img.shields.io/badge/Wassima-Certifi_Replacement-cyan">
60
+ </a>
61
+ </p>
62
+ <p align="center">
63
+ <sup><i>In other language (unofficial port - by the community)</i></sup><br>
64
+ <a href="https://github.com/nickspring/charset-normalizer-rs">
65
+ <img alt="Static Badge" src="https://img.shields.io/badge/Rust-red">
66
+ </a>
67
+ </p>
68
+
69
+ > A library that helps you read text from an unknown charset encoding.<br /> Motivated by `chardet`,
70
+ > I'm trying to resolve the issue by taking a new approach.
71
+ > All IANA character set names for which the Python core library provides codecs are supported.
72
+ > You can also register your own set of codecs, and yes, it would work as-is.
73
+
74
+ This project offers you an alternative to **Universal Charset Encoding Detector**, also known as **Chardet**.
75
+
76
+ | Feature | [Chardet](https://github.com/chardet/chardet) | Charset Normalizer | [cChardet](https://github.com/PyYoshi/cChardet) |
77
+ |--------------------------------------------------|:---------------------------------------------:|:-----------------------------------------------------------------------------------------------:|:-----------------------------------------------:|
78
+ | `Fast` | ✅ | ✅ | ✅ |
79
+ | `Universal`[^1] | ❌ | ✅ | ❌ |
80
+ | `Reliable` **without** distinguishable standards | ✅ | ✅ | ✅ |
81
+ | `Reliable` **with** distinguishable standards | ✅ | ✅ | ✅ |
82
+ | `License` | _Disputed_[^2]<br>_restrictive_ | MIT | MPL-1.1<br>_restrictive_ |
83
+ | `Native Python` | ✅ | ✅ | ❌ |
84
+ | `Detect spoken language` | ✅ | ✅ | N/A |
85
+ | `UnicodeDecodeError Safety` | ✅ | ✅ | ❌ |
86
+ | `Whl Size (min)` | 500 kB | 150 kB | ~200 kB |
87
+ | `Supported Encoding` | 99 | [99](https://charset-normalizer.readthedocs.io/en/latest/user/support.html#supported-encodings) | 40 |
88
+ | `Can register custom encoding` | ❌ | ✅ | ❌ |
89
+
90
+ <p align="center">
91
+ <img src="https://i.imgflip.com/373iay.gif" alt="Reading Normalized Text" width="226"/><img src="https://media.tenor.com/images/c0180f70732a18b4965448d33adba3d0/tenor.gif" alt="Cat Reading Text" width="200"/>
92
+ </p>
93
+
94
+ [^1]: They are clearly using specific code for a specific encoding even if covering most of used one.
95
+ [^2]: Chardet 7.0+ was relicensed from LGPL-2.1 to MIT following an AI-assisted rewrite. This relicensing is disputed on two independent grounds: **(a)** the original author [contests](https://github.com/chardet/chardet/issues/327) that the maintainer had the right to relicense, arguing the rewrite is a derivative work of the LGPL-licensed codebase since it was not a clean room implementation; **(b)** the copyright claim itself is [questionable](https://github.com/chardet/chardet/issues/334) given the code was primarily generated by an LLM, and AI-generated output may not be copyrightable under most jurisdictions. Either issue alone could undermine the MIT license. Beyond licensing, the rewrite raises questions about responsible use of AI in open source: key architectural ideas pioneered by charset-normalizer - notably decode-first validity filtering (our foundational approach since v1) and encoding pairwise similarity with the same algorithm and threshold — surfaced in chardet 7 without acknowledgment. The project also imported test files from charset-normalizer to train and benchmark against it, then claimed superior accuracy on those very files. Charset-normalizer has always been MIT-licensed, encoding-agnostic by design, and built on a verifiable human-authored history.
96
+
97
+ ## ⚡ Performance
98
+
99
+ This package offer better performances against Chardet. Here are some numbers.
100
+
101
+ | Package | Accuracy | Mean per file (ms) | File per sec (est) |
102
+ |---------------------------------------------------|:--------:|:------------------:|:------------------:|
103
+ | [chardet 7.4](https://github.com/chardet/chardet) | 89 % | 3 ms | 333 file/sec |
104
+ | charset-normalizer | **97 %** | 1 ms | 1000 file/sec |
105
+
106
+ | Package | 99th percentile | 95th percentile | 50th percentile |
107
+ |---------------------------------------------------|:---------------:|:---------------:|:---------------:|
108
+ | [chardet 7.4](https://github.com/chardet/chardet) | 28 ms | 16 ms | < 1 ms |
109
+ | charset-normalizer | 8 ms | 5 ms | 1 ms |
110
+
111
+ _updated as of July 2026 using CPython 3.12, Charset-Normalizer 3.4.8, and Chardet 7.4.3_
112
+
113
+ ~Chardet's performance on larger file (1MB+) are very poor. Expect huge difference on large payload.~ No longer the case since Chardet 7.0+
114
+
115
+ > Stats are generated using 400+ files using default parameters. More details on used files, see GHA workflows.
116
+ > And yes, these results might change at any time. The dataset can be updated to include more files.
117
+ > The actual delays heavily depends on your CPU capabilities. The factors should remain the same.
118
+ > Chardet claims on his documentation to have a greater accuracy than us based on the dataset they trained Chardet on(...)
119
+ > Well, it's normal, the opposite would have been worrying. Whereas charset-normalizer don't train on anything, our solution
120
+ > is based on a completely different algorithm, still heuristic through, it does not need weights across every encoding tables.
121
+
122
+ ## ✨ Installation
123
+
124
+ Using pip:
125
+
126
+ ```sh
127
+ pip install charset-normalizer -U
128
+ ```
129
+
130
+ ## 🚀 Basic Usage
131
+
132
+ ### CLI
133
+ This package comes with a CLI.
134
+
135
+ ```
136
+ usage: normalizer [-h] [-v] [-a] [-n] [-m] [-r] [-f] [-t THRESHOLD]
137
+ file [file ...]
138
+
139
+ The Real First Universal Charset Detector. Discover originating encoding used
140
+ on text file. Normalize text to unicode.
141
+
142
+ positional arguments:
143
+ files File(s) to be analysed
144
+
145
+ optional arguments:
146
+ -h, --help show this help message and exit
147
+ -v, --verbose Display complementary information about file if any.
148
+ Stdout will contain logs about the detection process.
149
+ -a, --with-alternative
150
+ Output complementary possibilities if any. Top-level
151
+ JSON WILL be a list.
152
+ -n, --normalize Permit to normalize input file. If not set, program
153
+ does not write anything.
154
+ -m, --minimal Only output the charset detected to STDOUT. Disabling
155
+ JSON output.
156
+ -r, --replace Replace file when trying to normalize it instead of
157
+ creating a new one.
158
+ -f, --force Replace file without asking if you are sure, use this
159
+ flag with caution.
160
+ -t THRESHOLD, --threshold THRESHOLD
161
+ Define a custom maximum amount of chaos allowed in
162
+ decoded content. 0. <= chaos <= 1.
163
+ --version Show version information and exit.
164
+ ```
165
+
166
+ ```bash
167
+ normalizer ./data/sample.1.fr.srt
168
+ ```
169
+
170
+ or
171
+
172
+ ```bash
173
+ python -m charset_normalizer ./data/sample.1.fr.srt
174
+ ```
175
+
176
+ 🎉 Since version 1.4.0 the CLI produce easily usable stdout result in JSON format.
177
+
178
+ ```json
179
+ {
180
+ "path": "/home/default/projects/charset_normalizer/data/sample.1.fr.srt",
181
+ "encoding": "cp1252",
182
+ "encoding_aliases": [
183
+ "1252",
184
+ "windows_1252"
185
+ ],
186
+ "alternative_encodings": [
187
+ "cp1254",
188
+ "cp1256",
189
+ "cp1258",
190
+ "iso8859_14",
191
+ "iso8859_15",
192
+ "iso8859_16",
193
+ "iso8859_3",
194
+ "iso8859_9",
195
+ "latin_1",
196
+ "mbcs"
197
+ ],
198
+ "language": "French",
199
+ "alphabets": [
200
+ "Basic Latin",
201
+ "Latin-1 Supplement"
202
+ ],
203
+ "has_sig_or_bom": false,
204
+ "chaos": 0.149,
205
+ "coherence": 97.152,
206
+ "unicode_path": null,
207
+ "is_preferred": true
208
+ }
209
+ ```
210
+
211
+ ### Python
212
+ *Just print out normalized text*
213
+ ```python
214
+ from charset_normalizer import from_path
215
+
216
+ results = from_path('./my_subtitle.srt')
217
+
218
+ print(str(results.best()))
219
+ ```
220
+
221
+ *Upgrade your code without effort*
222
+ ```python
223
+ from charset_normalizer import detect
224
+ ```
225
+
226
+ The above code will behave the same as **chardet**. We ensure that we offer the best (reasonable) BC result possible.
227
+
228
+ See the docs for advanced usage : [readthedocs.io](https://charset-normalizer.readthedocs.io/en/latest/)
229
+
230
+ ## 😇 Why
231
+
232
+ When I started using Chardet, I noticed that it was not suited to my expectations, and I wanted to propose a
233
+ reliable alternative using a completely different method. Also! I never back down on a good challenge!
234
+
235
+ I **don't care** about the **originating charset** encoding, because **two different tables** can
236
+ produce **two identical rendered string.**
237
+ What I want is to get readable text, the best I can.
238
+
239
+ In a way, **I'm brute forcing text decoding.** How cool is that ? 😎
240
+
241
+ Don't confuse package **ftfy** with charset-normalizer or chardet. ftfy goal is to repair Unicode string whereas charset-normalizer to convert raw file in unknown encoding to unicode.
242
+
243
+ ## 🍰 How
244
+
245
+ - Discard all charset encoding table that could not fit the binary content.
246
+ - Measure noise, or the mess once opened (by chunks) with a corresponding charset encoding.
247
+ - Extract matches with the lowest mess detected.
248
+ - Additionally, we measure coherence / probe for a language.
249
+
250
+ **Wait a minute**, what is noise/mess and coherence according to **YOU ?**
251
+
252
+ *Noise :* I opened hundred of text files, **written by humans**, with the wrong encoding table. **I observed**, then
253
+ **I established** some ground rules about **what is obvious** when **it seems like** a mess (aka. defining noise in rendered text).
254
+ I know that my interpretation of what is noise is probably incomplete, feel free to contribute in order to
255
+ improve or rewrite it.
256
+
257
+ *Coherence :* For each language there is on earth, we have computed ranked letter appearance occurrences (the best we can). So I thought
258
+ that intel is worth something here. So I use those records against decoded text to check if I can detect intelligent design.
259
+
260
+ ## ⚡ Known limitations
261
+
262
+ - Language detection is unreliable when text contains two or more languages sharing identical letters. (eg. HTML (english tags) + Turkish content (Sharing Latin characters))
263
+ - Every charset detector heavily depends on sufficient content. In common cases, do not bother run detection on very tiny content.
264
+
265
+ ## ⚠️ About Python EOLs
266
+
267
+ **If you are running:**
268
+
269
+ - Python >=2.7,<3.5: Unsupported
270
+ - Python 3.5: charset-normalizer < 2.1
271
+ - Python 3.6: charset-normalizer < 3.1
272
+
273
+ Upgrade your Python interpreter as soon as possible.
274
+
275
+ ## 👤 Contributing
276
+
277
+ Contributions, issues and feature requests are very much welcome.<br />
278
+ Feel free to check [issues page](https://github.com/ousret/charset_normalizer/issues) if you want to contribute.
279
+
280
+ ## 📝 License
281
+
282
+ Copyright © [Ahmed TAHRI @Ousret](https://github.com/Ousret).<br />
283
+ This project is [MIT](https://github.com/Ousret/charset_normalizer/blob/master/LICENSE) licensed.
284
+
285
+ Characters frequencies used in this project © 2012 [Denny Vrandečić](http://simia.net/letters/)
286
+
287
+ ## 💼 For Enterprise
288
+
289
+ Professional support for charset-normalizer is available as part of the [Tidelift
290
+ Subscription][1]. Tidelift gives software development teams a single source for
291
+ purchasing and maintaining their software, with professional grade assurances
292
+ from the experts who know it best, while seamlessly integrating with existing
293
+ tools.
294
+
295
+ [1]: https://tidelift.com/subscription/pkg/pypi-charset-normalizer?utm_source=pypi-charset-normalizer&utm_medium=readme
296
+
297
+ [![OpenSSF Best Practices](https://www.bestpractices.dev/projects/7297/badge)](https://www.bestpractices.dev/projects/7297)
298
+
299
+ # Changelog
300
+ All notable changes to charset-normalizer will be documented in this file. This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
301
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
302
+
303
+ ## [3.4.9](https://github.com/Ousret/charset_normalizer/compare/3.4.8...3.4.9) (2026-07-07)
304
+
305
+ ### Fixed
306
+ - Regression in our fallback path leading to a decode error. (#771)
307
+ We've yanked 3.4.8 as a result of that bug.
308
+
309
+ ## [3.4.8](https://github.com/Ousret/charset_normalizer/compare/3.4.7...3.4.8) (2026-07-06)
310
+
311
+ ### Fixed
312
+ - Wall import time due to cascade codec imports for our multibyte first sort of iana supported codecs (#742)
313
+ - Unnecessary json import at runtime (#753)
314
+ - Inverse capitalization not seen by noise detector (#731)
315
+
316
+ ### Changed
317
+ - No longer holding a global cache for our noise / coherence measurements. Relax RSS memory usage.
318
+ - Micro-optimizations in our noise / coherence measurements.
319
+ - No longer using regex search by default for our preemptive charset mark algorithm.
320
+ - Raised upperbound of setuptools to v83.
321
+ - Raised upperbound of mypy(c) to v2.1.
322
+
323
+ ### Removed
324
+ - Redundant UTF7 BOM marker (#730)
325
+
326
+ ## [3.4.7](https://github.com/Ousret/charset_normalizer/compare/3.4.6...3.4.7) (2026-04-02)
327
+
328
+ ### Changed
329
+ - Pre-built optimized version using mypy[c] v1.20.
330
+ - Relax `setuptools` constraint to `setuptools>=68,<82.1`.
331
+
332
+ ### Fixed
333
+ - Correctly remove SIG remnant in utf-7 decoded string. (#718) (#716)
334
+
335
+ ## [3.4.6](https://github.com/Ousret/charset_normalizer/compare/3.4.5...3.4.6) (2026-03-15)
336
+
337
+ ### Changed
338
+ - Flattened the logic in `charset_normalizer.md` for higher performance. Removed `eligible(..)` and `feed(...)`
339
+ in favor of `feed_info(...)`.
340
+ - Raised upper bound for mypy[c] to 1.20, for our optimized version.
341
+ - Updated `UNICODE_RANGES_COMBINED` using Unicode blocks v17.
342
+
343
+ ### Fixed
344
+ - Edge case where noise difference between two candidates can be almost insignificant. (#672)
345
+ - CLI `--normalize` writing to wrong path when passing multiple files in. (#702)
346
+
347
+ ### Misc
348
+ - Freethreaded pre-built wheels now shipped in PyPI starting with 3.14t. (#616)
349
+
350
+ ## [3.4.5](https://github.com/Ousret/charset_normalizer/compare/3.4.4...3.4.5) (2026-03-06)
351
+
352
+ ### Changed
353
+ - Update `setuptools` constraint to `setuptools>=68,<=82`.
354
+ - Raised upper bound of mypyc for the optional pre-built extension to v1.19.1
355
+
356
+ ### Fixed
357
+ - Add explicit link to lib math in our optimized build. (#692)
358
+ - Logger level not restored correctly for empty byte sequences. (#701)
359
+ - TypeError when passing bytearray to from_bytes. (#703)
360
+
361
+ ### Misc
362
+ - Applied safe micro-optimizations in both our noise detector and language detector.
363
+ - Rewrote the `query_yes_no` function (inside CLI) to avoid using ambiguous licensed code.
364
+ - Added `cd.py` submodule into mypyc optional compilation to reduce further the performance impact.
365
+
366
+ ## [3.4.4](https://github.com/Ousret/charset_normalizer/compare/3.4.2...3.4.4) (2025-10-13)
367
+
368
+ ### Changed
369
+ - Bound `setuptools` to a specific constraint `setuptools>=68,<=81`.
370
+ - Raised upper bound of mypyc for the optional pre-built extension to v1.18.2
371
+
372
+ ### Removed
373
+ - `setuptools-scm` as a build dependency.
374
+
375
+ ### Misc
376
+ - Enforced hashes in `dev-requirements.txt` and created `ci-requirements.txt` for security purposes.
377
+ - Additional pre-built wheels for riscv64, s390x, and armv7l architectures.
378
+ - Restore ` multiple.intoto.jsonl` in GitHub releases in addition to individual attestation file per wheel.
379
+
380
+ ## [3.4.3](https://github.com/Ousret/charset_normalizer/compare/3.4.2...3.4.3) (2025-08-09)
381
+
382
+ ### Changed
383
+ - mypy(c) is no longer a required dependency at build time if `CHARSET_NORMALIZER_USE_MYPYC` isn't set to `1`. (#595) (#583)
384
+ - automatically lower confidence on small bytes samples that are not Unicode in `detect` output legacy function. (#391)
385
+
386
+ ### Added
387
+ - Custom build backend to overcome inability to mark mypy as an optional dependency in the build phase.
388
+ - Support for Python 3.14
389
+
390
+ ### Fixed
391
+ - sdist archive contained useless directories.
392
+ - automatically fallback on valid UTF-16 or UTF-32 even if the md says it's noisy. (#633)
393
+
394
+ ### Misc
395
+ - SBOM are automatically published to the relevant GitHub release to comply with regulatory changes.
396
+ Each published wheel comes with its SBOM. We choose CycloneDX as the format.
397
+ - Prebuilt optimized wheel are no longer distributed by default for CPython 3.7 due to a change in cibuildwheel.
398
+
399
+ ## [3.4.2](https://github.com/Ousret/charset_normalizer/compare/3.4.1...3.4.2) (2025-05-02)
400
+
401
+ ### Fixed
402
+ - Addressed the DeprecationWarning in our CLI regarding `argparse.FileType` by backporting the target class into the package. (#591)
403
+ - Improved the overall reliability of the detector with CJK Ideographs. (#605) (#587)
404
+
405
+ ### Changed
406
+ - Optional mypyc compilation upgraded to version 1.15 for Python >= 3.8
407
+
408
+ ## [3.4.1](https://github.com/Ousret/charset_normalizer/compare/3.4.0...3.4.1) (2024-12-24)
409
+
410
+ ### Changed
411
+ - Project metadata are now stored using `pyproject.toml` instead of `setup.cfg` using setuptools as the build backend.
412
+ - Enforce annotation delayed loading for a simpler and consistent types in the project.
413
+ - Optional mypyc compilation upgraded to version 1.14 for Python >= 3.8
414
+
415
+ ### Added
416
+ - pre-commit configuration.
417
+ - noxfile.
418
+
419
+ ### Removed
420
+ - `build-requirements.txt` as per using `pyproject.toml` native build configuration.
421
+ - `bin/integration.py` and `bin/serve.py` in favor of downstream integration test (see noxfile).
422
+ - `setup.cfg` in favor of `pyproject.toml` metadata configuration.
423
+ - Unused `utils.range_scan` function.
424
+
425
+ ### Fixed
426
+ - Converting content to Unicode bytes may insert `utf_8` instead of preferred `utf-8`. (#572)
427
+ - Deprecation warning "'count' is passed as positional argument" when converting to Unicode bytes on Python 3.13+
428
+
429
+ ## [3.4.0](https://github.com/Ousret/charset_normalizer/compare/3.3.2...3.4.0) (2024-10-08)
430
+
431
+ ### Added
432
+ - Argument `--no-preemptive` in the CLI to prevent the detector to search for hints.
433
+ - Support for Python 3.13 (#512)
434
+
435
+ ### Fixed
436
+ - Relax the TypeError exception thrown when trying to compare a CharsetMatch with anything else than a CharsetMatch.
437
+ - Improved the general reliability of the detector based on user feedbacks. (#520) (#509) (#498) (#407) (#537)
438
+ - Declared charset in content (preemptive detection) not changed when converting to utf-8 bytes. (#381)
439
+
440
+ ## [3.3.2](https://github.com/Ousret/charset_normalizer/compare/3.3.1...3.3.2) (2023-10-31)
441
+
442
+ ### Fixed
443
+ - Unintentional memory usage regression when using large payload that match several encoding (#376)
444
+ - Regression on some detection case showcased in the documentation (#371)
445
+
446
+ ### Added
447
+ - Noise (md) probe that identify malformed arabic representation due to the presence of letters in isolated form (credit to my wife)
448
+
449
+ ## [3.3.1](https://github.com/Ousret/charset_normalizer/compare/3.3.0...3.3.1) (2023-10-22)
450
+
451
+ ### Changed
452
+ - Optional mypyc compilation upgraded to version 1.6.1 for Python >= 3.8
453
+ - Improved the general detection reliability based on reports from the community
454
+
455
+ ## [3.3.0](https://github.com/Ousret/charset_normalizer/compare/3.2.0...3.3.0) (2023-09-30)
456
+
457
+ ### Added
458
+ - Allow to execute the CLI (e.g. normalizer) through `python -m charset_normalizer.cli` or `python -m charset_normalizer`
459
+ - Support for 9 forgotten encoding that are supported by Python but unlisted in `encoding.aliases` as they have no alias (#323)
460
+
461
+ ### Removed
462
+ - (internal) Redundant utils.is_ascii function and unused function is_private_use_only
463
+ - (internal) charset_normalizer.assets is moved inside charset_normalizer.constant
464
+
465
+ ### Changed
466
+ - (internal) Unicode code blocks in constants are updated using the latest v15.0.0 definition to improve detection
467
+ - Optional mypyc compilation upgraded to version 1.5.1 for Python >= 3.8
468
+
469
+ ### Fixed
470
+ - Unable to properly sort CharsetMatch when both chaos/noise and coherence were close due to an unreachable condition in \_\_lt\_\_ (#350)
471
+
472
+ ## [3.2.0](https://github.com/Ousret/charset_normalizer/compare/3.1.0...3.2.0) (2023-06-07)
473
+
474
+ ### Changed
475
+ - Typehint for function `from_path` no longer enforce `PathLike` as its first argument
476
+ - Minor improvement over the global detection reliability
477
+
478
+ ### Added
479
+ - Introduce function `is_binary` that relies on main capabilities, and optimized to detect binaries
480
+ - Propagate `enable_fallback` argument throughout `from_bytes`, `from_path`, and `from_fp` that allow a deeper control over the detection (default True)
481
+ - Explicit support for Python 3.12
482
+
483
+ ### Fixed
484
+ - Edge case detection failure where a file would contain 'very-long' camel cased word (Issue #289)
485
+
486
+ ## [3.1.0](https://github.com/Ousret/charset_normalizer/compare/3.0.1...3.1.0) (2023-03-06)
487
+
488
+ ### Added
489
+ - Argument `should_rename_legacy` for legacy function `detect` and disregard any new arguments without errors (PR #262)
490
+
491
+ ### Removed
492
+ - Support for Python 3.6 (PR #260)
493
+
494
+ ### Changed
495
+ - Optional speedup provided by mypy/c 1.0.1
496
+
497
+ ## [3.0.1](https://github.com/Ousret/charset_normalizer/compare/3.0.0...3.0.1) (2022-11-18)
498
+
499
+ ### Fixed
500
+ - Multi-bytes cutter/chunk generator did not always cut correctly (PR #233)
501
+
502
+ ### Changed
503
+ - Speedup provided by mypy/c 0.990 on Python >= 3.7
504
+
505
+ ## [3.0.0](https://github.com/Ousret/charset_normalizer/compare/2.1.1...3.0.0) (2022-10-20)
506
+
507
+ ### Added
508
+ - Extend the capability of explain=True when cp_isolation contains at most two entries (min one), will log in details of the Mess-detector results
509
+ - Support for alternative language frequency set in charset_normalizer.assets.FREQUENCIES
510
+ - Add parameter `language_threshold` in `from_bytes`, `from_path` and `from_fp` to adjust the minimum expected coherence ratio
511
+ - `normalizer --version` now specify if current version provide extra speedup (meaning mypyc compilation whl)
512
+
513
+ ### Changed
514
+ - Build with static metadata using 'build' frontend
515
+ - Make the language detection stricter
516
+ - Optional: Module `md.py` can be compiled using Mypyc to provide an extra speedup up to 4x faster than v2.1
517
+
518
+ ### Fixed
519
+ - CLI with opt --normalize fail when using full path for files
520
+ - TooManyAccentuatedPlugin induce false positive on the mess detection when too few alpha character have been fed to it
521
+ - Sphinx warnings when generating the documentation
522
+
523
+ ### Removed
524
+ - Coherence detector no longer return 'Simple English' instead return 'English'
525
+ - Coherence detector no longer return 'Classical Chinese' instead return 'Chinese'
526
+ - Breaking: Method `first()` and `best()` from CharsetMatch
527
+ - UTF-7 will no longer appear as "detected" without a recognized SIG/mark (is unreliable/conflict with ASCII)
528
+ - Breaking: Class aliases CharsetDetector, CharsetDoctor, CharsetNormalizerMatch and CharsetNormalizerMatches
529
+ - Breaking: Top-level function `normalize`
530
+ - Breaking: Properties `chaos_secondary_pass`, `coherence_non_latin` and `w_counter` from CharsetMatch
531
+ - Support for the backport `unicodedata2`
532
+
533
+ ## [3.0.0rc1](https://github.com/Ousret/charset_normalizer/compare/3.0.0b2...3.0.0rc1) (2022-10-18)
534
+
535
+ ### Added
536
+ - Extend the capability of explain=True when cp_isolation contains at most two entries (min one), will log in details of the Mess-detector results
537
+ - Support for alternative language frequency set in charset_normalizer.assets.FREQUENCIES
538
+ - Add parameter `language_threshold` in `from_bytes`, `from_path` and `from_fp` to adjust the minimum expected coherence ratio
539
+
540
+ ### Changed
541
+ - Build with static metadata using 'build' frontend
542
+ - Make the language detection stricter
543
+
544
+ ### Fixed
545
+ - CLI with opt --normalize fail when using full path for files
546
+ - TooManyAccentuatedPlugin induce false positive on the mess detection when too few alpha character have been fed to it
547
+
548
+ ### Removed
549
+ - Coherence detector no longer return 'Simple English' instead return 'English'
550
+ - Coherence detector no longer return 'Classical Chinese' instead return 'Chinese'
551
+
552
+ ## [3.0.0b2](https://github.com/Ousret/charset_normalizer/compare/3.0.0b1...3.0.0b2) (2022-08-21)
553
+
554
+ ### Added
555
+ - `normalizer --version` now specify if current version provide extra speedup (meaning mypyc compilation whl)
556
+
557
+ ### Removed
558
+ - Breaking: Method `first()` and `best()` from CharsetMatch
559
+ - UTF-7 will no longer appear as "detected" without a recognized SIG/mark (is unreliable/conflict with ASCII)
560
+
561
+ ### Fixed
562
+ - Sphinx warnings when generating the documentation
563
+
564
+ ## [3.0.0b1](https://github.com/Ousret/charset_normalizer/compare/2.1.0...3.0.0b1) (2022-08-15)
565
+
566
+ ### Changed
567
+ - Optional: Module `md.py` can be compiled using Mypyc to provide an extra speedup up to 4x faster than v2.1
568
+
569
+ ### Removed
570
+ - Breaking: Class aliases CharsetDetector, CharsetDoctor, CharsetNormalizerMatch and CharsetNormalizerMatches
571
+ - Breaking: Top-level function `normalize`
572
+ - Breaking: Properties `chaos_secondary_pass`, `coherence_non_latin` and `w_counter` from CharsetMatch
573
+ - Support for the backport `unicodedata2`
574
+
575
+ ## [2.1.1](https://github.com/Ousret/charset_normalizer/compare/2.1.0...2.1.1) (2022-08-19)
576
+
577
+ ### Deprecated
578
+ - Function `normalize` scheduled for removal in 3.0
579
+
580
+ ### Changed
581
+ - Removed useless call to decode in fn is_unprintable (#206)
582
+
583
+ ### Fixed
584
+ - Third-party library (i18n xgettext) crashing not recognizing utf_8 (PEP 263) with underscore from [@aleksandernovikov](https://github.com/aleksandernovikov) (#204)
585
+
586
+ ## [2.1.0](https://github.com/Ousret/charset_normalizer/compare/2.0.12...2.1.0) (2022-06-19)
587
+
588
+ ### Added
589
+ - Output the Unicode table version when running the CLI with `--version` (PR #194)
590
+
591
+ ### Changed
592
+ - Reuse decoded buffer for single byte character sets from [@nijel](https://github.com/nijel) (PR #175)
593
+ - Fixing some performance bottlenecks from [@deedy5](https://github.com/deedy5) (PR #183)
594
+
595
+ ### Fixed
596
+ - Workaround potential bug in cpython with Zero Width No-Break Space located in Arabic Presentation Forms-B, Unicode 1.1 not acknowledged as space (PR #175)
597
+ - CLI default threshold aligned with the API threshold from [@oleksandr-kuzmenko](https://github.com/oleksandr-kuzmenko) (PR #181)
598
+
599
+ ### Removed
600
+ - Support for Python 3.5 (PR #192)
601
+
602
+ ### Deprecated
603
+ - Use of backport unicodedata from `unicodedata2` as Python is quickly catching up, scheduled for removal in 3.0 (PR #194)
604
+
605
+ ## [2.0.12](https://github.com/Ousret/charset_normalizer/compare/2.0.11...2.0.12) (2022-02-12)
606
+
607
+ ### Fixed
608
+ - ASCII miss-detection on rare cases (PR #170)
609
+
610
+ ## [2.0.11](https://github.com/Ousret/charset_normalizer/compare/2.0.10...2.0.11) (2022-01-30)
611
+
612
+ ### Added
613
+ - Explicit support for Python 3.11 (PR #164)
614
+
615
+ ### Changed
616
+ - The logging behavior have been completely reviewed, now using only TRACE and DEBUG levels (PR #163 #165)
617
+
618
+ ## [2.0.10](https://github.com/Ousret/charset_normalizer/compare/2.0.9...2.0.10) (2022-01-04)
619
+
620
+ ### Fixed
621
+ - Fallback match entries might lead to UnicodeDecodeError for large bytes sequence (PR #154)
622
+
623
+ ### Changed
624
+ - Skipping the language-detection (CD) on ASCII (PR #155)
625
+
626
+ ## [2.0.9](https://github.com/Ousret/charset_normalizer/compare/2.0.8...2.0.9) (2021-12-03)
627
+
628
+ ### Changed
629
+ - Moderating the logging impact (since 2.0.8) for specific environments (PR #147)
630
+
631
+ ### Fixed
632
+ - Wrong logging level applied when setting kwarg `explain` to True (PR #146)
633
+
634
+ ## [2.0.8](https://github.com/Ousret/charset_normalizer/compare/2.0.7...2.0.8) (2021-11-24)
635
+ ### Changed
636
+ - Improvement over Vietnamese detection (PR #126)
637
+ - MD improvement on trailing data and long foreign (non-pure latin) data (PR #124)
638
+ - Efficiency improvements in cd/alphabet_languages from [@adbar](https://github.com/adbar) (PR #122)
639
+ - call sum() without an intermediary list following PEP 289 recommendations from [@adbar](https://github.com/adbar) (PR #129)
640
+ - Code style as refactored by Sourcery-AI (PR #131)
641
+ - Minor adjustment on the MD around european words (PR #133)
642
+ - Remove and replace SRTs from assets / tests (PR #139)
643
+ - Initialize the library logger with a `NullHandler` by default from [@nmaynes](https://github.com/nmaynes) (PR #135)
644
+ - Setting kwarg `explain` to True will add provisionally (bounded to function lifespan) a specific stream handler (PR #135)
645
+
646
+ ### Fixed
647
+ - Fix large (misleading) sequence giving UnicodeDecodeError (PR #137)
648
+ - Avoid using too insignificant chunk (PR #137)
649
+
650
+ ### Added
651
+ - Add and expose function `set_logging_handler` to configure a specific StreamHandler from [@nmaynes](https://github.com/nmaynes) (PR #135)
652
+ - Add `CHANGELOG.md` entries, format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) (PR #141)
653
+
654
+ ## [2.0.7](https://github.com/Ousret/charset_normalizer/compare/2.0.6...2.0.7) (2021-10-11)
655
+ ### Added
656
+ - Add support for Kazakh (Cyrillic) language detection (PR #109)
657
+
658
+ ### Changed
659
+ - Further, improve inferring the language from a given single-byte code page (PR #112)
660
+ - Vainly trying to leverage PEP263 when PEP3120 is not supported (PR #116)
661
+ - Refactoring for potential performance improvements in loops from [@adbar](https://github.com/adbar) (PR #113)
662
+ - Various detection improvement (MD+CD) (PR #117)
663
+
664
+ ### Removed
665
+ - Remove redundant logging entry about detected language(s) (PR #115)
666
+
667
+ ### Fixed
668
+ - Fix a minor inconsistency between Python 3.5 and other versions regarding language detection (PR #117 #102)
669
+
670
+ ## [2.0.6](https://github.com/Ousret/charset_normalizer/compare/2.0.5...2.0.6) (2021-09-18)
671
+ ### Fixed
672
+ - Unforeseen regression with the loss of the backward-compatibility with some older minor of Python 3.5.x (PR #100)
673
+ - Fix CLI crash when using --minimal output in certain cases (PR #103)
674
+
675
+ ### Changed
676
+ - Minor improvement to the detection efficiency (less than 1%) (PR #106 #101)
677
+
678
+ ## [2.0.5](https://github.com/Ousret/charset_normalizer/compare/2.0.4...2.0.5) (2021-09-14)
679
+ ### Changed
680
+ - The project now comply with: flake8, mypy, isort and black to ensure a better overall quality (PR #81)
681
+ - The BC-support with v1.x was improved, the old staticmethods are restored (PR #82)
682
+ - The Unicode detection is slightly improved (PR #93)
683
+ - Add syntax sugar \_\_bool\_\_ for results CharsetMatches list-container (PR #91)
684
+
685
+ ### Removed
686
+ - The project no longer raise warning on tiny content given for detection, will be simply logged as warning instead (PR #92)
687
+
688
+ ### Fixed
689
+ - In some rare case, the chunks extractor could cut in the middle of a multi-byte character and could mislead the mess detection (PR #95)
690
+ - Some rare 'space' characters could trip up the UnprintablePlugin/Mess detection (PR #96)
691
+ - The MANIFEST.in was not exhaustive (PR #78)
692
+
693
+ ## [2.0.4](https://github.com/Ousret/charset_normalizer/compare/2.0.3...2.0.4) (2021-07-30)
694
+ ### Fixed
695
+ - The CLI no longer raise an unexpected exception when no encoding has been found (PR #70)
696
+ - Fix accessing the 'alphabets' property when the payload contains surrogate characters (PR #68)
697
+ - The logger could mislead (explain=True) on detected languages and the impact of one MBCS match (PR #72)
698
+ - Submatch factoring could be wrong in rare edge cases (PR #72)
699
+ - Multiple files given to the CLI were ignored when publishing results to STDOUT. (After the first path) (PR #72)
700
+ - Fix line endings from CRLF to LF for certain project files (PR #67)
701
+
702
+ ### Changed
703
+ - Adjust the MD to lower the sensitivity, thus improving the global detection reliability (PR #69 #76)
704
+ - Allow fallback on specified encoding if any (PR #71)
705
+
706
+ ## [2.0.3](https://github.com/Ousret/charset_normalizer/compare/2.0.2...2.0.3) (2021-07-16)
707
+ ### Changed
708
+ - Part of the detection mechanism has been improved to be less sensitive, resulting in more accurate detection results. Especially ASCII. (PR #63)
709
+ - According to the community wishes, the detection will fall back on ASCII or UTF-8 in a last-resort case. (PR #64)
710
+
711
+ ## [2.0.2](https://github.com/Ousret/charset_normalizer/compare/2.0.1...2.0.2) (2021-07-15)
712
+ ### Fixed
713
+ - Empty/Too small JSON payload miss-detection fixed. Report from [@tseaver](https://github.com/tseaver) (PR #59)
714
+
715
+ ### Changed
716
+ - Don't inject unicodedata2 into sys.modules from [@akx](https://github.com/akx) (PR #57)
717
+
718
+ ## [2.0.1](https://github.com/Ousret/charset_normalizer/compare/2.0.0...2.0.1) (2021-07-13)
719
+ ### Fixed
720
+ - Make it work where there isn't a filesystem available, dropping assets frequencies.json. Report from [@sethmlarson](https://github.com/sethmlarson). (PR #55)
721
+ - Using explain=False permanently disable the verbose output in the current runtime (PR #47)
722
+ - One log entry (language target preemptive) was not show in logs when using explain=True (PR #47)
723
+ - Fix undesired exception (ValueError) on getitem of instance CharsetMatches (PR #52)
724
+
725
+ ### Changed
726
+ - Public function normalize default args values were not aligned with from_bytes (PR #53)
727
+
728
+ ### Added
729
+ - You may now use charset aliases in cp_isolation and cp_exclusion arguments (PR #47)
730
+
731
+ ## [2.0.0](https://github.com/Ousret/charset_normalizer/compare/1.4.1...2.0.0) (2021-07-02)
732
+ ### Changed
733
+ - 4x to 5 times faster than the previous 1.4.0 release. At least 2x faster than Chardet.
734
+ - Accent has been made on UTF-8 detection, should perform rather instantaneous.
735
+ - The backward compatibility with Chardet has been greatly improved. The legacy detect function returns an identical charset name whenever possible.
736
+ - The detection mechanism has been slightly improved, now Turkish content is detected correctly (most of the time)
737
+ - The program has been rewritten to ease the readability and maintainability. (+Using static typing)+
738
+ - utf_7 detection has been reinstated.
739
+
740
+ ### Removed
741
+ - This package no longer require anything when used with Python 3.5 (Dropped cached_property)
742
+ - Removed support for these languages: Catalan, Esperanto, Kazakh, Baque, Volapük, Azeri, Galician, Nynorsk, Macedonian, and Serbocroatian.
743
+ - The exception hook on UnicodeDecodeError has been removed.
744
+
745
+ ### Deprecated
746
+ - Methods coherence_non_latin, w_counter, chaos_secondary_pass of the class CharsetMatch are now deprecated and scheduled for removal in v3.0
747
+
748
+ ### Fixed
749
+ - The CLI output used the relative path of the file(s). Should be absolute.
750
+
751
+ ## [1.4.1](https://github.com/Ousret/charset_normalizer/compare/1.4.0...1.4.1) (2021-05-28)
752
+ ### Fixed
753
+ - Logger configuration/usage no longer conflict with others (PR #44)
754
+
755
+ ## [1.4.0](https://github.com/Ousret/charset_normalizer/compare/1.3.9...1.4.0) (2021-05-21)
756
+ ### Removed
757
+ - Using standard logging instead of using the package loguru.
758
+ - Dropping nose test framework in favor of the maintained pytest.
759
+ - Choose to not use dragonmapper package to help with gibberish Chinese/CJK text.
760
+ - Require cached_property only for Python 3.5 due to constraint. Dropping for every other interpreter version.
761
+ - Stop support for UTF-7 that does not contain a SIG.
762
+ - Dropping PrettyTable, replaced with pure JSON output in CLI.
763
+
764
+ ### Fixed
765
+ - BOM marker in a CharsetNormalizerMatch instance could be False in rare cases even if obviously present. Due to the sub-match factoring process.
766
+ - Not searching properly for the BOM when trying utf32/16 parent codec.
767
+
768
+ ### Changed
769
+ - Improving the package final size by compressing frequencies.json.
770
+ - Huge improvement over the larges payload.
771
+
772
+ ### Added
773
+ - CLI now produces JSON consumable output.
774
+ - Return ASCII if given sequences fit. Given reasonable confidence.
775
+
776
+ ## [1.3.9](https://github.com/Ousret/charset_normalizer/compare/1.3.8...1.3.9) (2021-05-13)
777
+
778
+ ### Fixed
779
+ - In some very rare cases, you may end up getting encode/decode errors due to a bad bytes payload (PR #40)
780
+
781
+ ## [1.3.8](https://github.com/Ousret/charset_normalizer/compare/1.3.7...1.3.8) (2021-05-12)
782
+
783
+ ### Fixed
784
+ - Empty given payload for detection may cause an exception if trying to access the `alphabets` property. (PR #39)
785
+
786
+ ## [1.3.7](https://github.com/Ousret/charset_normalizer/compare/1.3.6...1.3.7) (2021-05-12)
787
+
788
+ ### Fixed
789
+ - The legacy detect function should return UTF-8-SIG if sig is present in the payload. (PR #38)
790
+
791
+ ## [1.3.6](https://github.com/Ousret/charset_normalizer/compare/1.3.5...1.3.6) (2021-02-09)
792
+
793
+ ### Changed
794
+ - Amend the previous release to allow prettytable 2.0 (PR #35)
795
+
796
+ ## [1.3.5](https://github.com/Ousret/charset_normalizer/compare/1.3.4...1.3.5) (2021-02-08)
797
+
798
+ ### Fixed
799
+ - Fix error while using the package with a python pre-release interpreter (PR #33)
800
+
801
+ ### Changed
802
+ - Dependencies refactoring, constraints revised.
803
+
804
+ ### Added
805
+ - Add python 3.9 and 3.10 to the supported interpreters
806
+
807
+ MIT License
808
+
809
+ Copyright (c) 2025 TAHRI Ahmed R.
810
+
811
+ Permission is hereby granted, free of charge, to any person obtaining a copy
812
+ of this software and associated documentation files (the "Software"), to deal
813
+ in the Software without restriction, including without limitation the rights
814
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
815
+ copies of the Software, and to permit persons to whom the Software is
816
+ furnished to do so, subject to the following conditions:
817
+
818
+ The above copyright notice and this permission notice shall be included in all
819
+ copies or substantial portions of the Software.
820
+
821
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
822
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
823
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
824
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
825
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
826
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
827
+ SOFTWARE.
data/diffusion/.venv/lib/python3.11/site-packages/charset_normalizer-3.4.9.dist-info/RECORD ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ../../../bin/normalizer,sha256=i0ixk3EJRXTC1lnQ8uohOue_U4rOAgVarutB41IVcKc,344
2
+ ada92cb5d92a588d1b93__mypyc.cpython-311-x86_64-linux-gnu.so,sha256=v_iWTzRsZXn2W3DwYZnauFr4Yf0A8w8xs_8j7mfTbFw,445952
3
+ charset_normalizer-3.4.9.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2
4
+ charset_normalizer-3.4.9.dist-info/METADATA,sha256=DdPeF2CbDbZL0dRkPFvQ3TW16zxb53-LF7wZDy9KKsA,41678
5
+ charset_normalizer-3.4.9.dist-info/RECORD,,
6
+ charset_normalizer-3.4.9.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ charset_normalizer-3.4.9.dist-info/WHEEL,sha256=nn5AcWa_wYrb7xwtxEqCCax8LY-Ol14wJNGDK76X20E,190
8
+ charset_normalizer-3.4.9.dist-info/entry_points.txt,sha256=ADSTKrkXZ3hhdOVFi6DcUEHQRS0xfxDIE_pEz4wLIXA,65
9
+ charset_normalizer-3.4.9.dist-info/licenses/LICENSE,sha256=bQ1Bv-FwrGx9wkjJpj4lTQ-0WmDVCoJX0K-SxuJJuIc,1071
10
+ charset_normalizer-3.4.9.dist-info/top_level.txt,sha256=y65Zf_GLs5FHscGHzcUTGAldXcp5mEVXbh8Mo0ZlmWs,47
11
+ charset_normalizer/__init__.py,sha256=OKRxRv2Zhnqk00tqkN0c1BtJjm165fWXLydE52IKuHc,1590
12
+ charset_normalizer/__main__.py,sha256=yzYxMR-IhKRHYwcSlavEv8oGdwxsR89mr2X09qXGdps,109
13
+ charset_normalizer/api.py,sha256=kXhFlZNMi6_p0YhbTeGTswoK_DZ6oeAdprPxE8F4yfM,42325
14
+ charset_normalizer/cd.cpython-311-x86_64-linux-gnu.so,sha256=AgR449IbdARrS3y2V8xOUmX_bYkKmVsoJRAGPmMJuwg,16040
15
+ charset_normalizer/cd.py,sha256=6dJOZvd0rrEEWvkx54kAEy9qAP_uIuiWMAi5wX8OZsY,15980
16
+ charset_normalizer/cli/__init__.py,sha256=D8I86lFk2-py45JvqxniTirSj_sFyE6sjaY_0-G1shc,136
17
+ charset_normalizer/cli/__main__.py,sha256=NPK3yYAkXXE7Uvs6IqijkgZzS6G6fguRFuKXzgpf8Uc,11949
18
+ charset_normalizer/constant.py,sha256=vp9HvaompccS71BXPZk8lVahonkPbBpeVE3NzKZe2sk,44624
19
+ charset_normalizer/legacy.py,sha256=bgkdEvubTCOPlMKOzuENXHMiarh36VaGbRvWSlIr1KA,2651
20
+ charset_normalizer/md.cpython-311-x86_64-linux-gnu.so,sha256=vXEPVSHEXBrFgbT6a_6DmmBAYZhSFnewl_sVGLNGyaA,16040
21
+ charset_normalizer/md.py,sha256=bwD18o2xLkGxBkuM1HPnYULsLBzNVe09j727Tng2tJw,32641
22
+ charset_normalizer/models.py,sha256=BAYguAENiSKBb7mf3DKzY3qgqjrjBeP0dySCmQSieXE,12830
23
+ charset_normalizer/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
24
+ charset_normalizer/utils.py,sha256=fMCjgJXzMFegyO-gX-NElZi1rmdF1y1xax2Y-V2eudo,13537
25
+ charset_normalizer/version.py,sha256=FUQoaRCvGW_xwCoesgsGTwzekLTlCkAJr7diNpv-gPI,115
data/diffusion/.venv/lib/python3.11/site-packages/charset_normalizer-3.4.9.dist-info/REQUESTED ADDED
File without changes
data/diffusion/.venv/lib/python3.11/site-packages/charset_normalizer-3.4.9.dist-info/WHEEL ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (83.0.0)
3
+ Root-Is-Purelib: false
4
+ Tag: cp311-cp311-manylinux_2_17_x86_64
5
+ Tag: cp311-cp311-manylinux2014_x86_64
6
+ Tag: cp311-cp311-manylinux_2_28_x86_64
7
+
data/diffusion/.venv/lib/python3.11/site-packages/charset_normalizer-3.4.9.dist-info/entry_points.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ [console_scripts]
2
+ normalizer = charset_normalizer.cli:cli_detect
data/diffusion/.venv/lib/python3.11/site-packages/charset_normalizer-3.4.9.dist-info/top_level.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ ada92cb5d92a588d1b93__mypyc
2
+ charset_normalizer
data/diffusion/.venv/lib/python3.11/site-packages/filelock/__init__.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A platform independent file lock that supports the with-statement.
3
+
4
+ .. autodata:: filelock.__version__
5
+ :no-value:
6
+
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import sys
12
+ import warnings
13
+ from typing import TYPE_CHECKING
14
+
15
+ from ._api import AcquireReturnProxy, BaseFileLock
16
+ from ._error import Timeout
17
+
18
+ if TYPE_CHECKING:
19
+ from ._async_read_write import (
20
+ AsyncAcquireReadWriteReturnProxy,
21
+ AsyncReadWriteLock,
22
+ )
23
+ from ._read_write import ReadWriteLock
24
+ else:
25
+ try:
26
+ from ._async_read_write import AsyncAcquireReadWriteReturnProxy, AsyncReadWriteLock
27
+ from ._read_write import ReadWriteLock
28
+ except ImportError: # sqlite3 may be unavailable if Python was built without it or the C library is missing
29
+ AsyncAcquireReadWriteReturnProxy = None
30
+ AsyncReadWriteLock = None
31
+ ReadWriteLock = None
32
+
33
+ from ._soft import SoftFileLock
34
+ from ._soft_rw import AsyncAcquireSoftReadWriteReturnProxy, AsyncSoftReadWriteLock, SoftReadWriteLock
35
+ from ._unix import UnixFileLock, has_fcntl
36
+ from ._windows import WindowsFileLock
37
+ from .asyncio import (
38
+ AsyncAcquireReturnProxy,
39
+ AsyncSoftFileLock,
40
+ AsyncUnixFileLock,
41
+ AsyncWindowsFileLock,
42
+ BaseAsyncFileLock,
43
+ )
44
+ from .version import version
45
+
46
+ #: version of the project as a string
47
+ __version__: str = version
48
+
49
+
50
+ if sys.platform == "win32": # pragma: win32 cover
51
+ _FileLock: type[BaseFileLock] = WindowsFileLock
52
+ _AsyncFileLock: type[BaseAsyncFileLock] = AsyncWindowsFileLock
53
+ else: # pragma: win32 no cover # noqa: PLR5501
54
+ if has_fcntl:
55
+ _FileLock: type[BaseFileLock] = UnixFileLock
56
+ _AsyncFileLock: type[BaseAsyncFileLock] = AsyncUnixFileLock
57
+ else:
58
+ _FileLock = SoftFileLock
59
+ _AsyncFileLock = AsyncSoftFileLock
60
+ if warnings is not None:
61
+ warnings.warn("only soft file lock is available", stacklevel=2)
62
+
63
+ if TYPE_CHECKING:
64
+ FileLock = SoftFileLock
65
+ AsyncFileLock = AsyncSoftFileLock
66
+ else:
67
+ #: Alias for the lock, which should be used for the current platform.
68
+ FileLock = _FileLock
69
+ AsyncFileLock = _AsyncFileLock
70
+
71
+
72
+ __all__ = [
73
+ "AcquireReturnProxy",
74
+ "AsyncAcquireReadWriteReturnProxy",
75
+ "AsyncAcquireReturnProxy",
76
+ "AsyncAcquireSoftReadWriteReturnProxy",
77
+ "AsyncFileLock",
78
+ "AsyncReadWriteLock",
79
+ "AsyncSoftFileLock",
80
+ "AsyncSoftReadWriteLock",
81
+ "AsyncUnixFileLock",
82
+ "AsyncWindowsFileLock",
83
+ "BaseAsyncFileLock",
84
+ "BaseFileLock",
85
+ "FileLock",
86
+ "ReadWriteLock",
87
+ "SoftFileLock",
88
+ "SoftReadWriteLock",
89
+ "Timeout",
90
+ "UnixFileLock",
91
+ "WindowsFileLock",
92
+ "__version__",
93
+ ]
data/diffusion/.venv/lib/python3.11/site-packages/filelock/_api.py ADDED
@@ -0,0 +1,645 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import contextlib
4
+ import inspect
5
+ import logging
6
+ import os
7
+ import sys
8
+ import time
9
+ import warnings
10
+ from abc import ABCMeta, abstractmethod
11
+ from dataclasses import dataclass
12
+ from threading import Lock, local
13
+ from typing import TYPE_CHECKING, Any, TypeVar
14
+ from weakref import WeakValueDictionary
15
+
16
+ from ._error import Timeout
17
+ from ._util import break_lock_file
18
+
19
+ #: Sentinel indicating that no explicit file permission mode was passed.
20
+ #: When used, lock files are created with 0o666 (letting umask and default ACLs control the final permissions)
21
+ #: and fchmod is skipped so that POSIX default ACL inheritance is preserved.
22
+ _UNSET_FILE_MODE: int = -1
23
+
24
+ if TYPE_CHECKING:
25
+ from collections.abc import Callable
26
+ from types import TracebackType
27
+
28
+ from ._read_write import ReadWriteLock
29
+ from ._soft_rw import SoftReadWriteLock
30
+
31
+ if sys.version_info >= (3, 11): # pragma: no cover (py311+)
32
+ from typing import Self
33
+ else: # pragma: no cover (<py311)
34
+ from typing_extensions import Self
35
+
36
+
37
+ _LOGGER = logging.getLogger("filelock")
38
+
39
+ # On Windows os.path.realpath calls CreateFileW with share_mode=0, which blocks concurrent DeleteFileW and causes
40
+ # livelocks under threaded contention with SoftFileLock. os.path.abspath is purely string-based and avoids this.
41
+ _canonical = os.path.abspath if sys.platform == "win32" else os.path.realpath
42
+
43
+
44
+ class _ThreadLocalRegistry(local):
45
+ def __init__(self) -> None:
46
+ super().__init__()
47
+ self.held: dict[str, int] = {}
48
+
49
+
50
+ _registry = _ThreadLocalRegistry()
51
+
52
+
53
+ # This is a helper class which is returned by :meth:`BaseFileLock.acquire` and wraps the lock to make sure __enter__
54
+ # is not called twice when entering the with statement. If we would simply return *self*, the lock would be acquired
55
+ # again in the *__enter__* method of the BaseFileLock, but not released again automatically. issue #37 (memory leak)
56
+ class AcquireReturnProxy:
57
+ """A context-aware object that will release the lock file when exiting."""
58
+
59
+ def __init__(self, lock: BaseFileLock | ReadWriteLock | SoftReadWriteLock) -> None:
60
+ self.lock: BaseFileLock | ReadWriteLock | SoftReadWriteLock = lock
61
+
62
+ def __enter__(self) -> BaseFileLock | ReadWriteLock | SoftReadWriteLock:
63
+ return self.lock
64
+
65
+ def __exit__(
66
+ self,
67
+ exc_type: type[BaseException] | None,
68
+ exc_value: BaseException | None,
69
+ traceback: TracebackType | None,
70
+ ) -> None:
71
+ self.lock.release()
72
+
73
+
74
+ @dataclass
75
+ class FileLockContext:
76
+ """A dataclass which holds the context for a ``BaseFileLock`` object."""
77
+
78
+ # The context is held in a separate class to allow optional use of thread local storage via the
79
+ # ThreadLocalFileContext class.
80
+
81
+ #: The path to the lock file.
82
+ lock_file: str
83
+
84
+ #: The default timeout value.
85
+ timeout: float
86
+
87
+ #: The mode for the lock files
88
+ mode: int
89
+
90
+ #: Whether the lock should be blocking or not
91
+ blocking: bool
92
+
93
+ #: The default polling interval value.
94
+ poll_interval: float
95
+
96
+ #: The lock lifetime in seconds; ``None`` means the lock never expires.
97
+ lifetime: float | None = None
98
+
99
+ #: The file descriptor for the *_lock_file* as it is returned by the os.open() function, not None when lock held
100
+ lock_file_fd: int | None = None
101
+
102
+ #: The lock counter is used for implementing the nested locking mechanism.
103
+ lock_counter: int = 0 # When the lock is acquired is increased and the lock is only released, when this value is 0
104
+
105
+
106
+ class ThreadLocalFileContext(FileLockContext, local):
107
+ """A thread local version of the ``FileLockContext`` class."""
108
+
109
+
110
+ _T = TypeVar("_T", bound="BaseFileLock")
111
+
112
+
113
+ class FileLockMeta(ABCMeta):
114
+ _instances: WeakValueDictionary[str, BaseFileLock]
115
+ _instances_lock: Lock
116
+
117
+ def __call__( # noqa: PLR0913
118
+ cls: type[_T],
119
+ lock_file: str | os.PathLike[str],
120
+ timeout: float = -1,
121
+ mode: int = _UNSET_FILE_MODE,
122
+ thread_local: bool = True, # noqa: FBT001, FBT002
123
+ *,
124
+ blocking: bool = True,
125
+ is_singleton: bool = False,
126
+ poll_interval: float = 0.05,
127
+ lifetime: float | None = None,
128
+ **kwargs: Any, # capture remaining kwargs for subclasses # noqa: ANN401
129
+ ) -> _T:
130
+ params = {
131
+ "timeout": timeout,
132
+ "mode": mode,
133
+ "thread_local": thread_local,
134
+ "blocking": blocking,
135
+ "is_singleton": is_singleton,
136
+ "poll_interval": poll_interval,
137
+ "lifetime": lifetime,
138
+ **kwargs,
139
+ }
140
+ if not is_singleton:
141
+ return cls._create_instance(lock_file, params)
142
+
143
+ # Look up, build and store under one lock. Without it two threads racing the first construction for a
144
+ # path both miss the cache and each build their own instance, so callers relying on is_singleton for
145
+ # reentrant locking across instances end up with two "singletons" and acquire()'s deadlock check then
146
+ # rejects a legitimate reentrant acquire; the unguarded writes to the WeakValueDictionary are a data
147
+ # race besides. ReadWriteLock and SoftReadWriteLock already guard their singleton caches this way.
148
+ with cls._instances_lock:
149
+ if (instance := cls._instances.get(str(lock_file))) is None:
150
+ instance = cls._create_instance(lock_file, params)
151
+ cls._instances[str(lock_file)] = instance
152
+ return instance
153
+
154
+ params_to_check = {
155
+ "thread_local": (thread_local, instance.is_thread_local()),
156
+ "timeout": (timeout, instance.timeout),
157
+ "mode": (mode, instance._context.mode), # noqa: SLF001
158
+ "blocking": (blocking, instance.blocking),
159
+ "poll_interval": (poll_interval, instance.poll_interval),
160
+ "lifetime": (lifetime, instance.lifetime),
161
+ }
162
+
163
+ non_matching_params = {
164
+ name: (passed_param, set_param)
165
+ for name, (passed_param, set_param) in params_to_check.items()
166
+ if passed_param != set_param
167
+ }
168
+ if not non_matching_params:
169
+ return instance # ty: ignore[invalid-return-type] # https://github.com/astral-sh/ty/issues/3231
170
+
171
+ # parameters do not match; raise error
172
+ msg = "Singleton lock instances cannot be initialized with differing arguments"
173
+ msg += "\nNon-matching arguments: "
174
+ for param_name, (passed_param, set_param) in non_matching_params.items():
175
+ msg += f"\n\t{param_name} (existing lock has {set_param} but {passed_param} was passed)"
176
+ raise ValueError(msg)
177
+
178
+ def _create_instance(cls: type[_T], lock_file: str | os.PathLike[str], params: dict[str, Any]) -> _T:
179
+ # Keep only the params this subclass's __init__ accepts: virtualenv narrows the signature of its
180
+ # BaseFileLock descendant, so passing the full set would break it (https://github.com/tox-dev/filelock/pull/340).
181
+ present_params = inspect.signature(cls.__init__).parameters
182
+ init_params = {key: value for key, value in params.items() if key in present_params}
183
+ return super().__call__(lock_file, **init_params)
184
+
185
+
186
+ class BaseFileLock(contextlib.ContextDecorator, metaclass=FileLockMeta):
187
+ """
188
+ Abstract base class for a file lock object.
189
+
190
+ Provides a reentrant, cross-process exclusive lock backed by OS-level primitives. Subclasses implement the actual
191
+ locking mechanism (:class:`UnixFileLock <filelock.UnixFileLock>`, :class:`WindowsFileLock
192
+ <filelock.WindowsFileLock>`, :class:`SoftFileLock <filelock.SoftFileLock>`).
193
+
194
+ """
195
+
196
+ _instances: WeakValueDictionary[str, BaseFileLock]
197
+ _instances_lock: Lock
198
+
199
+ #: How the cross-instance deadlock message names the conflicting holder; the async subclass says "task".
200
+ _deadlock_holder_desc: str = "FileLock instance in this thread"
201
+
202
+ def __init_subclass__(cls, **kwargs: dict[str, Any]) -> None:
203
+ """Setup unique state for lock subclasses."""
204
+ super().__init_subclass__(**kwargs)
205
+ cls._instances = WeakValueDictionary()
206
+ cls._instances_lock = Lock()
207
+
208
+ def __init__( # noqa: PLR0913
209
+ self,
210
+ lock_file: str | os.PathLike[str],
211
+ timeout: float = -1,
212
+ mode: int = _UNSET_FILE_MODE,
213
+ thread_local: bool = True, # noqa: FBT001, FBT002
214
+ *,
215
+ blocking: bool = True,
216
+ is_singleton: bool = False,
217
+ poll_interval: float = 0.05,
218
+ lifetime: float | None = None,
219
+ ) -> None:
220
+ """
221
+ Create a new lock object.
222
+
223
+ :param lock_file: path to the file
224
+ :param timeout: default timeout when acquiring the lock, in seconds. It will be used as fallback value in the
225
+ acquire method, if no timeout value (``None``) is given. If you want to disable the timeout, set it to a
226
+ negative value. A timeout of 0 means that there is exactly one attempt to acquire the file lock.
227
+ :param mode: file permissions for the lockfile. When not specified, the OS controls permissions via umask and
228
+ default ACLs, preserving POSIX default ACL inheritance in shared directories.
229
+ :param thread_local: Whether this object's internal context should be thread local or not. If this is set to
230
+ ``False`` then the lock will be reentrant across threads. When ``True`` (the default), **all fields of the
231
+ lock's internal context are per-thread**, including the configuration values ``poll_interval``, ``timeout``,
232
+ ``blocking``, ``mode``, and ``lifetime``. Setting one of these properties from one thread does not change
233
+ the value seen by another thread; threads that did not perform the write continue to see the value supplied
234
+ at construction time. If you need configuration values to be visible across threads, construct the lock
235
+ with ``thread_local=False``.
236
+ :param blocking: whether the lock should be blocking or not
237
+ :param is_singleton: If this is set to ``True`` then only one instance of this class will be created per lock
238
+ file. This is useful if you want to use the lock object for reentrant locking without needing to pass the
239
+ same object around.
240
+ :param poll_interval: default interval for polling the lock file, in seconds. It will be used as fallback value
241
+ in the acquire method, if no poll_interval value (``None``) is given.
242
+ :param lifetime: maximum time in seconds a lock can be held before it is considered expired. When set, a waiting
243
+ process will break a lock whose file modification time is older than ``lifetime`` seconds. ``None`` (the
244
+ default) means locks never expire.
245
+
246
+ """
247
+ self._is_thread_local = thread_local
248
+ self._is_singleton = is_singleton
249
+
250
+ # Create the context. Note that external code should not work with the context directly and should instead use
251
+ # properties of this class.
252
+ kwargs: dict[str, Any] = {
253
+ "lock_file": os.fspath(lock_file),
254
+ "timeout": timeout,
255
+ "mode": mode,
256
+ "blocking": blocking,
257
+ "poll_interval": poll_interval,
258
+ "lifetime": lifetime,
259
+ }
260
+ self._context: FileLockContext = (ThreadLocalFileContext if thread_local else FileLockContext)(**kwargs)
261
+
262
+ def is_thread_local(self) -> bool:
263
+ """:returns: a flag indicating if this lock is thread local or not"""
264
+ return self._is_thread_local
265
+
266
+ @property
267
+ def is_singleton(self) -> bool:
268
+ """
269
+ A flag indicating if this lock is singleton or not.
270
+
271
+ .. versionadded:: 3.13.0
272
+
273
+ """
274
+ return self._is_singleton
275
+
276
+ @property
277
+ def lock_file(self) -> str:
278
+ """Path to the lock file."""
279
+ return self._context.lock_file
280
+
281
+ @property
282
+ def timeout(self) -> float:
283
+ """
284
+ The default timeout value, in seconds.
285
+
286
+ .. versionadded:: 2.0.0
287
+
288
+ """
289
+ return self._context.timeout
290
+
291
+ @timeout.setter
292
+ def timeout(self, value: float | str) -> None:
293
+ """
294
+ Change the default timeout value.
295
+
296
+ :param value: the new value, in seconds
297
+
298
+ """
299
+ self._context.timeout = float(value)
300
+
301
+ @property
302
+ def blocking(self) -> bool:
303
+ """
304
+ Whether the locking is blocking or not.
305
+
306
+ .. versionadded:: 3.14.0
307
+
308
+ """
309
+ return self._context.blocking
310
+
311
+ @blocking.setter
312
+ def blocking(self, value: bool) -> None:
313
+ """
314
+ Change the default blocking value.
315
+
316
+ :param value: the new value as bool
317
+
318
+ """
319
+ self._context.blocking = value
320
+
321
+ @property
322
+ def poll_interval(self) -> float:
323
+ """
324
+ The default polling interval, in seconds.
325
+
326
+ .. versionadded:: 3.24.0
327
+
328
+ """
329
+ return self._context.poll_interval
330
+
331
+ @poll_interval.setter
332
+ def poll_interval(self, value: float) -> None:
333
+ """
334
+ Change the default polling interval.
335
+
336
+ :param value: the new value, in seconds
337
+
338
+ """
339
+ self._context.poll_interval = value
340
+
341
+ @property
342
+ def lifetime(self) -> float | None:
343
+ """
344
+ The lock lifetime in seconds, or ``None`` if the lock never expires.
345
+
346
+ .. versionadded:: 3.24.0
347
+
348
+ """
349
+ return self._context.lifetime
350
+
351
+ @lifetime.setter
352
+ def lifetime(self, value: float | None) -> None:
353
+ """
354
+ Change the lock lifetime.
355
+
356
+ :param value: the new value in seconds, or ``None`` to disable expiration
357
+
358
+ :raises ValueError: if *value* is a negative number
359
+ :raises TypeError: if *value* is not ``None`` and not a real number
360
+
361
+ """
362
+ if value is not None:
363
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
364
+ msg = f"lifetime must be a non-negative number or None, not {type(value).__name__}"
365
+ raise TypeError(msg)
366
+ if value < 0:
367
+ msg = f"lifetime must be non-negative, not {value!r}"
368
+ raise ValueError(msg)
369
+ self._context.lifetime = value
370
+
371
+ @property
372
+ def mode(self) -> int:
373
+ """The file permissions for the lockfile."""
374
+ return 0o644 if self._context.mode == _UNSET_FILE_MODE else self._context.mode
375
+
376
+ @property
377
+ def has_explicit_mode(self) -> bool:
378
+ """Whether the file permissions were explicitly set."""
379
+ return self._context.mode != _UNSET_FILE_MODE
380
+
381
+ def _open_mode(self) -> int:
382
+ """:returns: the mode for os.open() — 0o666 when unset (let umask/ACLs decide), else the explicit mode"""
383
+ return 0o666 if self._context.mode == _UNSET_FILE_MODE else self._context.mode
384
+
385
+ def _try_break_expired_lock(self) -> None:
386
+ """Remove the lock file if its modification time exceeds the configured :attr:`lifetime`."""
387
+ if (lifetime := self._context.lifetime) is None:
388
+ return
389
+ with contextlib.suppress(OSError):
390
+ # lstat, not stat: an attacker with write access to the lock directory can replace a held
391
+ # lock file with a symlink pointing at an old file, making stat() report the target's stale
392
+ # mtime so a waiter breaks a live lock and two processes hold it at once. lstat reads the
393
+ # symlink's own mtime, matching the O_NOFOLLOW reads elsewhere.
394
+ st = os.lstat(self.lock_file)
395
+ if time.time() - st.st_mtime < lifetime:
396
+ return
397
+ break_lock_file(self.lock_file, st.st_mtime, st.st_ino)
398
+
399
+ @abstractmethod
400
+ def _acquire(self) -> None:
401
+ """If the file lock could be acquired, self._context.lock_file_fd holds the file descriptor of the lock file."""
402
+ raise NotImplementedError
403
+
404
+ @abstractmethod
405
+ def _release(self) -> None:
406
+ """Releases the lock and sets self._context.lock_file_fd to None."""
407
+ raise NotImplementedError
408
+
409
+ @property
410
+ def is_locked(self) -> bool:
411
+ """
412
+ A boolean indicating if the lock file is holding the lock currently.
413
+
414
+ .. versionchanged:: 2.0.0
415
+
416
+ This was previously a method and is now a property.
417
+
418
+ """
419
+ return self._context.lock_file_fd is not None
420
+
421
+ @property
422
+ def lock_counter(self) -> int:
423
+ """The number of times this lock has been acquired (but not yet released)."""
424
+ return self._context.lock_counter
425
+
426
+ @staticmethod
427
+ def _check_give_up( # noqa: PLR0913
428
+ lock_id: int,
429
+ lock_filename: str,
430
+ *,
431
+ blocking: bool,
432
+ cancel_check: Callable[[], bool] | None,
433
+ timeout: float,
434
+ start_time: float,
435
+ ) -> bool:
436
+ if blocking is False:
437
+ _LOGGER.debug("Failed to immediately acquire lock %s on %s", lock_id, lock_filename)
438
+ return True
439
+ if cancel_check is not None and cancel_check():
440
+ _LOGGER.debug("Cancellation requested for lock %s on %s", lock_id, lock_filename)
441
+ return True
442
+ if 0 <= timeout < time.perf_counter() - start_time:
443
+ _LOGGER.debug("Timeout on acquiring lock %s on %s", lock_id, lock_filename)
444
+ return True
445
+ return False
446
+
447
+ def acquire(
448
+ self,
449
+ timeout: float | None = None,
450
+ poll_interval: float | None = None,
451
+ *,
452
+ poll_intervall: float | None = None,
453
+ blocking: bool | None = None,
454
+ cancel_check: Callable[[], bool] | None = None,
455
+ ) -> AcquireReturnProxy:
456
+ """
457
+ Try to acquire the file lock.
458
+
459
+ :param timeout: maximum wait time for acquiring the lock, ``None`` means use the default :attr:`~timeout` is and
460
+ if ``timeout < 0``, there is no timeout and this method will block until the lock could be acquired
461
+ :param poll_interval: interval of trying to acquire the lock file, ``None`` means use the default
462
+ :attr:`~poll_interval`
463
+ :param poll_intervall: deprecated, kept for backwards compatibility, use ``poll_interval`` instead
464
+ :param blocking: defaults to True. If False, function will return immediately if it cannot obtain a lock on the
465
+ first attempt. Otherwise, this method will block until the timeout expires or the lock is acquired.
466
+ :param cancel_check: a callable returning ``True`` when the acquisition should be canceled. Checked on each poll
467
+ iteration. When triggered, raises :class:`~Timeout` just like an expired timeout.
468
+
469
+ :returns: a context object that will unlock the file when the context is exited
470
+
471
+ :raises Timeout: if fails to acquire lock within the timeout period
472
+
473
+ .. code-block:: python
474
+
475
+ # You can use this method in the context manager (recommended)
476
+ with lock.acquire():
477
+ pass
478
+
479
+ # Or use an equivalent try-finally construct:
480
+ lock.acquire()
481
+ try:
482
+ pass
483
+ finally:
484
+ lock.release()
485
+
486
+ .. versionchanged:: 2.0.0
487
+
488
+ This method returns now a *proxy* object instead of *self*, so that it can be used in a with statement
489
+ without side effects.
490
+
491
+ """
492
+ # Use the default timeout, if no timeout is provided.
493
+ if timeout is None:
494
+ timeout = self._context.timeout
495
+
496
+ if blocking is None:
497
+ blocking = self._context.blocking
498
+
499
+ if poll_intervall is not None:
500
+ msg = "use poll_interval instead of poll_intervall"
501
+ warnings.warn(msg, DeprecationWarning, stacklevel=2)
502
+ poll_interval = poll_intervall
503
+
504
+ poll_interval = poll_interval if poll_interval is not None else self._context.poll_interval
505
+
506
+ # Increment the number right at the beginning. We can still undo it, if something fails.
507
+ self._context.lock_counter += 1
508
+
509
+ canonical = _canonical(self.lock_file)
510
+ self._raise_if_would_deadlock(canonical, timeout=timeout, blocking=blocking)
511
+
512
+ start_time = time.perf_counter()
513
+ try:
514
+ self._poll_until_acquired(
515
+ blocking=blocking,
516
+ cancel_check=cancel_check,
517
+ timeout=timeout,
518
+ poll_interval=poll_interval,
519
+ start_time=start_time,
520
+ )
521
+ except BaseException:
522
+ self._undo_acquire(canonical)
523
+ raise
524
+ self._commit_acquire(canonical)
525
+ return AcquireReturnProxy(lock=self)
526
+
527
+ def _raise_if_would_deadlock(self, canonical: str, *, timeout: float, blocking: bool) -> None:
528
+ """
529
+ Fail fast when a *different* live instance already holds this path on the current thread/task.
530
+
531
+ Only the first, indefinitely-blocking acquire can self-deadlock this way: waiting in the OS primitive would
532
+ block on a lock this thread already owns. A finite timeout or ``blocking=False`` keeps the normal Timeout path.
533
+ """
534
+ would_block = self._context.lock_counter == 1 and not self.is_locked and timeout < 0 and blocking
535
+ if would_block and _registry.held.get(canonical) not in {None, id(self)}:
536
+ self._context.lock_counter -= 1
537
+ msg = (
538
+ f"Deadlock: lock '{self.lock_file}' is already held by a different {self._deadlock_holder_desc}. "
539
+ f"Use is_singleton=True to enable reentrant locking across instances."
540
+ )
541
+ raise RuntimeError(msg)
542
+
543
+ def _undo_acquire(self, canonical: str) -> None:
544
+ """Roll back the counter after a failed acquire, dropping the registry entry once nothing holds the path."""
545
+ self._context.lock_counter = max(0, self._context.lock_counter - 1)
546
+ if self._context.lock_counter == 0:
547
+ _registry.held.pop(canonical, None)
548
+
549
+ def _commit_acquire(self, canonical: str) -> None:
550
+ """Record this instance as the holder once the first acquire succeeds, so peers can detect the deadlock."""
551
+ if self._context.lock_counter == 1:
552
+ _registry.held[canonical] = id(self)
553
+
554
+ def _drop_registry_entry(self) -> None:
555
+ """Forget this path's holder on release so a later cross-instance acquire is not misread as a deadlock."""
556
+ _registry.held.pop(_canonical(self.lock_file), None)
557
+
558
+ def _poll_until_acquired(
559
+ self,
560
+ *,
561
+ blocking: bool,
562
+ cancel_check: Callable[[], bool] | None,
563
+ timeout: float,
564
+ poll_interval: float,
565
+ start_time: float,
566
+ ) -> None:
567
+ lock_id = id(self)
568
+ lock_filename = self.lock_file
569
+ while True:
570
+ if not self.is_locked:
571
+ self._try_break_expired_lock()
572
+ _LOGGER.debug("Attempting to acquire lock %s on %s", lock_id, lock_filename)
573
+ self._acquire()
574
+ if self.is_locked:
575
+ _LOGGER.debug("Lock %s acquired on %s", lock_id, lock_filename)
576
+ return
577
+ if self._check_give_up(
578
+ lock_id,
579
+ lock_filename,
580
+ blocking=blocking,
581
+ cancel_check=cancel_check,
582
+ timeout=timeout,
583
+ start_time=start_time,
584
+ ):
585
+ raise Timeout(lock_filename)
586
+ msg = "Lock %s not acquired on %s, waiting %s seconds ..."
587
+ _LOGGER.debug(msg, lock_id, lock_filename, poll_interval)
588
+ time.sleep(poll_interval)
589
+
590
+ def release(self, force: bool = False) -> None: # noqa: FBT001, FBT002
591
+ """
592
+ Release the file lock. The lock is only completely released when the lock counter reaches 0. The lock file
593
+ itself may be deleted automatically, the behavior is platform-specific.
594
+
595
+ :param force: If true, the lock counter is ignored and the lock is released in every case.
596
+
597
+ """
598
+ if self.is_locked:
599
+ self._context.lock_counter -= 1
600
+
601
+ if self._context.lock_counter == 0 or force:
602
+ lock_id, lock_filename = id(self), self.lock_file
603
+
604
+ _LOGGER.debug("Attempting to release lock %s on %s", lock_id, lock_filename)
605
+ self._release()
606
+ self._context.lock_counter = 0
607
+ self._drop_registry_entry()
608
+ _LOGGER.debug("Lock %s released on %s", lock_id, lock_filename)
609
+
610
+ def __enter__(self) -> Self:
611
+ """
612
+ Acquire the lock.
613
+
614
+ :returns: the lock object
615
+
616
+ """
617
+ self.acquire()
618
+ return self
619
+
620
+ def __exit__(
621
+ self,
622
+ exc_type: type[BaseException] | None,
623
+ exc_value: BaseException | None,
624
+ traceback: TracebackType | None,
625
+ ) -> None:
626
+ """
627
+ Release the lock.
628
+
629
+ :param exc_type: the exception type if raised
630
+ :param exc_value: the exception value if raised
631
+ :param traceback: the exception traceback if raised
632
+
633
+ """
634
+ self.release()
635
+
636
+ def __del__(self) -> None:
637
+ """Called when the lock object is deleted."""
638
+ self.release(force=True)
639
+
640
+
641
+ __all__ = [
642
+ "_UNSET_FILE_MODE",
643
+ "AcquireReturnProxy",
644
+ "BaseFileLock",
645
+ ]
data/diffusion/.venv/lib/python3.11/site-packages/filelock/_async_read_write.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Async wrapper around :class:`ReadWriteLock` for use with ``asyncio``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import functools
7
+ from concurrent.futures import ThreadPoolExecutor
8
+ from contextlib import asynccontextmanager
9
+ from typing import TYPE_CHECKING
10
+
11
+ from ._read_write import ReadWriteLock
12
+
13
+ if TYPE_CHECKING:
14
+ import os
15
+ from collections.abc import AsyncGenerator, Callable
16
+ from concurrent import futures
17
+ from types import TracebackType
18
+
19
+
20
+ class AsyncAcquireReadWriteReturnProxy:
21
+ """Context-aware object that releases the async read/write lock on exit."""
22
+
23
+ def __init__(self, lock: AsyncReadWriteLock) -> None:
24
+ self.lock = lock
25
+
26
+ async def __aenter__(self) -> AsyncReadWriteLock:
27
+ return self.lock
28
+
29
+ async def __aexit__(
30
+ self,
31
+ exc_type: type[BaseException] | None,
32
+ exc_value: BaseException | None,
33
+ traceback: TracebackType | None,
34
+ ) -> None:
35
+ await self.lock.release()
36
+
37
+
38
+ class AsyncReadWriteLock:
39
+ """
40
+ Async wrapper around :class:`ReadWriteLock` for use in ``asyncio`` applications.
41
+
42
+ Because Python's :mod:`sqlite3` module has no async API, all blocking SQLite operations are dispatched to a thread
43
+ pool via ``loop.run_in_executor()``. Reentrancy, upgrade/downgrade rules, and singleton behavior are delegated
44
+ to the underlying :class:`ReadWriteLock`.
45
+
46
+ :param lock_file: path to the SQLite database file used as the lock
47
+ :param timeout: maximum wait time in seconds; ``-1`` means block indefinitely
48
+ :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately when the lock is unavailable
49
+ :param is_singleton: if ``True``, reuse existing :class:`ReadWriteLock` instances for the same resolved path
50
+ :param loop: event loop for ``run_in_executor``; ``None`` uses the running loop
51
+ :param executor: executor for ``run_in_executor``. When ``None`` a dedicated single-thread executor is created
52
+ and owned by this lock, ensuring every operation runs on the same thread (required for SQLite affinity); it
53
+ is shut down by :meth:`close`. A caller-supplied executor is used as-is and never shut down here, so when no
54
+ executor is passed remember to call :meth:`close` to release the owned one.
55
+
56
+ .. versionadded:: 3.21.0
57
+
58
+ """
59
+
60
+ def __init__( # noqa: PLR0913
61
+ self,
62
+ lock_file: str | os.PathLike[str],
63
+ timeout: float = -1,
64
+ *,
65
+ blocking: bool = True,
66
+ is_singleton: bool = True,
67
+ loop: asyncio.AbstractEventLoop | None = None,
68
+ executor: futures.Executor | None = None,
69
+ ) -> None:
70
+ self._lock = ReadWriteLock(lock_file, timeout, blocking=blocking, is_singleton=is_singleton)
71
+ self._loop = loop
72
+ self._owns_executor = executor is None
73
+ self._executor = executor or ThreadPoolExecutor(max_workers=1)
74
+
75
+ @property
76
+ def lock_file(self) -> str:
77
+ """The path to the lock file."""
78
+ return self._lock.lock_file
79
+
80
+ @property
81
+ def timeout(self) -> float:
82
+ """The default timeout."""
83
+ return self._lock.timeout
84
+
85
+ @property
86
+ def blocking(self) -> bool:
87
+ """Whether blocking is enabled by default."""
88
+ return self._lock.blocking
89
+
90
+ @property
91
+ def loop(self) -> asyncio.AbstractEventLoop | None:
92
+ """The event loop (or ``None`` for the running loop)."""
93
+ return self._loop
94
+
95
+ @property
96
+ def executor(self) -> futures.Executor:
97
+ """The executor used for ``run_in_executor`` (a dedicated single-thread one if none was supplied)."""
98
+ return self._executor
99
+
100
+ async def _run(self, func: Callable[..., object], *args: object, **kwargs: object) -> object:
101
+ loop = self._loop or asyncio.get_running_loop()
102
+ return await loop.run_in_executor(self._executor, functools.partial(func, *args, **kwargs))
103
+
104
+ async def acquire_read(self, timeout: float = -1, *, blocking: bool = True) -> AsyncAcquireReadWriteReturnProxy:
105
+ """
106
+ Acquire a shared read lock.
107
+
108
+ See :meth:`ReadWriteLock.acquire_read` for full semantics.
109
+
110
+ :param timeout: maximum wait time in seconds; ``-1`` means block indefinitely
111
+ :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately when the lock is unavailable
112
+
113
+ :returns: a proxy that can be used as an async context manager to release the lock
114
+
115
+ :raises RuntimeError: if a write lock is already held on this instance
116
+ :raises Timeout: if the lock cannot be acquired within *timeout* seconds
117
+
118
+ """
119
+ await self._run(self._lock.acquire_read, timeout, blocking=blocking)
120
+ return AsyncAcquireReadWriteReturnProxy(lock=self)
121
+
122
+ async def acquire_write(self, timeout: float = -1, *, blocking: bool = True) -> AsyncAcquireReadWriteReturnProxy:
123
+ """
124
+ Acquire an exclusive write lock.
125
+
126
+ See :meth:`ReadWriteLock.acquire_write` for full semantics.
127
+
128
+ :param timeout: maximum wait time in seconds; ``-1`` means block indefinitely
129
+ :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately when the lock is unavailable
130
+
131
+ :returns: a proxy that can be used as an async context manager to release the lock
132
+
133
+ :raises RuntimeError: if a read lock is already held, or a write lock is held by a different thread
134
+ :raises Timeout: if the lock cannot be acquired within *timeout* seconds
135
+
136
+ """
137
+ await self._run(self._lock.acquire_write, timeout, blocking=blocking)
138
+ return AsyncAcquireReadWriteReturnProxy(lock=self)
139
+
140
+ async def release(self, *, force: bool = False) -> None:
141
+ """
142
+ Release one level of the current lock.
143
+
144
+ See :meth:`ReadWriteLock.release` for full semantics.
145
+
146
+ :param force: if ``True``, release the lock completely regardless of the current lock level
147
+
148
+ :raises RuntimeError: if no lock is currently held and *force* is ``False``
149
+
150
+ """
151
+ await self._run(self._lock.release, force=force)
152
+
153
+ @asynccontextmanager
154
+ async def read_lock(self, timeout: float | None = None, *, blocking: bool | None = None) -> AsyncGenerator[None]:
155
+ """
156
+ Async context manager that acquires and releases a shared read lock.
157
+
158
+ Falls back to instance defaults for *timeout* and *blocking* when ``None``.
159
+
160
+ :param timeout: maximum wait time in seconds, or ``None`` to use the instance default
161
+ :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default
162
+
163
+ """
164
+ if timeout is None:
165
+ timeout = self._lock.timeout
166
+ if blocking is None:
167
+ blocking = self._lock.blocking
168
+ await self.acquire_read(timeout, blocking=blocking)
169
+ try:
170
+ yield
171
+ finally:
172
+ await self.release()
173
+
174
+ @asynccontextmanager
175
+ async def write_lock(self, timeout: float | None = None, *, blocking: bool | None = None) -> AsyncGenerator[None]:
176
+ """
177
+ Async context manager that acquires and releases an exclusive write lock.
178
+
179
+ Falls back to instance defaults for *timeout* and *blocking* when ``None``.
180
+
181
+ :param timeout: maximum wait time in seconds, or ``None`` to use the instance default
182
+ :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default
183
+
184
+ """
185
+ if timeout is None:
186
+ timeout = self._lock.timeout
187
+ if blocking is None:
188
+ blocking = self._lock.blocking
189
+ await self.acquire_write(timeout, blocking=blocking)
190
+ try:
191
+ yield
192
+ finally:
193
+ await self.release()
194
+
195
+ async def close(self) -> None:
196
+ """
197
+ Release the lock (if held) and close the underlying SQLite connection.
198
+
199
+ After calling this method, the lock instance is no longer usable.
200
+
201
+ """
202
+ await self._run(self._lock.close)
203
+ if self._owns_executor:
204
+ self._executor.shutdown(wait=False)
205
+
206
+ def __del__(self) -> None:
207
+ # Safety net: if close() was never called, still shut down the executor we created so its worker thread does
208
+ # not outlive the lock. A caller-supplied executor is left untouched. shutdown(wait=False) never blocks.
209
+ if getattr(self, "_owns_executor", False):
210
+ self._executor.shutdown(wait=False)
211
+
212
+
213
+ __all__ = [
214
+ "AsyncAcquireReadWriteReturnProxy",
215
+ "AsyncReadWriteLock",
216
+ ]
data/diffusion/.venv/lib/python3.11/site-packages/filelock/_error.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+
4
+ class Timeout(TimeoutError): # noqa: N818
5
+ """Raised when the lock could not be acquired in *timeout* seconds."""
6
+
7
+ def __init__(self, lock_file: str) -> None:
8
+ super().__init__()
9
+ self._lock_file = lock_file
10
+
11
+ def __reduce__(self) -> tuple[type[Timeout], tuple[str]]:
12
+ return self.__class__, (self._lock_file,) # Properly pickle the exception
13
+
14
+ def __str__(self) -> str:
15
+ return f"The file lock '{self._lock_file}' could not be acquired."
16
+
17
+ def __repr__(self) -> str:
18
+ return f"{self.__class__.__name__}({self.lock_file!r})"
19
+
20
+ @property
21
+ def lock_file(self) -> str:
22
+ """The path of the file lock."""
23
+ return self._lock_file
24
+
25
+
26
+ __all__ = [
27
+ "Timeout",
28
+ ]
data/diffusion/.venv/lib/python3.11/site-packages/filelock/_read_write.py ADDED
@@ -0,0 +1,385 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import atexit
4
+ import logging
5
+ import os
6
+ import pathlib
7
+ import sqlite3
8
+ import threading
9
+ import time
10
+ from contextlib import contextmanager, suppress
11
+ from typing import TYPE_CHECKING, Literal
12
+ from weakref import WeakValueDictionary
13
+
14
+ from ._api import AcquireReturnProxy
15
+ from ._error import Timeout
16
+
17
+ if TYPE_CHECKING:
18
+ from collections.abc import Generator
19
+
20
+ _LOGGER = logging.getLogger("filelock")
21
+
22
+ _all_connections: set[sqlite3.Connection] = set()
23
+ _all_connections_lock = threading.Lock()
24
+
25
+
26
+ def _cleanup_connections() -> None:
27
+ with _all_connections_lock:
28
+ for con in list(_all_connections):
29
+ with suppress(Exception):
30
+ con.close()
31
+ _all_connections.clear()
32
+
33
+
34
+ atexit.register(_cleanup_connections)
35
+
36
+ # sqlite3_busy_timeout() accepts a C int, max 2_147_483_647 on 32-bit. Use a lower value to be safe (~23 days).
37
+ _MAX_SQLITE_TIMEOUT_MS = 2_000_000_000 - 1
38
+
39
+
40
+ def timeout_for_sqlite(timeout: float, *, blocking: bool, already_waited: float) -> int:
41
+ if blocking is False:
42
+ return 0
43
+
44
+ if timeout == -1:
45
+ return _MAX_SQLITE_TIMEOUT_MS
46
+
47
+ if timeout < 0:
48
+ msg = "timeout must be a non-negative number or -1"
49
+ raise ValueError(msg)
50
+
51
+ remaining = max(timeout - already_waited, 0) if timeout > 0 else timeout
52
+ timeout_ms = int(remaining * 1000)
53
+ if timeout_ms > _MAX_SQLITE_TIMEOUT_MS or timeout_ms < 0:
54
+ _LOGGER.warning("timeout %s is too large for SQLite, using %s ms instead", timeout, _MAX_SQLITE_TIMEOUT_MS)
55
+ return _MAX_SQLITE_TIMEOUT_MS
56
+ return timeout_ms
57
+
58
+
59
+ class _ReadWriteLockMeta(type):
60
+ """
61
+ Metaclass that handles singleton resolution when is_singleton=True.
62
+
63
+ Singleton logic lives here rather than in ReadWriteLock.get_lock so that ``ReadWriteLock(path)`` transparently
64
+ returns cached instances without a 2-arg ``super()`` call that type checkers cannot verify.
65
+
66
+ """
67
+
68
+ _instances: WeakValueDictionary[pathlib.Path, ReadWriteLock]
69
+ _instances_lock: threading.Lock
70
+
71
+ def __call__(
72
+ cls,
73
+ lock_file: str | os.PathLike[str],
74
+ timeout: float = -1,
75
+ *,
76
+ blocking: bool = True,
77
+ is_singleton: bool = True,
78
+ ) -> ReadWriteLock:
79
+ if not is_singleton:
80
+ return super().__call__(lock_file, timeout, blocking=blocking, is_singleton=is_singleton)
81
+
82
+ normalized = pathlib.Path(lock_file).resolve()
83
+ with cls._instances_lock:
84
+ if normalized not in cls._instances:
85
+ instance = super().__call__(lock_file, timeout, blocking=blocking, is_singleton=is_singleton)
86
+ cls._instances[normalized] = instance
87
+ else:
88
+ instance = cls._instances[normalized]
89
+
90
+ if instance.timeout != timeout or instance.blocking != blocking:
91
+ msg = (
92
+ f"Singleton lock created with timeout={instance.timeout}, blocking={instance.blocking},"
93
+ f" cannot be changed to timeout={timeout}, blocking={blocking}"
94
+ )
95
+ raise ValueError(msg)
96
+ return instance
97
+
98
+
99
+ class ReadWriteLock(metaclass=_ReadWriteLockMeta):
100
+ """
101
+ Cross-process read-write lock backed by SQLite.
102
+
103
+ Allows concurrent shared readers or a single exclusive writer. The lock is reentrant within the same mode (multiple
104
+ ``acquire_read`` calls nest, as do multiple ``acquire_write`` calls from the same thread), but upgrading from read
105
+ to write or downgrading from write to read raises :class:`RuntimeError`. Write locks are pinned to the thread that
106
+ acquired them.
107
+
108
+ By default, ``is_singleton=True``: calling ``ReadWriteLock(path)`` with the same resolved path returns the same
109
+ instance. The lock file must use a ``.db`` extension (SQLite database).
110
+
111
+ :param lock_file: path to the SQLite database file used as the lock
112
+ :param timeout: maximum wait time in seconds; ``-1`` means block indefinitely
113
+ :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately when the lock is unavailable
114
+ :param is_singleton: if ``True``, reuse existing instances for the same resolved path
115
+
116
+ .. versionadded:: 3.21.0
117
+
118
+ """
119
+
120
+ _instances: WeakValueDictionary[pathlib.Path, ReadWriteLock] = WeakValueDictionary()
121
+ _instances_lock = threading.Lock()
122
+
123
+ @classmethod
124
+ def get_lock(
125
+ cls, lock_file: str | os.PathLike[str], timeout: float = -1, *, blocking: bool = True
126
+ ) -> ReadWriteLock:
127
+ """
128
+ Return the singleton :class:`ReadWriteLock` for *lock_file*.
129
+
130
+ :param lock_file: path to the SQLite database file used as the lock
131
+ :param timeout: maximum wait time in seconds; ``-1`` means block indefinitely
132
+ :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately when the lock is unavailable
133
+
134
+ :returns: the singleton lock instance
135
+
136
+ :raises ValueError: if an instance already exists for this path with different *timeout* or *blocking* values
137
+
138
+ """
139
+ return cls(lock_file, timeout, blocking=blocking)
140
+
141
+ def __init__(
142
+ self,
143
+ lock_file: str | os.PathLike[str],
144
+ timeout: float = -1,
145
+ *,
146
+ blocking: bool = True,
147
+ is_singleton: bool = True, # noqa: ARG002 # consumed by _ReadWriteLockMeta.__call__
148
+ ) -> None:
149
+ self.lock_file = os.fspath(lock_file)
150
+ self.timeout = timeout
151
+ self.blocking = blocking
152
+ self._transaction_lock = threading.Lock() # serializes the (possibly blocking) SQLite transaction work
153
+ self._internal_lock = threading.Lock() # protects _lock_level / _current_mode updates and rollback
154
+ self._lock_level = 0
155
+ self._current_mode: Literal["read", "write"] | None = None
156
+ self._write_thread_id: int | None = None
157
+ self._con = sqlite3.connect(self.lock_file, check_same_thread=False)
158
+ with _all_connections_lock:
159
+ _all_connections.add(self._con)
160
+
161
+ def _acquire_transaction_lock(self, *, blocking: bool, timeout: float) -> None:
162
+ if not blocking:
163
+ acquired = self._transaction_lock.acquire(blocking=False)
164
+ elif timeout == -1:
165
+ acquired = self._transaction_lock.acquire(blocking=True)
166
+ else:
167
+ acquired = self._transaction_lock.acquire(blocking=True, timeout=timeout)
168
+ if not acquired:
169
+ raise Timeout(self.lock_file) from None
170
+
171
+ def _validate_reentrant(self, mode: Literal["read", "write"]) -> AcquireReturnProxy:
172
+ opposite = "write" if mode == "read" else "read"
173
+ direction = "downgrade" if mode == "read" else "upgrade"
174
+ if self._current_mode != mode:
175
+ msg = (
176
+ f"Cannot acquire {mode} lock on {self.lock_file} (lock id: {id(self)}): "
177
+ f"already holding a {opposite} lock ({direction} not allowed)"
178
+ )
179
+ raise RuntimeError(msg)
180
+ if mode == "write" and (cur := threading.get_ident()) != self._write_thread_id:
181
+ msg = (
182
+ f"Cannot acquire write lock on {self.lock_file} (lock id: {id(self)}) "
183
+ f"from thread {cur} while it is held by thread {self._write_thread_id}"
184
+ )
185
+ raise RuntimeError(msg)
186
+ self._lock_level += 1
187
+ return AcquireReturnProxy(lock=self)
188
+
189
+ def _configure_and_begin(
190
+ self, mode: Literal["read", "write"], timeout: float, *, blocking: bool, start_time: float
191
+ ) -> None:
192
+ waited = time.perf_counter() - start_time
193
+ timeout_ms = timeout_for_sqlite(timeout, blocking=blocking, already_waited=waited)
194
+ self._con.execute(f"PRAGMA busy_timeout={timeout_ms};").close()
195
+ # Use legacy journal mode (not WAL) because WAL does not block readers when a concurrent EXCLUSIVE
196
+ # write transaction is active, making read-write locking impossible without modifying table data.
197
+ # MEMORY is safe here since no actual writes happen — crashes cannot corrupt the DB.
198
+ # See https://sqlite.org/lang_transaction.html#deferred_immediate_and_exclusive_transactions
199
+ #
200
+ # Set here (not in __init__) because this pragma itself may block on a locked database,
201
+ # so it must run after busy_timeout is configured above.
202
+ self._con.execute("PRAGMA journal_mode=MEMORY;").close()
203
+ # Recompute remaining timeout after the potentially blocking journal_mode pragma.
204
+ waited = time.perf_counter() - start_time
205
+ if (recomputed := timeout_for_sqlite(timeout, blocking=blocking, already_waited=waited)) != timeout_ms:
206
+ self._con.execute(f"PRAGMA busy_timeout={recomputed};").close()
207
+ stmt = "BEGIN EXCLUSIVE TRANSACTION;" if mode == "write" else "BEGIN TRANSACTION;"
208
+ self._con.execute(stmt).close()
209
+ if mode == "read":
210
+ # A SELECT is needed to force SQLite to actually acquire the SHARED lock on the database.
211
+ # https://www.sqlite.org/lockingv3.html#transaction_control
212
+ self._con.execute("SELECT name FROM sqlite_schema LIMIT 1;").close()
213
+
214
+ def _acquire(self, mode: Literal["read", "write"], timeout: float, *, blocking: bool) -> AcquireReturnProxy:
215
+ with self._internal_lock:
216
+ if self._lock_level > 0:
217
+ return self._validate_reentrant(mode)
218
+
219
+ start_time = time.perf_counter()
220
+ self._acquire_transaction_lock(blocking=blocking, timeout=timeout)
221
+ try:
222
+ return self._do_acquire_inner(mode, timeout, blocking=blocking, start_time=start_time)
223
+ except sqlite3.Error as exc:
224
+ # A read acquire runs BEGIN (a deferred transaction that takes no database lock) and only then the
225
+ # SELECT that actually takes the SHARED lock. If a writer grabs the EXCLUSIVE lock between the two,
226
+ # the SELECT fails but BEGIN's transaction is left open on the shared connection. Roll it back here,
227
+ # while we still hold _transaction_lock, otherwise the next acquire's BEGIN dies with "cannot start a
228
+ # transaction within a transaction" and the instance is wedged for good. Catch only sqlite3.Error: a
229
+ # reentrant-validation RuntimeError from _do_acquire_inner's double-check must not roll back, or it
230
+ # would drop a transaction another thread legitimately holds on the shared connection.
231
+ with suppress(sqlite3.Error):
232
+ self._con.rollback()
233
+ if isinstance(exc, sqlite3.OperationalError) and "database is locked" in str(exc):
234
+ raise Timeout(self.lock_file) from None
235
+ raise
236
+ finally:
237
+ self._transaction_lock.release()
238
+
239
+ def _do_acquire_inner(
240
+ self,
241
+ mode: Literal["read", "write"],
242
+ timeout: float,
243
+ *,
244
+ blocking: bool,
245
+ start_time: float,
246
+ ) -> AcquireReturnProxy:
247
+ # Double-check: another thread may have acquired the lock while we waited on _transaction_lock.
248
+ with self._internal_lock:
249
+ if self._lock_level > 0:
250
+ return self._validate_reentrant(mode)
251
+ self._configure_and_begin(mode, timeout, blocking=blocking, start_time=start_time)
252
+ with self._internal_lock:
253
+ self._current_mode = mode
254
+ self._lock_level = 1
255
+ if mode == "write":
256
+ self._write_thread_id = threading.get_ident()
257
+ return AcquireReturnProxy(lock=self)
258
+
259
+ def acquire_read(self, timeout: float = -1, *, blocking: bool = True) -> AcquireReturnProxy:
260
+ """
261
+ Acquire a shared read lock.
262
+
263
+ If this instance already holds a read lock, the lock level is incremented (reentrant). Attempting to acquire a
264
+ read lock while holding a write lock raises :class:`RuntimeError` (downgrade not allowed).
265
+
266
+ :param timeout: maximum wait time in seconds; ``-1`` means block indefinitely
267
+ :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately when the lock is unavailable
268
+
269
+ :returns: a proxy that can be used as a context manager to release the lock
270
+
271
+ :raises RuntimeError: if a write lock is already held on this instance
272
+ :raises Timeout: if the lock cannot be acquired within *timeout* seconds
273
+
274
+ """
275
+ return self._acquire("read", timeout, blocking=blocking)
276
+
277
+ def acquire_write(self, timeout: float = -1, *, blocking: bool = True) -> AcquireReturnProxy:
278
+ """
279
+ Acquire an exclusive write lock.
280
+
281
+ If this instance already holds a write lock from the same thread, the lock level is incremented (reentrant).
282
+ Attempting to acquire a write lock while holding a read lock raises :class:`RuntimeError` (upgrade not allowed).
283
+ Write locks are pinned to the acquiring thread: a different thread trying to re-enter also raises
284
+ :class:`RuntimeError`.
285
+
286
+ :param timeout: maximum wait time in seconds; ``-1`` means block indefinitely
287
+ :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately when the lock is unavailable
288
+
289
+ :returns: a proxy that can be used as a context manager to release the lock
290
+
291
+ :raises RuntimeError: if a read lock is already held, or a write lock is held by a different thread
292
+ :raises Timeout: if the lock cannot be acquired within *timeout* seconds
293
+
294
+ """
295
+ return self._acquire("write", timeout, blocking=blocking)
296
+
297
+ def release(self, *, force: bool = False) -> None:
298
+ """
299
+ Release one level of the current lock.
300
+
301
+ When the lock level reaches zero the underlying SQLite transaction is rolled back, releasing the database lock.
302
+
303
+ :param force: if ``True``, release the lock completely regardless of the current lock level
304
+
305
+ :raises RuntimeError: if no lock is currently held and *force* is ``False``
306
+
307
+ """
308
+ should_rollback = False
309
+ with self._internal_lock:
310
+ if self._lock_level == 0:
311
+ if force:
312
+ return
313
+ msg = f"Cannot release a lock on {self.lock_file} (lock id: {id(self)}) that is not held"
314
+ raise RuntimeError(msg)
315
+ if force:
316
+ self._lock_level = 0
317
+ else:
318
+ self._lock_level -= 1
319
+ if self._lock_level == 0:
320
+ self._current_mode = None
321
+ self._write_thread_id = None
322
+ should_rollback = True
323
+ if should_rollback:
324
+ # The rollback ends the transaction on the shared connection, so it has to be serialized against
325
+ # acquire()'s BEGIN the same way acquire() already serializes itself with _transaction_lock. Without
326
+ # this, another thread that sees lock_level back at 0 can start its BEGIN while this rollback's
327
+ # transaction is still open (raising "cannot start a transaction within a transaction") or, in the
328
+ # other ordering, have its freshly started transaction rolled back here, dropping the database lock
329
+ # while it still believes it holds it.
330
+ with self._transaction_lock:
331
+ self._con.rollback()
332
+
333
+ @contextmanager
334
+ def read_lock(self, timeout: float | None = None, *, blocking: bool | None = None) -> Generator[None]:
335
+ """
336
+ Context manager that acquires and releases a shared read lock.
337
+
338
+ Falls back to instance defaults for *timeout* and *blocking* when ``None``.
339
+
340
+ :param timeout: maximum wait time in seconds, or ``None`` to use the instance default
341
+ :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default
342
+
343
+ """
344
+ if timeout is None:
345
+ timeout = self.timeout
346
+ if blocking is None:
347
+ blocking = self.blocking
348
+ self.acquire_read(timeout, blocking=blocking)
349
+ try:
350
+ yield
351
+ finally:
352
+ self.release()
353
+
354
+ @contextmanager
355
+ def write_lock(self, timeout: float | None = None, *, blocking: bool | None = None) -> Generator[None]:
356
+ """
357
+ Context manager that acquires and releases an exclusive write lock.
358
+
359
+ Falls back to instance defaults for *timeout* and *blocking* when ``None``.
360
+
361
+ :param timeout: maximum wait time in seconds, or ``None`` to use the instance default
362
+ :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default
363
+
364
+ """
365
+ if timeout is None:
366
+ timeout = self.timeout
367
+ if blocking is None:
368
+ blocking = self.blocking
369
+ self.acquire_write(timeout, blocking=blocking)
370
+ try:
371
+ yield
372
+ finally:
373
+ self.release()
374
+
375
+ def close(self) -> None:
376
+ """
377
+ Release the lock (if held) and close the underlying SQLite connection.
378
+
379
+ After calling this method, the lock instance is no longer usable.
380
+
381
+ """
382
+ self.release(force=True)
383
+ self._con.close()
384
+ with _all_connections_lock:
385
+ _all_connections.discard(self._con)
data/diffusion/.venv/lib/python3.11/site-packages/filelock/_soft.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import socket
5
+ import sys
6
+ import time
7
+ from contextlib import suppress
8
+ from errno import EACCES, EEXIST, EPERM, ESRCH
9
+ from pathlib import Path
10
+
11
+ from ._api import BaseFileLock
12
+ from ._util import break_lock_file, ensure_directory_exists, raise_on_not_writable_file
13
+
14
+ _WIN_SYNCHRONIZE = 0x100000
15
+ _WIN_ERROR_INVALID_PARAMETER = 87
16
+ _WIN_PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
17
+ _MALFORMED_LOCK_AGE_THRESHOLD = 2.0
18
+ _MAX_LOCK_FILE_SIZE = 1024
19
+
20
+
21
+ class SoftFileLock(BaseFileLock):
22
+ """
23
+ Portable file lock based on file existence.
24
+
25
+ Unlike :class:`UnixFileLock <filelock.UnixFileLock>` and :class:`WindowsFileLock <filelock.WindowsFileLock>`, this
26
+ lock does not use OS-level locking primitives. Instead, it creates the lock file with ``O_CREAT | O_EXCL`` and
27
+ treats its existence as the lock indicator. This makes it work on any filesystem but leaves stale lock files behind
28
+ if the process crashes without releasing the lock.
29
+
30
+ To mitigate stale locks, the lock file contains the PID and hostname of the holding process. On contention, if the
31
+ holder is on the same host and its PID no longer exists, the stale lock is broken automatically.
32
+
33
+ """
34
+
35
+ def _acquire(self) -> None:
36
+ raise_on_not_writable_file(self.lock_file)
37
+ ensure_directory_exists(self.lock_file)
38
+ flags = (
39
+ os.O_WRONLY # open for writing only
40
+ | os.O_CREAT
41
+ | os.O_EXCL # together with above raise EEXIST if the file specified by filename exists
42
+ | os.O_TRUNC # truncate the file to zero byte
43
+ )
44
+ if (o_nofollow := getattr(os, "O_NOFOLLOW", None)) is not None:
45
+ flags |= o_nofollow
46
+ try:
47
+ file_handler = os.open(self.lock_file, flags, self._open_mode())
48
+ except OSError as exception:
49
+ if not (
50
+ exception.errno == EEXIST or (exception.errno == EACCES and sys.platform == "win32")
51
+ ): # pragma: win32 no cover
52
+ raise
53
+ self._try_break_stale_lock()
54
+ else:
55
+ self._write_lock_info(file_handler)
56
+ self._context.lock_file_fd = file_handler
57
+
58
+ def _try_break_stale_lock(self) -> None:
59
+ with suppress(OSError, ValueError):
60
+ content, mtime, ino = _read_lock_file(self.lock_file)
61
+ holder = _parse_lock_holder(content)
62
+
63
+ if holder is None:
64
+ # Unparsable: wrong line count, a non-integer PID or creation time, empty, oversized or not UTF-8.
65
+ # Self-heal only once the file is clearly not a half-written fresh lock (a peer between O_EXCL and
66
+ # _write_lock_info), so the brief create-then-write window is never mistaken for a stale lock.
67
+ if time.time() - mtime >= _MALFORMED_LOCK_AGE_THRESHOLD:
68
+ break_lock_file(self.lock_file, mtime, ino)
69
+ return
70
+
71
+ pid, hostname, creation_time = holder
72
+ if hostname != socket.gethostname():
73
+ return
74
+
75
+ if self._is_process_alive(pid):
76
+ if sys.platform != "win32" or creation_time is None: # pragma: win32 no cover
77
+ return # same process, or no creation time to disambiguate a recycled PID — don't evict
78
+ actual = self._get_process_creation_time(pid) # pragma: win32 cover
79
+ if actual is None or actual == creation_time: # pragma: win32 cover
80
+ return # same process or can't verify — don't evict
81
+ # else: PID alive but creation time differs — the PID was recycled, so the lock is stale.
82
+
83
+ break_lock_file(self.lock_file, mtime, ino)
84
+
85
+ @staticmethod
86
+ def _is_process_alive(pid: int) -> bool:
87
+ if sys.platform == "win32": # pragma: win32 cover
88
+ import ctypes # noqa: PLC0415
89
+
90
+ kernel32 = ctypes.windll.kernel32
91
+ handle = kernel32.OpenProcess(_WIN_SYNCHRONIZE, 0, pid)
92
+ if handle:
93
+ kernel32.CloseHandle(handle)
94
+ return True
95
+ return kernel32.GetLastError() != _WIN_ERROR_INVALID_PARAMETER
96
+ try:
97
+ os.kill(pid, 0)
98
+ except OSError as exc:
99
+ if exc.errno == ESRCH:
100
+ return False
101
+ if exc.errno == EPERM:
102
+ return True
103
+ raise
104
+ return True
105
+
106
+ @staticmethod
107
+ def _get_process_creation_time(pid: int) -> int | None:
108
+ """Return the process creation FILETIME as an integer on Windows, ``None`` otherwise."""
109
+ if sys.platform != "win32": # pragma: win32 no cover
110
+ return None
111
+ import ctypes # pragma: win32 cover # noqa: PLC0415
112
+ from ctypes import wintypes # noqa: PLC0415
113
+
114
+ kernel32 = ctypes.windll.kernel32
115
+ handle = kernel32.OpenProcess(_WIN_PROCESS_QUERY_LIMITED_INFORMATION, 0, pid)
116
+ if not handle:
117
+ return None
118
+ try:
119
+ creation = wintypes.FILETIME()
120
+ exit_time = wintypes.FILETIME()
121
+ kernel_time = wintypes.FILETIME()
122
+ user_time = wintypes.FILETIME()
123
+ if not kernel32.GetProcessTimes(
124
+ handle,
125
+ ctypes.byref(creation),
126
+ ctypes.byref(exit_time),
127
+ ctypes.byref(kernel_time),
128
+ ctypes.byref(user_time),
129
+ ):
130
+ return None
131
+ finally:
132
+ kernel32.CloseHandle(handle)
133
+ return (creation.dwHighDateTime << 32) | creation.dwLowDateTime
134
+
135
+ @staticmethod
136
+ def _write_lock_info(fd: int) -> None:
137
+ with suppress(OSError):
138
+ info = f"{os.getpid()}\n{socket.gethostname()}\n"
139
+ if sys.platform == "win32" and (ct := SoftFileLock._get_process_creation_time(os.getpid())) is not None:
140
+ info += f"{ct}\n"
141
+ os.write(fd, info.encode())
142
+
143
+ @property
144
+ def pid(self) -> int | None:
145
+ """
146
+ The PID of the process holding this lock, read from the lock file.
147
+
148
+ :returns: the PID as an integer, or ``None`` if the lock file does not exist or cannot be parsed
149
+
150
+ """
151
+ with suppress(OSError, ValueError):
152
+ holder = _parse_lock_holder(_read_lock_file(self.lock_file)[0])
153
+ if holder is not None:
154
+ return holder[0]
155
+ return None
156
+
157
+ @property
158
+ def is_lock_held_by_us(self) -> bool:
159
+ """
160
+ Whether this lock is held by the current process.
161
+
162
+ :returns: ``True`` if the lock file exists and names the current process's PID and hostname
163
+
164
+ """
165
+ with suppress(OSError, ValueError):
166
+ holder = _parse_lock_holder(_read_lock_file(self.lock_file)[0])
167
+ if holder is not None:
168
+ pid, hostname, _ = holder
169
+ return pid == os.getpid() and hostname == socket.gethostname()
170
+ return False
171
+
172
+ def break_lock(self) -> None:
173
+ """Forcibly break the lock by removing the lock file, regardless of who holds it."""
174
+ with suppress(OSError):
175
+ Path(self.lock_file).unlink()
176
+
177
+ def _release(self) -> None:
178
+ assert self._context.lock_file_fd is not None # noqa: S101
179
+ os.close(self._context.lock_file_fd)
180
+ self._context.lock_file_fd = None
181
+ if sys.platform == "win32":
182
+ self._windows_unlink_with_retry()
183
+ else:
184
+ with suppress(OSError):
185
+ Path(self.lock_file).unlink()
186
+
187
+ def _windows_unlink_with_retry(self) -> None:
188
+ max_retries = 10
189
+ retry_delay = 0.001
190
+ for attempt in range(max_retries):
191
+ # Windows doesn't immediately release file handles after close, causing EACCES/EPERM on unlink
192
+ try:
193
+ Path(self.lock_file).unlink()
194
+ except OSError as exc: # noqa: PERF203
195
+ if exc.errno not in {EACCES, EPERM}:
196
+ return
197
+ if attempt < max_retries - 1:
198
+ time.sleep(retry_delay)
199
+ retry_delay *= 2
200
+ else:
201
+ return
202
+
203
+
204
+ def _read_lock_file(path: str) -> tuple[str | None, float, int]:
205
+ # The lock file is created with O_EXCL | O_NOFOLLOW, so a symlink here is a hostile replacement and must
206
+ # not be followed. O_NONBLOCK keeps an attacker-placed FIFO from stalling the open (O_NOFOLLOW alone only
207
+ # rejects a symlink, not a real FIFO at the path), and the capped read stops a huge file (e.g. /dev/zero)
208
+ # from exhausting memory. Content is None when the file is too large or not UTF-8, but the mtime and inode
209
+ # still flow back so the caller can evict it as a stale, malformed lock and verify identity before breaking.
210
+ fd = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0))
211
+ try:
212
+ st, data = os.fstat(fd), os.read(fd, _MAX_LOCK_FILE_SIZE + 1)
213
+ finally:
214
+ os.close(fd)
215
+ if len(data) <= _MAX_LOCK_FILE_SIZE:
216
+ with suppress(UnicodeDecodeError):
217
+ return data.decode("utf-8"), st.st_mtime, st.st_ino
218
+ return None, st.st_mtime, st.st_ino
219
+
220
+
221
+ def _parse_lock_holder(content: str | None) -> tuple[int, str, int | None] | None:
222
+ # A well-formed lock file is "<pid>\n<hostname>\n" with an optional "<creation_time>\n" third line on Windows.
223
+ # Anything else — wrong line count, a non-integer PID or creation time, empty or unreadable content — is
224
+ # unparsable; returning None lets the caller treat it as a malformed lock to self-heal rather than a holder.
225
+ if not content or len(lines := content.strip().splitlines()) not in {2, 3}:
226
+ return None
227
+ try:
228
+ pid = int(lines[0])
229
+ creation_time = int(lines[2]) if len(lines) == 3 else None # noqa: PLR2004
230
+ except ValueError:
231
+ return None
232
+ # A pid outside the valid range is a malformed lock, not a holder. Without this, a non-positive pid
233
+ # reaches os.kill() where 0 / -1 mean "the caller's own process group / every process" so a dead
234
+ # holder reads as alive and the lock is never reclaimed, while an oversized pid raises OverflowError
235
+ # (not OSError/ValueError) out of the self-heal path. _parse_marker_bytes already enforces this range.
236
+ if not 1 <= pid <= 2**31 - 1:
237
+ return None
238
+ return pid, lines[1], creation_time
239
+
240
+
241
+ __all__ = [
242
+ "SoftFileLock",
243
+ ]
data/diffusion/.venv/lib/python3.11/site-packages/filelock/_unix.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import sys
5
+ import warnings
6
+ from contextlib import suppress
7
+ from errno import EAGAIN, ENOSYS, EWOULDBLOCK
8
+ from pathlib import Path
9
+ from typing import cast
10
+
11
+ from ._api import BaseFileLock
12
+ from ._util import ensure_directory_exists
13
+
14
+ #: a flag to indicate if the fcntl API is available
15
+ has_fcntl = False
16
+ if sys.platform == "win32": # pragma: win32 cover
17
+
18
+ class UnixFileLock(BaseFileLock):
19
+ """Uses the :func:`fcntl.flock` to hard lock the lock file on unix systems."""
20
+
21
+ def _acquire(self) -> None:
22
+ raise NotImplementedError
23
+
24
+ def _release(self) -> None:
25
+ raise NotImplementedError
26
+
27
+ else: # pragma: win32 no cover
28
+ try:
29
+ import fcntl
30
+
31
+ _ = (fcntl.flock, fcntl.LOCK_EX, fcntl.LOCK_NB, fcntl.LOCK_UN)
32
+ except (ImportError, AttributeError):
33
+ pass
34
+ else:
35
+ has_fcntl = True
36
+
37
+ class UnixFileLock(BaseFileLock):
38
+ """
39
+ Uses the :func:`fcntl.flock` to hard lock the lock file on unix systems.
40
+
41
+ The lock file is intentionally left in place after release. Unlinking a locked file on Unix
42
+ can split waiters across different inodes and break mutual exclusion for processes that
43
+ coordinate via the same path.
44
+ """
45
+
46
+ def _acquire(self) -> None: # noqa: C901, PLR0912
47
+ ensure_directory_exists(self.lock_file)
48
+ open_flags = os.O_RDWR | os.O_TRUNC
49
+ o_nofollow = getattr(os, "O_NOFOLLOW", None)
50
+ if o_nofollow is not None:
51
+ open_flags |= o_nofollow
52
+ open_flags |= os.O_CREAT
53
+ open_mode = self._open_mode()
54
+ try:
55
+ fd = os.open(self.lock_file, open_flags, open_mode)
56
+ except FileNotFoundError:
57
+ # On FUSE/NFS, os.open(O_CREAT) is not atomic: LOOKUP + CREATE can be split, allowing a concurrent
58
+ # unlink() to delete the file between them. For valid paths, treat ENOENT as transient contention.
59
+ # For invalid paths (e.g., empty string), re-raise to avoid infinite retry loops.
60
+ if self.lock_file and Path(self.lock_file).parent.exists():
61
+ return
62
+ raise
63
+ except PermissionError:
64
+ # Sticky-bit dirs (e.g. /tmp): O_CREAT fails if the file is owned by another user (#317).
65
+ # Fall back to opening the existing file without O_CREAT.
66
+ if not Path(self.lock_file).exists():
67
+ raise
68
+ try:
69
+ fd = os.open(self.lock_file, open_flags & ~os.O_CREAT, open_mode)
70
+ except FileNotFoundError:
71
+ return
72
+ if self.has_explicit_mode:
73
+ with suppress(PermissionError):
74
+ os.fchmod(fd, self._context.mode)
75
+ try:
76
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
77
+ except OSError as exception:
78
+ os.close(fd)
79
+ if exception.errno == ENOSYS:
80
+ with suppress(OSError):
81
+ Path(self.lock_file).unlink()
82
+ self._fallback_to_soft_lock()
83
+ self._acquire()
84
+ return
85
+ if exception.errno not in {EAGAIN, EWOULDBLOCK}:
86
+ raise
87
+ else:
88
+ # The file may have been unlinked by a concurrent _release() between our open() and flock().
89
+ # A lock on an unlinked inode is useless — discard and let the retry loop start fresh.
90
+ if os.fstat(fd).st_nlink == 0:
91
+ os.close(fd)
92
+ else:
93
+ self._context.lock_file_fd = fd
94
+
95
+ def _fallback_to_soft_lock(self) -> None:
96
+ from ._soft import SoftFileLock # noqa: PLC0415
97
+
98
+ warnings.warn("flock not supported on this filesystem, falling back to SoftFileLock", stacklevel=2)
99
+ from .asyncio import AsyncSoftFileLock, BaseAsyncFileLock # noqa: PLC0415
100
+
101
+ self.__class__ = AsyncSoftFileLock if isinstance(self, BaseAsyncFileLock) else SoftFileLock
102
+
103
+ def _release(self) -> None:
104
+ fd = cast("int", self._context.lock_file_fd)
105
+ self._context.lock_file_fd = None
106
+ fcntl.flock(fd, fcntl.LOCK_UN)
107
+ with suppress(OSError): # close can raise EIO on FUSE/Docker bind-mount filesystems
108
+ os.close(fd)
109
+
110
+
111
+ __all__ = [
112
+ "UnixFileLock",
113
+ "has_fcntl",
114
+ ]
data/diffusion/.venv/lib/python3.11/site-packages/filelock/_util.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import secrets
5
+ import stat
6
+ import sys
7
+ from errno import EACCES, EISDIR
8
+ from pathlib import Path
9
+
10
+
11
+ def raise_on_not_writable_file(filename: str) -> None:
12
+ """
13
+ Raise an exception if attempting to open the file for writing would fail.
14
+
15
+ Separates files that can never be written from files that are writable but currently locked.
16
+
17
+ :param filename: file to check
18
+
19
+ :raises OSError: as if the file was opened for writing.
20
+
21
+ """
22
+ try:
23
+ # lstat, not stat: it settles exists-and-writable in one syscall, and a hostile symlink planted at the lock
24
+ # path would otherwise make this inspect the link target, letting an attacker turn a contended acquire into a
25
+ # misleading PermissionError / IsADirectoryError and probe that target's attributes. The real open passes
26
+ # O_NOFOLLOW and refuses the symlink anyway.
27
+ file_stat = os.lstat(filename)
28
+ except OSError:
29
+ return # does not exist, or an error the caller cannot act on
30
+
31
+ # No mtime guard: the old `if st_mtime != 0` skip existed for NFS/Linux quirks where os.lstat could return an
32
+ # all-zero struct, which it no longer does. Skipping on mtime 0 let a read-only file or a directory at the lock
33
+ # path pass as missing, so acquire() blocked forever on an open that cannot succeed.
34
+ if not (file_stat.st_mode & stat.S_IWUSR):
35
+ raise PermissionError(EACCES, "Permission denied", filename)
36
+
37
+ if stat.S_ISDIR(file_stat.st_mode):
38
+ if sys.platform == "win32": # pragma: win32 cover
39
+ raise PermissionError(EACCES, "Permission denied", filename)
40
+ raise IsADirectoryError(EISDIR, "Is a directory", filename) # pragma: win32 no cover
41
+
42
+
43
+ def ensure_directory_exists(filename: Path | str) -> None:
44
+ """
45
+ Ensure the directory containing the file exists (create it if necessary).
46
+
47
+ :param filename: file.
48
+
49
+ """
50
+ Path(filename).parent.mkdir(parents=True, exist_ok=True)
51
+
52
+
53
+ def break_lock_file(lock_file: str, mtime_before: float, ino_before: int) -> None:
54
+ """
55
+ Atomically break a stale lock file that was judged stale at modification time *mtime_before*.
56
+
57
+ The file is renamed to a process-private name before being unlinked, so two processes breaking the same lock
58
+ cannot delete each other's work (only one rename of a given inode succeeds; the loser gets ``OSError``). After the
59
+ rename the file is re-checked: a newer modification time, or a different inode than *ino_before*, means a peer
60
+ recreated the lock between the stale decision and the rename, so we grabbed a live file and must abort, leaving the
61
+ renamed file in place rather than rolling back (a rollback rename is itself racy — same trade-off as the soft
62
+ read/write marker break). The inode check matters because filesystems with coarse modification-time granularity
63
+ (NFS, FAT) can give a same-second recreation the old mtime, so mtime alone would not catch it and a live lock would
64
+ be unlinked; the inode is the reliable identity, mirroring the token re-check in the soft read/write marker break.
65
+ ``lstat`` is used so a hostile symlink swapped in after the decision is not followed.
66
+
67
+ The break name carries a random token so it is unguessable and unique per attempt. Without it two breakers in the
68
+ same process share ``<lock>.break.<pid>``, and a second break can rename a freshly recreated live lock onto that
69
+ path in the window between the re-verify ``lstat`` above and the ``unlink`` below, so we would delete a live lock
70
+ the inode check just approved. A private name means nobody else can target our break path, matching the soft
71
+ read/write marker break.
72
+
73
+ :param lock_file: path to the lock file to break.
74
+ :param mtime_before: modification time observed when the lock was judged stale.
75
+ :param ino_before: inode number observed when the lock was judged stale.
76
+
77
+ :raises OSError: if the rename fails (e.g. the file vanished or is not owned in a sticky directory).
78
+
79
+ """
80
+ break_path = f"{lock_file}.break.{os.getpid()}.{secrets.token_hex(16)}"
81
+ Path(lock_file).rename(break_path)
82
+ try:
83
+ st_after = os.lstat(break_path)
84
+ except OSError:
85
+ return
86
+ if st_after.st_mtime > mtime_before or st_after.st_ino != ino_before:
87
+ return
88
+ Path(break_path).unlink()
89
+
90
+
91
+ __all__ = [
92
+ "break_lock_file",
93
+ "ensure_directory_exists",
94
+ "raise_on_not_writable_file",
95
+ ]
data/diffusion/.venv/lib/python3.11/site-packages/filelock/_windows.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import sys
5
+ from contextlib import suppress
6
+ from errno import EACCES
7
+ from pathlib import Path
8
+ from typing import cast
9
+
10
+ from ._api import BaseFileLock
11
+ from ._util import ensure_directory_exists, raise_on_not_writable_file
12
+
13
+ if sys.platform == "win32": # pragma: win32 cover
14
+ import ctypes
15
+ import msvcrt
16
+ from ctypes import wintypes
17
+
18
+ # Windows API constants for reparse point detection
19
+ FILE_ATTRIBUTE_REPARSE_POINT = 0x00000400
20
+ INVALID_FILE_ATTRIBUTES = 0xFFFFFFFF
21
+
22
+ # Load kernel32.dll
23
+ _kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
24
+ _kernel32.GetFileAttributesW.argtypes = [wintypes.LPCWSTR]
25
+ _kernel32.GetFileAttributesW.restype = wintypes.DWORD
26
+
27
+ def _is_reparse_point(path: str) -> bool:
28
+ """
29
+ Check if a path is a reparse point (symlink, junction, etc.) on Windows.
30
+
31
+ :param path: Path to check
32
+
33
+ :returns: True if path is a reparse point, False otherwise
34
+
35
+ :raises OSError: If GetFileAttributesW fails for reasons other than file-not-found
36
+
37
+ """
38
+ attrs = _kernel32.GetFileAttributesW(path)
39
+ if attrs == INVALID_FILE_ATTRIBUTES:
40
+ # File doesn't exist yet - that's fine, we'll create it
41
+ err = ctypes.get_last_error()
42
+ if err == 2: # noqa: PLR2004 # ERROR_FILE_NOT_FOUND
43
+ return False
44
+ if err == 3: # noqa: PLR2004 # ERROR_PATH_NOT_FOUND
45
+ return False
46
+ # Some other error - let caller handle it
47
+ return False
48
+ return bool(attrs & FILE_ATTRIBUTE_REPARSE_POINT)
49
+
50
+ class WindowsFileLock(BaseFileLock):
51
+ """
52
+ Uses the :func:`msvcrt.locking` function to hard lock the lock file on Windows systems.
53
+
54
+ Lock file cleanup: Windows attempts to delete the lock file after release, but deletion is
55
+ not guaranteed in multi-threaded scenarios where another thread holds an open handle. The lock
56
+ file may persist on disk, which does not affect lock correctness.
57
+ """
58
+
59
+ def _acquire(self) -> None:
60
+ raise_on_not_writable_file(self.lock_file)
61
+ ensure_directory_exists(self.lock_file)
62
+
63
+ # Security check: Refuse to open reparse points (symlinks, junctions)
64
+ # This prevents TOCTOU symlink attacks (CVE-TBD)
65
+ if _is_reparse_point(self.lock_file):
66
+ msg = f"Lock file is a reparse point (symlink/junction): {self.lock_file}"
67
+ raise OSError(msg)
68
+
69
+ flags = (
70
+ os.O_RDWR # open for read and write
71
+ | os.O_CREAT # create file if not exists
72
+ )
73
+ try:
74
+ fd = os.open(self.lock_file, flags, self._open_mode())
75
+ except OSError as exception:
76
+ if exception.errno != EACCES: # has no access to this lock
77
+ raise
78
+ else:
79
+ try:
80
+ msvcrt.locking(fd, msvcrt.LK_NBLCK, 1)
81
+ except OSError as exception:
82
+ os.close(fd) # close file first
83
+ if exception.errno != EACCES: # file is already locked
84
+ raise
85
+ else:
86
+ self._context.lock_file_fd = fd
87
+
88
+ def _release(self) -> None:
89
+ fd = cast("int", self._context.lock_file_fd)
90
+ self._context.lock_file_fd = None
91
+ msvcrt.locking(fd, msvcrt.LK_UNLCK, 1)
92
+ os.close(fd)
93
+
94
+ with suppress(OSError):
95
+ Path(self.lock_file).unlink()
96
+
97
+ else: # pragma: win32 no cover
98
+
99
+ class WindowsFileLock(BaseFileLock):
100
+ """Uses the :func:`msvcrt.locking` function to hard lock the lock file on Windows systems."""
101
+
102
+ def _acquire(self) -> None:
103
+ raise NotImplementedError
104
+
105
+ def _release(self) -> None:
106
+ raise NotImplementedError
107
+
108
+
109
+ __all__ = [
110
+ "WindowsFileLock",
111
+ ]
data/diffusion/.venv/lib/python3.11/site-packages/filelock/asyncio.py ADDED
@@ -0,0 +1,414 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """An asyncio-based implementation of the file lock."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import contextlib
7
+ import logging
8
+ import os
9
+ import time
10
+ from dataclasses import dataclass
11
+ from inspect import iscoroutinefunction
12
+ from threading import local
13
+ from typing import TYPE_CHECKING, Any, NoReturn, TypeVar
14
+
15
+ from ._api import _UNSET_FILE_MODE, BaseFileLock, FileLockContext, FileLockMeta, _canonical
16
+ from ._error import Timeout
17
+ from ._soft import SoftFileLock
18
+ from ._unix import UnixFileLock
19
+ from ._windows import WindowsFileLock
20
+
21
+ if TYPE_CHECKING:
22
+ import sys
23
+ from collections.abc import Callable
24
+ from concurrent import futures
25
+ from types import TracebackType
26
+
27
+ if sys.version_info >= (3, 11): # pragma: no cover (py311+)
28
+ from typing import Self
29
+ else: # pragma: no cover (<py311)
30
+ from typing_extensions import Self
31
+
32
+
33
+ _LOGGER = logging.getLogger("filelock")
34
+
35
+
36
+ @dataclass
37
+ class AsyncFileLockContext(FileLockContext):
38
+ """A dataclass which holds the context for a ``BaseAsyncFileLock`` object."""
39
+
40
+ #: Whether run in executor
41
+ run_in_executor: bool = True
42
+
43
+ #: The executor
44
+ executor: futures.Executor | None = None
45
+
46
+ #: The loop
47
+ loop: asyncio.AbstractEventLoop | None = None
48
+
49
+
50
+ class AsyncThreadLocalFileContext(AsyncFileLockContext, local):
51
+ """A thread local version of the ``FileLockContext`` class."""
52
+
53
+
54
+ class AsyncAcquireReturnProxy:
55
+ """A context-aware object that will release the lock file when exiting."""
56
+
57
+ def __init__(self, lock: BaseAsyncFileLock) -> None: # noqa: D107
58
+ self.lock = lock
59
+
60
+ async def __aenter__(self) -> BaseAsyncFileLock: # noqa: D105
61
+ return self.lock
62
+
63
+ async def __aexit__( # noqa: D105
64
+ self,
65
+ exc_type: type[BaseException] | None,
66
+ exc_value: BaseException | None,
67
+ traceback: TracebackType | None,
68
+ ) -> None:
69
+ await self.lock.release()
70
+
71
+
72
+ _AT = TypeVar("_AT", bound="BaseAsyncFileLock")
73
+
74
+
75
+ class AsyncFileLockMeta(FileLockMeta):
76
+ def __call__( # ty: ignore[invalid-method-override] # noqa: PLR0913
77
+ cls: type[_AT], # noqa: N805
78
+ lock_file: str | os.PathLike[str],
79
+ timeout: float = -1,
80
+ mode: int = _UNSET_FILE_MODE,
81
+ thread_local: bool = False, # noqa: FBT001, FBT002
82
+ *,
83
+ blocking: bool = True,
84
+ is_singleton: bool = False,
85
+ poll_interval: float = 0.05,
86
+ lifetime: float | None = None,
87
+ loop: asyncio.AbstractEventLoop | None = None,
88
+ run_in_executor: bool = True,
89
+ executor: futures.Executor | None = None,
90
+ ) -> _AT:
91
+ if thread_local and run_in_executor:
92
+ msg = "run_in_executor is not supported when thread_local is True"
93
+ raise ValueError(msg)
94
+ return super().__call__(
95
+ lock_file=lock_file,
96
+ timeout=timeout,
97
+ mode=mode,
98
+ thread_local=thread_local,
99
+ blocking=blocking,
100
+ is_singleton=is_singleton,
101
+ poll_interval=poll_interval,
102
+ lifetime=lifetime,
103
+ loop=loop,
104
+ run_in_executor=run_in_executor,
105
+ executor=executor,
106
+ )
107
+
108
+
109
+ class BaseAsyncFileLock(BaseFileLock, metaclass=AsyncFileLockMeta):
110
+ """
111
+ Base class for asynchronous file locks.
112
+
113
+ .. versionadded:: 3.15.0
114
+
115
+ """
116
+
117
+ _deadlock_holder_desc: str = "BaseAsyncFileLock instance in this task"
118
+
119
+ def __init__( # noqa: PLR0913
120
+ self,
121
+ lock_file: str | os.PathLike[str],
122
+ timeout: float = -1,
123
+ mode: int = _UNSET_FILE_MODE,
124
+ thread_local: bool = False, # noqa: FBT001, FBT002
125
+ *,
126
+ blocking: bool = True,
127
+ is_singleton: bool = False,
128
+ poll_interval: float = 0.05,
129
+ lifetime: float | None = None,
130
+ loop: asyncio.AbstractEventLoop | None = None,
131
+ run_in_executor: bool = True,
132
+ executor: futures.Executor | None = None,
133
+ ) -> None:
134
+ """
135
+ Create a new lock object.
136
+
137
+ :param lock_file: path to the file
138
+ :param timeout: default timeout when acquiring the lock, in seconds. It will be used as fallback value in the
139
+ acquire method, if no timeout value (``None``) is given. If you want to disable the timeout, set it to a
140
+ negative value. A timeout of 0 means that there is exactly one attempt to acquire the file lock.
141
+ :param mode: file permissions for the lockfile. When not specified, the OS controls permissions via umask and
142
+ default ACLs, preserving POSIX default ACL inheritance in shared directories.
143
+ :param thread_local: Whether this object's internal context should be thread local or not. If this is set to
144
+ ``False`` then the lock will be reentrant across threads. When ``True`` (the default), **all fields of the
145
+ lock's internal context are per-thread**, including the configuration values ``poll_interval``, ``timeout``,
146
+ ``blocking``, ``mode``, and ``lifetime``. Setting one of these properties from one thread does not change
147
+ the value seen by another thread; threads that did not perform the write continue to see the value supplied
148
+ at construction time. If you need configuration values to be visible across threads, construct the lock
149
+ with ``thread_local=False``.
150
+ :param blocking: whether the lock should be blocking or not
151
+ :param is_singleton: If this is set to ``True`` then only one instance of this class will be created per lock
152
+ file. This is useful if you want to use the lock object for reentrant locking without needing to pass the
153
+ same object around.
154
+ :param poll_interval: default interval for polling the lock file, in seconds. It will be used as fallback value
155
+ in the acquire method, if no poll_interval value (``None``) is given.
156
+ :param lifetime: maximum time in seconds a lock can be held before it is considered expired. When set, a waiting
157
+ process will break a lock whose file modification time is older than ``lifetime`` seconds. ``None`` (the
158
+ default) means locks never expire.
159
+ :param loop: The event loop to use. If not specified, the running event loop will be used.
160
+ :param run_in_executor: If this is set to ``True`` then the lock will be acquired in an executor.
161
+ :param executor: The executor to use. If not specified, the default executor will be used.
162
+
163
+ """
164
+ self._is_thread_local = thread_local
165
+ self._is_singleton = is_singleton
166
+
167
+ # Create the context. Note that external code should not work with the context directly and should instead use
168
+ # properties of this class.
169
+ kwargs: dict[str, Any] = {
170
+ "lock_file": os.fspath(lock_file),
171
+ "timeout": timeout,
172
+ "mode": mode,
173
+ "blocking": blocking,
174
+ "poll_interval": poll_interval,
175
+ "lifetime": lifetime,
176
+ "loop": loop,
177
+ "run_in_executor": run_in_executor,
178
+ "executor": executor,
179
+ }
180
+ self._context: AsyncFileLockContext = (AsyncThreadLocalFileContext if thread_local else AsyncFileLockContext)(
181
+ **kwargs
182
+ )
183
+
184
+ @property
185
+ def run_in_executor(self) -> bool:
186
+ """Whether run in executor."""
187
+ return self._context.run_in_executor
188
+
189
+ @property
190
+ def executor(self) -> futures.Executor | None:
191
+ """The executor."""
192
+ return self._context.executor
193
+
194
+ @executor.setter
195
+ def executor(self, value: futures.Executor | None) -> None: # pragma: no cover
196
+ """
197
+ Change the executor.
198
+
199
+ :param futures.Executor | None value: the new executor or ``None``
200
+
201
+ """
202
+ self._context.executor = value
203
+
204
+ @property
205
+ def loop(self) -> asyncio.AbstractEventLoop | None:
206
+ """The event loop."""
207
+ return self._context.loop
208
+
209
+ async def acquire( # ty: ignore[invalid-method-override]
210
+ self,
211
+ timeout: float | None = None,
212
+ poll_interval: float | None = None,
213
+ *,
214
+ blocking: bool | None = None,
215
+ cancel_check: Callable[[], bool] | None = None,
216
+ ) -> AsyncAcquireReturnProxy:
217
+ """
218
+ Try to acquire the file lock.
219
+
220
+ :param timeout: maximum wait time for acquiring the lock, ``None`` means use the default
221
+ :attr:`~BaseFileLock.timeout` is and if ``timeout < 0``, there is no timeout and this method will block
222
+ until the lock could be acquired
223
+ :param poll_interval: interval of trying to acquire the lock file, ``None`` means use the default
224
+ :attr:`~BaseFileLock.poll_interval`
225
+ :param blocking: defaults to True. If False, function will return immediately if it cannot obtain a lock on the
226
+ first attempt. Otherwise, this method will block until the timeout expires or the lock is acquired.
227
+ :param cancel_check: a callable returning ``True`` when the acquisition should be canceled. Checked on each poll
228
+ iteration. When triggered, raises :class:`~Timeout` just like an expired timeout.
229
+
230
+ :returns: a context object that will unlock the file when the context is exited
231
+
232
+ :raises Timeout: if fails to acquire lock within the timeout period
233
+
234
+ .. code-block:: python
235
+
236
+ # You can use this method in the context manager (recommended)
237
+ with lock.acquire():
238
+ pass
239
+
240
+ # Or use an equivalent try-finally construct:
241
+ lock.acquire()
242
+ try:
243
+ pass
244
+ finally:
245
+ lock.release()
246
+
247
+ """
248
+ # Use the default timeout, if no timeout is provided.
249
+ if timeout is None:
250
+ timeout = self._context.timeout
251
+
252
+ if blocking is None:
253
+ blocking = self._context.blocking
254
+
255
+ if poll_interval is None:
256
+ poll_interval = self._context.poll_interval
257
+
258
+ # Increment the number right at the beginning. We can still undo it, if something fails.
259
+ self._context.lock_counter += 1
260
+
261
+ canonical = _canonical(self.lock_file)
262
+ self._raise_if_would_deadlock(canonical, timeout=timeout, blocking=blocking)
263
+
264
+ start_time = time.perf_counter()
265
+ try:
266
+ await self._async_poll_until_acquired(
267
+ blocking=blocking,
268
+ cancel_check=cancel_check,
269
+ timeout=timeout,
270
+ poll_interval=poll_interval,
271
+ start_time=start_time,
272
+ )
273
+ except BaseException: # Something did go wrong, so decrement the counter.
274
+ self._undo_acquire(canonical)
275
+ raise
276
+ self._commit_acquire(canonical)
277
+ return AsyncAcquireReturnProxy(lock=self)
278
+
279
+ async def _async_poll_until_acquired(
280
+ self,
281
+ *,
282
+ blocking: bool,
283
+ cancel_check: Callable[[], bool] | None,
284
+ timeout: float,
285
+ poll_interval: float,
286
+ start_time: float,
287
+ ) -> None:
288
+ lock_id = id(self)
289
+ lock_filename = self.lock_file
290
+ while True:
291
+ if not self.is_locked:
292
+ self._try_break_expired_lock()
293
+ _LOGGER.debug("Attempting to acquire lock %s on %s", lock_id, lock_filename)
294
+ await self._run_internal_method(self._acquire)
295
+ if self.is_locked:
296
+ _LOGGER.debug("Lock %s acquired on %s", lock_id, lock_filename)
297
+ return
298
+ if self._check_give_up(
299
+ lock_id,
300
+ lock_filename,
301
+ blocking=blocking,
302
+ cancel_check=cancel_check,
303
+ timeout=timeout,
304
+ start_time=start_time,
305
+ ):
306
+ raise Timeout(lock_filename)
307
+ msg = "Lock %s not acquired on %s, waiting %s seconds ..."
308
+ _LOGGER.debug(msg, lock_id, lock_filename, poll_interval)
309
+ await asyncio.sleep(poll_interval)
310
+
311
+ async def release(self, force: bool = False) -> None: # ty: ignore[invalid-method-override] # noqa: FBT001, FBT002
312
+ """
313
+ Release the file lock. The lock is only completely released when the lock counter reaches 0. The lock file
314
+ itself may be deleted automatically, the behavior is platform-specific.
315
+
316
+ :param force: If true, the lock counter is ignored and the lock is released in every case.
317
+
318
+ """
319
+ if self.is_locked:
320
+ self._context.lock_counter -= 1
321
+
322
+ if self._context.lock_counter == 0 or force:
323
+ lock_id, lock_filename = id(self), self.lock_file
324
+
325
+ _LOGGER.debug("Attempting to release lock %s on %s", lock_id, lock_filename)
326
+ await self._run_internal_method(self._release)
327
+ self._context.lock_counter = 0
328
+ self._drop_registry_entry()
329
+ _LOGGER.debug("Lock %s released on %s", lock_id, lock_filename)
330
+
331
+ async def _run_internal_method(self, method: Callable[[], Any]) -> None:
332
+ if iscoroutinefunction(method):
333
+ await method()
334
+ elif self.run_in_executor:
335
+ await asyncio.get_running_loop().run_in_executor(self.executor, method)
336
+ else:
337
+ method()
338
+
339
+ def __enter__(self) -> NoReturn:
340
+ """Sync context manager entry is not supported because lock acquisition is a coroutine."""
341
+ msg = "Use `async with` — acquire/release are coroutines and cannot be awaited in a sync context manager."
342
+ raise NotImplementedError(msg)
343
+
344
+ def __exit__(
345
+ self,
346
+ exc_type: type[BaseException] | None,
347
+ exc_value: BaseException | None,
348
+ traceback: object,
349
+ ) -> None:
350
+ """Sync context manager exit is not supported because lock release is a coroutine."""
351
+ msg = "Use `async with` — acquire/release are coroutines and cannot be awaited in a sync context manager."
352
+ raise NotImplementedError(msg)
353
+
354
+ async def __aenter__(self) -> Self:
355
+ """
356
+ Acquire the lock.
357
+
358
+ :returns: the lock object
359
+
360
+ """
361
+ await self.acquire()
362
+ return self
363
+
364
+ async def __aexit__(
365
+ self,
366
+ exc_type: type[BaseException] | None,
367
+ exc_value: BaseException | None,
368
+ traceback: TracebackType | None,
369
+ ) -> None:
370
+ """
371
+ Release the lock.
372
+
373
+ :param exc_type: the exception type if raised
374
+ :param exc_value: the exception value if raised
375
+ :param traceback: the exception traceback if raised
376
+
377
+ """
378
+ await self.release()
379
+
380
+ def __del__(self) -> None:
381
+ """Release on deletion — safe to call during GC even when no event loop is running."""
382
+ with contextlib.suppress(Exception):
383
+ try:
384
+ loop = asyncio.get_running_loop()
385
+ except RuntimeError:
386
+ # No running loop — try stored loop or create one
387
+ loop = self._context.loop if self._context.loop and not self._context.loop.is_closed() else None
388
+ if loop is None:
389
+ return
390
+ if not loop.is_running(): # pragma: no cover
391
+ loop.run_until_complete(self.release(force=True))
392
+ else:
393
+ loop.create_task(self.release(force=True))
394
+
395
+
396
+ class AsyncSoftFileLock(SoftFileLock, BaseAsyncFileLock):
397
+ """Simply watches the existence of the lock file."""
398
+
399
+
400
+ class AsyncUnixFileLock(UnixFileLock, BaseAsyncFileLock):
401
+ """Uses the :func:`fcntl.flock` to hard lock the lock file on unix systems."""
402
+
403
+
404
+ class AsyncWindowsFileLock(WindowsFileLock, BaseAsyncFileLock):
405
+ """Uses the :func:`msvcrt.locking` to hard lock the lock file on windows systems."""
406
+
407
+
408
+ __all__ = [
409
+ "AsyncAcquireReturnProxy",
410
+ "AsyncSoftFileLock",
411
+ "AsyncUnixFileLock",
412
+ "AsyncWindowsFileLock",
413
+ "BaseAsyncFileLock",
414
+ ]
data/diffusion/.venv/lib/python3.11/site-packages/filelock/py.typed ADDED
File without changes
data/diffusion/.venv/lib/python3.11/site-packages/filelock/version.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # file generated by vcs-versioning
2
+ # don't change, don't track in version control
3
+ from __future__ import annotations
4
+
5
+ __all__ = [
6
+ "__version__",
7
+ "__version_tuple__",
8
+ "version",
9
+ "version_tuple",
10
+ "__commit_id__",
11
+ "commit_id",
12
+ ]
13
+
14
+ version: str
15
+ __version__: str
16
+ __version_tuple__: tuple[int | str, ...]
17
+ version_tuple: tuple[int | str, ...]
18
+ commit_id: str | None
19
+ __commit_id__: str | None
20
+
21
+ __version__ = version = '3.29.7'
22
+ __version_tuple__ = version_tuple = (3, 29, 7)
23
+
24
+ __commit_id__ = commit_id = None
data/diffusion/.venv/lib/python3.11/site-packages/idna-3.18.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ uv
data/diffusion/.venv/lib/python3.11/site-packages/idna-3.18.dist-info/METADATA ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: idna
3
+ Version: 3.18
4
+ Summary: Internationalized Domain Names in Applications (IDNA)
5
+ Author-email: Kim Davies <kim+pypi@gumleaf.org>
6
+ Requires-Python: >=3.9
7
+ Description-Content-Type: text/markdown
8
+ License-Expression: BSD-3-Clause
9
+ Classifier: Development Status :: 5 - Production/Stable
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Intended Audience :: System Administrators
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3 :: Only
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Programming Language :: Python :: 3.14
22
+ Classifier: Programming Language :: Python :: Implementation :: CPython
23
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
24
+ Classifier: Topic :: Internet :: Name Service (DNS)
25
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
26
+ Classifier: Topic :: Utilities
27
+ License-File: LICENSE.md
28
+ Requires-Dist: ruff >= 0.6.2 ; extra == "all"
29
+ Requires-Dist: mypy >= 1.11.2 ; extra == "all"
30
+ Requires-Dist: pytest >= 8.3.2 ; extra == "all"
31
+ Project-URL: Changelog, https://github.com/kjd/idna/blob/master/HISTORY.md
32
+ Project-URL: Issue tracker, https://github.com/kjd/idna/issues
33
+ Project-URL: Source, https://github.com/kjd/idna
34
+ Provides-Extra: all
35
+
36
+ # Internationalized Domain Names in Applications (IDNA)
37
+
38
+ Support for [Internationalized Domain Names in Applications
39
+ (IDNA)](https://tools.ietf.org/html/rfc5891) and [Unicode IDNA
40
+ Compatibility Processing](https://unicode.org/reports/tr46/). It
41
+ supersedes the standard library's `encodings.idna`, which only
42
+ implements the 2003 specification, offering broader script coverage and
43
+ limiting domains with known security vulnerabilities.
44
+
45
+ ## Usage
46
+
47
+ Package may be installed from [PyPI](https://pypi.org/project/idna/) via
48
+ the typical methods (e.g. `python3 -m pip install idna`)
49
+
50
+ For typical usage, the `encode` and `decode` functions will take a
51
+ domain name argument and perform a conversion to ASCII-compatible encoding
52
+ (known as A-labels), or to Unicode strings (known as U-labels)
53
+ respectively.
54
+
55
+ ```pycon
56
+ >>> import idna
57
+ >>> idna.encode('ドメイン.テスト')
58
+ b'xn--eckwd4c7c.xn--zckzah'
59
+ >>> print(idna.decode('xn--eckwd4c7c.xn--zckzah'))
60
+ ドメイン.テスト
61
+ ```
62
+
63
+ Conversions can be applied at a per-label basis using the `ulabel` or
64
+ `alabel` functions for specialized use cases.
65
+
66
+
67
+ ### Compatibility Mapping (UTS #46)
68
+
69
+ This library provides support for [Unicode IDNA Compatibility
70
+ Processing](https://unicode.org/reports/tr46/) which normalizes input from
71
+ different potential ways a user may input a domain prior to performing the IDNA
72
+ conversion operations. This functionality, known as a
73
+ [mapping](https://tools.ietf.org/html/rfc5895), is considered by the
74
+ specification to be a local user-interface issue distinct from IDNA
75
+ conversion functionality.
76
+
77
+ For example, "Königsgäßchen" is not a permissible label as capital letters
78
+ are not allowed. UTS 46 will convert this into lower case prior to applying
79
+ the IDNA conversion.
80
+
81
+ ```pycon
82
+ >>> import idna
83
+ >>> idna.encode('Königsgäßchen')
84
+ ...
85
+ idna.core.InvalidCodepoint: Codepoint U+004B at position 1 of 'Königsgäßchen' not allowed
86
+ >>> idna.encode('Königsgäßchen', uts46=True)
87
+ b'xn--knigsgchen-b4a3dun'
88
+ >>> idna.decode('xn--knigsgchen-b4a3dun')
89
+ 'königsgäßchen'
90
+ ```
91
+
92
+ When performing a decode operation for display purposes, `decode()`
93
+ accepts a `display=True` argument that leaves any `xn--` label that
94
+ fails to decode unchanged. This is useful for user interface display
95
+ where a domain is in use, the A-label form can be presented when it
96
+ is not a valid IDN.
97
+
98
+
99
+ ## Exceptions
100
+
101
+ All errors raised during conversion derive from the `idna.IDNAError`
102
+ base class. The more specific exceptions are:
103
+
104
+ * `idna.IDNABidiError` — raised when a label contains an illegal
105
+ combination of left-to-right and right-to-left characters.
106
+ * `idna.InvalidCodepoint` — raised when a label contains a codepoint
107
+ that is INVALID for IDNA.
108
+ * `idna.InvalidCodepointContext` — raised when a CONTEXTO or CONTEXTJ
109
+ codepoint appears in a position whose contextual requirements are
110
+ not satisfied.
111
+
112
+
113
+ ## Command-line tool
114
+
115
+ The package supports command-line usage to convert domain names
116
+ between their Unicode and ASCII-compatible forms. It can be run either
117
+ as a module (`python3 -m idna`) or, once installed (such as with `uv
118
+ tool` or `pipx`), via the `idna` script:
119
+
120
+ ```bash
121
+ $ uv tool install idna
122
+ $ idna xn--e1afmkfd.xn--p1ai
123
+ пример.рф
124
+ $ idna пример.рф
125
+ xn--e1afmkfd.xn--p1ai
126
+ ```
127
+
128
+ Mode can be specified with `-e`/`--encode` or `-d`/`--decode`, otherwise
129
+ it will be chosen automatically based on the first input. Multiple
130
+ domains can be supplied either as arguments or through standard input.
131
+ UTS #46 mapping is applied by default, which lets the tool accept
132
+ inputs that aren't strictly valid IDNA 2008 by normalising them first,
133
+ pass `--strict` to disable UTS #46.
134
+
135
+ Conversion failures are reported on stderr together with the
136
+ offending input; processing continues with the remaining domains and
137
+ the tool exits with a non-zero status if any conversion failed.
138
+
139
+
140
+ ## Additional Notes
141
+
142
+ * **Version support**. This library supports Python 3.9 and higher.
143
+ As this library serves as a low-level toolkit for a variety of
144
+ applications, we strive to support all versions of Python that are
145
+ not beyond end-of-life.
146
+
147
+ * **Emoji**. It is an occasional request to support emoji domains in
148
+ this library. Encoding of symbols like emoji is expressly prohibited by
149
+ the IDNA technical standard, and emoji domains are broadly phased
150
+ out across the domain industry due to associated security risks.
151
+
152
+ * **Regenerating lookup tables**. The IDNA and UTS 46 functionality
153
+ relies upon pre-calculated lookup tables, generated using the
154
+ `idna-data` script in [`tools/`](tools/README.md).
155
+
data/diffusion/.venv/lib/python3.11/site-packages/idna-3.18.dist-info/RECORD ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ../../../bin/idna,sha256=4chDdzsOhyujVvCniBMHlc6kQu90-3AVYbMU05ellcc,318
2
+ idna-3.18.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2
3
+ idna-3.18.dist-info/METADATA,sha256=Rt_m5axGLQ9oDs2avPZugptqIzSCS02eOXmzETXK8oE,6119
4
+ idna-3.18.dist-info/RECORD,,
5
+ idna-3.18.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ idna-3.18.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82
7
+ idna-3.18.dist-info/entry_points.txt,sha256=7H3nGOHap3jnLE5e7q7Ywr9Vq8axB7WIj5-C_4N2vhw,38
8
+ idna-3.18.dist-info/licenses/LICENSE.md,sha256=GppPDj1HmickDd1ZqRN6ZqtKD539yMphiMwL_YUYfwQ,1541
9
+ idna/__init__.py,sha256=MPqNDLZbXqGaNdXxAFhiqFPKEQXju2jNQhCey6-5eJM,868
10
+ idna/__main__.py,sha256=4JMK66Wj4uLZTKbF-sT3LAxOsr6buig77PmOkJCRRxw,83
11
+ idna/cli.py,sha256=swqJLMNc8Uzs60KziNpbWnHuqlG3WRQwJSbo4n8xDAo,4139
12
+ idna/codec.py,sha256=JRbo-f7pEkLdWeiH89Z72UR4VBYhvKDFrQBeNX6sRDE,5040
13
+ idna/compat.py,sha256=AepA39ceRHxkfHP41-FvKW5Ki-f4PfUZ90RUMlCNdmo,1353
14
+ idna/core.py,sha256=SfOr1xO3PoE0RDYx7bMciAnjiyjJPbPw_93AB5IUYOw,24685
15
+ idna/idnadata.py,sha256=Af-mo8WBmkhAK6TyXKOQH88OX0mQNDKtdL7UWtQpppk,44862
16
+ idna/intranges.py,sha256=g49scLSkqJtAhLmOODa7hVHriSjmb60tiTsEoocJdBI,1851
17
+ idna/package_data.py,sha256=TeI94EqAFAFaXfBJwsOPUMLn2969uirPa-DaeaceAyU,21
18
+ idna/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
19
+ idna/uts46data.py,sha256=jujNz5QqWMcJf-XYLv4X1jBvb5FlI0t6-e1mILsgbPk,234325
data/diffusion/.venv/lib/python3.11/site-packages/idna-3.18.dist-info/REQUESTED ADDED
File without changes
data/diffusion/.venv/lib/python3.11/site-packages/idna-3.18.dist-info/WHEEL ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: flit 3.12.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
data/diffusion/.venv/lib/python3.11/site-packages/idna-3.18.dist-info/entry_points.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ [console_scripts]
2
+ idna=idna.cli:main
3
+
data/diffusion/.venv/lib/python3.11/site-packages/setuptools/_core_metadata.py ADDED
@@ -0,0 +1,337 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Handling of Core Metadata for Python packages (including reading and writing).
3
+
4
+ See: https://packaging.python.org/en/latest/specifications/core-metadata/
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ import stat
11
+ import textwrap
12
+ from email import message_from_file
13
+ from email.message import Message
14
+ from tempfile import NamedTemporaryFile
15
+
16
+ from packaging.markers import Marker
17
+ from packaging.requirements import Requirement
18
+ from packaging.utils import canonicalize_name, canonicalize_version
19
+ from packaging.version import Version
20
+
21
+ from . import _normalization, _reqs
22
+ from ._static import is_static
23
+ from .warnings import SetuptoolsDeprecationWarning
24
+
25
+ from distutils.util import rfc822_escape
26
+
27
+
28
+ def get_metadata_version(self):
29
+ mv = getattr(self, 'metadata_version', None)
30
+ if mv is None:
31
+ mv = Version('2.4')
32
+ self.metadata_version = mv
33
+ return mv
34
+
35
+
36
+ def rfc822_unescape(content: str) -> str:
37
+ """Reverse RFC-822 escaping by removing leading whitespaces from content."""
38
+ lines = content.splitlines()
39
+ if len(lines) == 1:
40
+ return lines[0].lstrip()
41
+ return '\n'.join((lines[0].lstrip(), textwrap.dedent('\n'.join(lines[1:]))))
42
+
43
+
44
+ def _read_field_from_msg(msg: Message, field: str) -> str | None:
45
+ """Read Message header field."""
46
+ value = msg[field]
47
+ if value == 'UNKNOWN':
48
+ return None
49
+ return value
50
+
51
+
52
+ def _read_field_unescaped_from_msg(msg: Message, field: str) -> str | None:
53
+ """Read Message header field and apply rfc822_unescape."""
54
+ value = _read_field_from_msg(msg, field)
55
+ if value is None:
56
+ return value
57
+ return rfc822_unescape(value)
58
+
59
+
60
+ def _read_list_from_msg(msg: Message, field: str) -> list[str] | None:
61
+ """Read Message header field and return all results as list."""
62
+ values = msg.get_all(field, None)
63
+ if values == []:
64
+ return None
65
+ return values
66
+
67
+
68
+ def _read_payload_from_msg(msg: Message) -> str | None:
69
+ value = str(msg.get_payload()).strip()
70
+ if value == 'UNKNOWN' or not value:
71
+ return None
72
+ return value
73
+
74
+
75
+ def read_pkg_file(self, file):
76
+ """Reads the metadata values from a file object."""
77
+ msg = message_from_file(file)
78
+
79
+ self.metadata_version = Version(msg['metadata-version'])
80
+ self.name = _read_field_from_msg(msg, 'name')
81
+ self.version = _read_field_from_msg(msg, 'version')
82
+ self.description = _read_field_from_msg(msg, 'summary')
83
+ # we are filling author only.
84
+ self.author = _read_field_from_msg(msg, 'author')
85
+ self.maintainer = None
86
+ self.author_email = _read_field_from_msg(msg, 'author-email')
87
+ self.maintainer_email = None
88
+ self.url = _read_field_from_msg(msg, 'home-page')
89
+ self.download_url = _read_field_from_msg(msg, 'download-url')
90
+ self.license = _read_field_unescaped_from_msg(msg, 'license')
91
+ self.license_expression = _read_field_unescaped_from_msg(msg, 'license-expression')
92
+
93
+ self.long_description = _read_field_unescaped_from_msg(msg, 'description')
94
+ if self.long_description is None and self.metadata_version >= Version('2.1'):
95
+ self.long_description = _read_payload_from_msg(msg)
96
+ self.description = _read_field_from_msg(msg, 'summary')
97
+
98
+ if 'keywords' in msg:
99
+ self.keywords = _read_field_from_msg(msg, 'keywords').split(',')
100
+
101
+ self.platforms = _read_list_from_msg(msg, 'platform')
102
+ self.classifiers = _read_list_from_msg(msg, 'classifier')
103
+
104
+ # PEP 314 - these fields only exist in 1.1
105
+ if self.metadata_version == Version('1.1'):
106
+ self.requires = _read_list_from_msg(msg, 'requires')
107
+ self.provides = _read_list_from_msg(msg, 'provides')
108
+ self.obsoletes = _read_list_from_msg(msg, 'obsoletes')
109
+ else:
110
+ self.requires = None
111
+ self.provides = None
112
+ self.obsoletes = None
113
+
114
+ self.license_files = _read_list_from_msg(msg, 'license-file')
115
+
116
+
117
+ def single_line(val):
118
+ """
119
+ Quick and dirty validation for Summary pypa/setuptools#1390.
120
+ """
121
+ if '\n' in val:
122
+ # TODO: Replace with `raise ValueError("newlines not allowed")`
123
+ # after reviewing #2893.
124
+ msg = "newlines are not allowed in `summary` and will break in the future"
125
+ SetuptoolsDeprecationWarning.emit("Invalid config.", msg)
126
+ # due_date is undefined. Controversial change, there was a lot of push back.
127
+ val = val.strip().split('\n')[0]
128
+ return val
129
+
130
+
131
+ def write_pkg_info(self, base_dir):
132
+ """Write the PKG-INFO file into the release tree."""
133
+ temp = ""
134
+ final = os.path.join(base_dir, 'PKG-INFO')
135
+ try:
136
+ # Use a temporary file while writing to avoid race conditions
137
+ # (e.g. `importlib.metadata` reading `.egg-info/PKG-INFO`):
138
+ with NamedTemporaryFile("w", encoding="utf-8", dir=base_dir, delete=False) as f:
139
+ temp = f.name
140
+ self.write_pkg_file(f)
141
+ permissions = stat.S_IMODE(os.lstat(temp).st_mode)
142
+ os.chmod(temp, permissions | stat.S_IRGRP | stat.S_IROTH)
143
+ os.replace(temp, final) # atomic operation.
144
+ finally:
145
+ if temp and os.path.exists(temp):
146
+ os.remove(temp)
147
+
148
+
149
+ # Based on Python 3.5 version
150
+ def write_pkg_file(self, file): # noqa: C901 # is too complex (14) # FIXME
151
+ """Write the PKG-INFO format data to a file object."""
152
+ version = self.get_metadata_version()
153
+
154
+ def write_field(key, value):
155
+ file.write(f"{key}: {value}\n")
156
+
157
+ write_field('Metadata-Version', str(version))
158
+ write_field('Name', self.get_name())
159
+ write_field('Version', self.get_version())
160
+
161
+ summary = self.get_description()
162
+ if summary:
163
+ write_field('Summary', single_line(summary))
164
+
165
+ optional_fields = (
166
+ ('Home-page', 'url'),
167
+ ('Download-URL', 'download_url'),
168
+ ('Author', 'author'),
169
+ ('Author-email', 'author_email'),
170
+ ('Maintainer', 'maintainer'),
171
+ ('Maintainer-email', 'maintainer_email'),
172
+ )
173
+
174
+ for field, attr in optional_fields:
175
+ attr_val = getattr(self, attr, None)
176
+ if attr_val is not None:
177
+ write_field(field, attr_val)
178
+
179
+ if license_expression := self.license_expression:
180
+ write_field('License-Expression', license_expression)
181
+ elif license := self.get_license():
182
+ write_field('License', rfc822_escape(license))
183
+
184
+ for label, url in self.project_urls.items():
185
+ write_field('Project-URL', f'{label}, {url}')
186
+
187
+ keywords = ','.join(self.get_keywords())
188
+ if keywords:
189
+ write_field('Keywords', keywords)
190
+
191
+ platforms = self.get_platforms() or []
192
+ for platform in platforms:
193
+ write_field('Platform', platform)
194
+
195
+ self._write_list(file, 'Classifier', self.get_classifiers())
196
+
197
+ # PEP 314
198
+ self._write_list(file, 'Requires', self.get_requires())
199
+ self._write_list(file, 'Provides', self.get_provides())
200
+ self._write_list(file, 'Obsoletes', self.get_obsoletes())
201
+
202
+ # Setuptools specific for PEP 345
203
+ if hasattr(self, 'python_requires'):
204
+ write_field('Requires-Python', self.python_requires)
205
+
206
+ # PEP 566
207
+ if self.long_description_content_type:
208
+ write_field('Description-Content-Type', self.long_description_content_type)
209
+
210
+ safe_license_files = map(_safe_license_file, self.license_files or [])
211
+ self._write_list(file, 'License-File', safe_license_files)
212
+ _write_requirements(self, file)
213
+
214
+ for field, attr in _POSSIBLE_DYNAMIC_FIELDS.items():
215
+ if (val := getattr(self, attr, None)) and not is_static(val):
216
+ write_field('Dynamic', field)
217
+
218
+ long_description = self.get_long_description()
219
+ if long_description:
220
+ file.write(f"\n{long_description}")
221
+ if not long_description.endswith("\n"):
222
+ file.write("\n")
223
+
224
+
225
+ def _write_requirements(self, file):
226
+ for req in _reqs.parse(self.install_requires):
227
+ file.write(f"Requires-Dist: {req}\n")
228
+
229
+ processed_extras = {}
230
+ for augmented_extra, reqs in self.extras_require.items():
231
+ # Historically, setuptools allows "augmented extras": `<extra>:<condition>`
232
+ unsafe_extra, _, condition = augmented_extra.partition(":")
233
+ unsafe_extra = unsafe_extra.strip()
234
+ extra = _normalization.safe_extra(unsafe_extra)
235
+
236
+ if extra:
237
+ _write_provides_extra(file, processed_extras, extra, unsafe_extra)
238
+ for req in _reqs.parse_strings(reqs):
239
+ r = _include_extra(req, extra, condition.strip())
240
+ file.write(f"Requires-Dist: {r}\n")
241
+
242
+ return processed_extras
243
+
244
+
245
+ def _include_extra(req: str, extra: str, condition: str) -> Requirement:
246
+ r = Requirement(req) # create a fresh object that can be modified
247
+ parts = (
248
+ f"({r.marker})" if r.marker else None,
249
+ f"({condition})" if condition else None,
250
+ f"extra == {extra!r}" if extra else None,
251
+ )
252
+ r.marker = Marker(" and ".join(x for x in parts if x))
253
+ return r
254
+
255
+
256
+ def _write_provides_extra(file, processed_extras, safe, unsafe):
257
+ previous = processed_extras.get(safe)
258
+ if previous == unsafe:
259
+ SetuptoolsDeprecationWarning.emit(
260
+ 'Ambiguity during "extra" normalization for dependencies.',
261
+ f"""
262
+ {previous!r} and {unsafe!r} normalize to the same value:\n
263
+ {safe!r}\n
264
+ In future versions, setuptools might halt the build process.
265
+ """,
266
+ see_url="https://peps.python.org/pep-0685/",
267
+ )
268
+ else:
269
+ processed_extras[safe] = unsafe
270
+ file.write(f"Provides-Extra: {safe}\n")
271
+
272
+
273
+ # from pypa/distutils#244; needed only until that logic is always available
274
+ def get_fullname(self):
275
+ return _distribution_fullname(self.get_name(), self.get_version())
276
+
277
+
278
+ def _distribution_fullname(name: str, version: str) -> str:
279
+ """
280
+ >>> _distribution_fullname('setup.tools', '1.0-2')
281
+ 'setup_tools-1.0.post2'
282
+ >>> _distribution_fullname('setup-tools', '1.2post2')
283
+ 'setup_tools-1.2.post2'
284
+ >>> _distribution_fullname('setup-tools', '1.0-r2')
285
+ 'setup_tools-1.0.post2'
286
+ >>> _distribution_fullname('setup.tools', '1.0.post')
287
+ 'setup_tools-1.0.post0'
288
+ >>> _distribution_fullname('setup.tools', '1.0+ubuntu-1')
289
+ 'setup_tools-1.0+ubuntu.1'
290
+ """
291
+ return "{}-{}".format(
292
+ canonicalize_name(name).replace('-', '_'),
293
+ canonicalize_version(version, strip_trailing_zero=False),
294
+ )
295
+
296
+
297
+ def _safe_license_file(file):
298
+ # XXX: Do we need this after the deprecation discussed in #4892, #4896??
299
+ normalized = os.path.normpath(file).replace(os.sep, "/")
300
+ if "../" in normalized:
301
+ return os.path.basename(normalized) # Temporarily restore pre PEP639 behaviour
302
+ return normalized
303
+
304
+
305
+ _POSSIBLE_DYNAMIC_FIELDS = {
306
+ # Core Metadata Field x related Distribution attribute
307
+ "author": "author",
308
+ "author-email": "author_email",
309
+ "classifier": "classifiers",
310
+ "description": "long_description",
311
+ "description-content-type": "long_description_content_type",
312
+ "download-url": "download_url",
313
+ "home-page": "url",
314
+ "keywords": "keywords",
315
+ "license": "license",
316
+ # XXX: License-File is complicated because the user gives globs that are expanded
317
+ # during the build. Without special handling it is likely always
318
+ # marked as Dynamic, which is an acceptable outcome according to:
319
+ # https://github.com/pypa/setuptools/issues/4629#issuecomment-2331233677
320
+ "license-file": "license_files",
321
+ "license-expression": "license_expression", # PEP 639
322
+ "maintainer": "maintainer",
323
+ "maintainer-email": "maintainer_email",
324
+ "obsoletes": "obsoletes",
325
+ # "obsoletes-dist": "obsoletes_dist", # NOT USED
326
+ "platform": "platforms",
327
+ "project-url": "project_urls",
328
+ "provides": "provides",
329
+ # "provides-dist": "provides_dist", # NOT USED
330
+ "provides-extra": "extras_require",
331
+ "requires": "requires",
332
+ "requires-dist": "install_requires",
333
+ # "requires-external": "requires_external", # NOT USED
334
+ "requires-python": "python_requires",
335
+ "summary": "description",
336
+ # "supported-platform": "supported_platforms", # NOT USED
337
+ }
data/diffusion/.venv/lib/python3.11/site-packages/setuptools/_imp.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Re-implementation of find_module and get_frozen_object
3
+ from the deprecated imp module.
4
+ """
5
+
6
+ import importlib.machinery
7
+ import importlib.util
8
+ import os
9
+ import tokenize
10
+ from importlib.util import module_from_spec
11
+
12
+ PY_SOURCE = 1
13
+ PY_COMPILED = 2
14
+ C_EXTENSION = 3
15
+ C_BUILTIN = 6
16
+ PY_FROZEN = 7
17
+
18
+
19
+ def find_spec(module, paths):
20
+ finder = (
21
+ importlib.machinery.PathFinder().find_spec
22
+ if isinstance(paths, list)
23
+ else importlib.util.find_spec
24
+ )
25
+ return finder(module, paths)
26
+
27
+
28
+ def find_module(module, paths=None):
29
+ """Just like 'imp.find_module()', but with package support"""
30
+ spec = find_spec(module, paths)
31
+ if spec is None:
32
+ raise ImportError(f"Can't find {module}")
33
+ if not spec.has_location and hasattr(spec, 'submodule_search_locations'):
34
+ spec = importlib.util.spec_from_loader('__init__.py', spec.loader)
35
+
36
+ kind = -1
37
+ file = None
38
+ static = isinstance(spec.loader, type)
39
+ if (
40
+ spec.origin == 'frozen'
41
+ or static
42
+ and issubclass(spec.loader, importlib.machinery.FrozenImporter)
43
+ ):
44
+ kind = PY_FROZEN
45
+ path = None # imp compabilty
46
+ suffix = mode = '' # imp compatibility
47
+ elif (
48
+ spec.origin == 'built-in'
49
+ or static
50
+ and issubclass(spec.loader, importlib.machinery.BuiltinImporter)
51
+ ):
52
+ kind = C_BUILTIN
53
+ path = None # imp compabilty
54
+ suffix = mode = '' # imp compatibility
55
+ elif spec.has_location:
56
+ path = spec.origin
57
+ suffix = os.path.splitext(path)[1]
58
+ mode = 'r' if suffix in importlib.machinery.SOURCE_SUFFIXES else 'rb'
59
+
60
+ if suffix in importlib.machinery.SOURCE_SUFFIXES:
61
+ kind = PY_SOURCE
62
+ file = tokenize.open(path)
63
+ elif suffix in importlib.machinery.BYTECODE_SUFFIXES:
64
+ kind = PY_COMPILED
65
+ file = open(path, 'rb')
66
+ elif suffix in importlib.machinery.EXTENSION_SUFFIXES:
67
+ kind = C_EXTENSION
68
+
69
+ else:
70
+ path = None
71
+ suffix = mode = ''
72
+
73
+ return file, path, (suffix, mode, kind)
74
+
75
+
76
+ def get_frozen_object(module, paths=None):
77
+ spec = find_spec(module, paths)
78
+ if not spec:
79
+ raise ImportError(f"Can't find {module}")
80
+ return spec.loader.get_code(module)
81
+
82
+
83
+ def get_module(module, paths, info):
84
+ spec = find_spec(module, paths)
85
+ if not spec:
86
+ raise ImportError(f"Can't find {module}")
87
+ return module_from_spec(spec)
data/diffusion/.venv/lib/python3.11/site-packages/setuptools/build_meta.py ADDED
@@ -0,0 +1,556 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A PEP 517 interface to setuptools
2
+
3
+ Previously, when a user or a command line tool (let's call it a "frontend")
4
+ needed to make a request of setuptools to take a certain action, for
5
+ example, generating a list of installation requirements, the frontend
6
+ would call "setup.py egg_info" or "setup.py bdist_wheel" on the command line.
7
+
8
+ PEP 517 defines a different method of interfacing with setuptools. Rather
9
+ than calling "setup.py" directly, the frontend should:
10
+
11
+ 1. Set the current directory to the directory with a setup.py file
12
+ 2. Import this module into a safe python interpreter (one in which
13
+ setuptools can potentially set global variables or crash hard).
14
+ 3. Call one of the functions defined in PEP 517.
15
+
16
+ What each function does is defined in PEP 517. However, here is a "casual"
17
+ definition of the functions (this definition should not be relied on for
18
+ bug reports or API stability):
19
+
20
+ - `build_wheel`: build a wheel in the folder and return the basename
21
+ - `get_requires_for_build_wheel`: get the `setup_requires` to build
22
+ - `prepare_metadata_for_build_wheel`: get the `install_requires`
23
+ - `build_sdist`: build an sdist in the folder and return the basename
24
+ - `get_requires_for_build_sdist`: get the `setup_requires` to build
25
+
26
+ Again, this is not a formal definition! Just a "taste" of the module.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import contextlib
32
+ import io
33
+ import os
34
+ import shlex
35
+ import shutil
36
+ import sys
37
+ import tempfile
38
+ import tokenize
39
+ import warnings
40
+ from collections.abc import Iterable, Iterator, Mapping
41
+ from pathlib import Path
42
+ from typing import TYPE_CHECKING, NoReturn
43
+
44
+ import setuptools
45
+
46
+ from . import errors
47
+ from ._path import StrPath, same_path
48
+ from ._reqs import parse_strings
49
+ from .warnings import SetuptoolsDeprecationWarning
50
+
51
+ import distutils
52
+ from distutils.util import strtobool
53
+
54
+ if TYPE_CHECKING:
55
+ from typing import TypeAlias
56
+
57
+ __all__ = [
58
+ 'get_requires_for_build_sdist',
59
+ 'get_requires_for_build_wheel',
60
+ 'prepare_metadata_for_build_wheel',
61
+ 'build_wheel',
62
+ 'build_sdist',
63
+ 'get_requires_for_build_editable',
64
+ 'prepare_metadata_for_build_editable',
65
+ 'build_editable',
66
+ '__legacy__',
67
+ 'SetupRequirementsError',
68
+ ]
69
+
70
+
71
+ class SetupRequirementsError(BaseException):
72
+ def __init__(self, specifiers) -> None:
73
+ self.specifiers = specifiers
74
+
75
+
76
+ class Distribution(setuptools.dist.Distribution):
77
+ def fetch_build_eggs(self, specifiers) -> NoReturn:
78
+ specifier_list = list(parse_strings(specifiers))
79
+
80
+ raise SetupRequirementsError(specifier_list)
81
+
82
+ @classmethod
83
+ @contextlib.contextmanager
84
+ def patch(cls) -> Iterator[None]:
85
+ """
86
+ Replace
87
+ distutils.dist.Distribution with this class
88
+ for the duration of this context.
89
+ """
90
+ orig = distutils.core.Distribution
91
+ distutils.core.Distribution = cls # type: ignore[misc] # monkeypatching
92
+ try:
93
+ yield
94
+ finally:
95
+ distutils.core.Distribution = orig # type: ignore[misc] # monkeypatching
96
+
97
+
98
+ @contextlib.contextmanager
99
+ def no_install_setup_requires():
100
+ """Temporarily disable installing setup_requires
101
+
102
+ Under PEP 517, the backend reports build dependencies to the frontend,
103
+ and the frontend is responsible for ensuring they're installed.
104
+ So setuptools (acting as a backend) should not try to install them.
105
+ """
106
+ orig = setuptools._install_setup_requires
107
+ setuptools._install_setup_requires = lambda attrs: None
108
+ try:
109
+ yield
110
+ finally:
111
+ setuptools._install_setup_requires = orig
112
+
113
+
114
+ def _get_immediate_subdirectories(a_dir):
115
+ return [
116
+ name for name in os.listdir(a_dir) if os.path.isdir(os.path.join(a_dir, name))
117
+ ]
118
+
119
+
120
+ def _file_with_extension(directory: StrPath, extension: str | tuple[str, ...]):
121
+ matching = (f for f in os.listdir(directory) if f.endswith(extension))
122
+ try:
123
+ (file,) = matching
124
+ except ValueError:
125
+ raise ValueError(
126
+ 'No distribution was found. Ensure that `setup.py` '
127
+ 'is not empty and that it calls `setup()`.'
128
+ ) from None
129
+ return file
130
+
131
+
132
+ def _open_setup_script(setup_script):
133
+ if not os.path.exists(setup_script):
134
+ # Supply a default setup.py
135
+ return io.StringIO("from setuptools import setup; setup()")
136
+
137
+ return tokenize.open(setup_script)
138
+
139
+
140
+ @contextlib.contextmanager
141
+ def suppress_known_deprecation():
142
+ with warnings.catch_warnings():
143
+ warnings.filterwarnings('ignore', 'setup.py install is deprecated')
144
+ yield
145
+
146
+
147
+ _ConfigSettings: TypeAlias = Mapping[str, str | list[str] | None] | None
148
+ """
149
+ Currently the user can run::
150
+
151
+ pip install -e . --config-settings key=value
152
+ python -m build -C--key=value -C key=value
153
+
154
+ - pip will pass both key and value as strings and overwriting repeated keys
155
+ (pypa/pip#11059).
156
+ - build will accumulate values associated with repeated keys in a list.
157
+ It will also accept keys with no associated value.
158
+ This means that an option passed by build can be ``str | list[str] | None``.
159
+ - PEP 517 specifies that ``config_settings`` is an optional dict.
160
+ """
161
+
162
+
163
+ class _ConfigSettingsTranslator:
164
+ """Translate ``config_settings`` into distutils-style command arguments.
165
+ Only a limited number of options is currently supported.
166
+ """
167
+
168
+ # See pypa/setuptools#1928 pypa/setuptools#2491
169
+
170
+ def _get_config(self, key: str, config_settings: _ConfigSettings) -> list[str]:
171
+ """
172
+ Get the value of a specific key in ``config_settings`` as a list of strings.
173
+
174
+ >>> fn = _ConfigSettingsTranslator()._get_config
175
+ >>> fn("--global-option", None)
176
+ []
177
+ >>> fn("--global-option", {})
178
+ []
179
+ >>> fn("--global-option", {'--global-option': 'foo'})
180
+ ['foo']
181
+ >>> fn("--global-option", {'--global-option': ['foo']})
182
+ ['foo']
183
+ >>> fn("--global-option", {'--global-option': 'foo'})
184
+ ['foo']
185
+ >>> fn("--global-option", {'--global-option': 'foo bar'})
186
+ ['foo', 'bar']
187
+ """
188
+ cfg = config_settings or {}
189
+ opts = cfg.get(key) or []
190
+ return shlex.split(opts) if isinstance(opts, str) else opts
191
+
192
+ def _global_args(self, config_settings: _ConfigSettings) -> Iterator[str]:
193
+ """
194
+ Let the user specify ``verbose`` or ``quiet`` + escape hatch via
195
+ ``--global-option``.
196
+ Note: ``-v``, ``-vv``, ``-vvv`` have similar effects in setuptools,
197
+ so we just have to cover the basic scenario ``-v``.
198
+
199
+ >>> fn = _ConfigSettingsTranslator()._global_args
200
+ >>> list(fn(None))
201
+ []
202
+ >>> list(fn({"verbose": "False"}))
203
+ ['-q']
204
+ >>> list(fn({"verbose": "1"}))
205
+ ['-v']
206
+ >>> list(fn({"--verbose": None}))
207
+ ['-v']
208
+ >>> list(fn({"verbose": "true", "--global-option": "-q --no-user-cfg"}))
209
+ ['-v', '-q', '--no-user-cfg']
210
+ >>> list(fn({"--quiet": None}))
211
+ ['-q']
212
+ """
213
+ cfg = config_settings or {}
214
+ falsey = {"false", "no", "0", "off"}
215
+ if "verbose" in cfg or "--verbose" in cfg:
216
+ level = str(cfg.get("verbose") or cfg.get("--verbose") or "1")
217
+ yield ("-q" if level.lower() in falsey else "-v")
218
+ if "quiet" in cfg or "--quiet" in cfg:
219
+ level = str(cfg.get("quiet") or cfg.get("--quiet") or "1")
220
+ yield ("-v" if level.lower() in falsey else "-q")
221
+
222
+ yield from self._get_config("--global-option", config_settings)
223
+
224
+ def __dist_info_args(self, config_settings: _ConfigSettings) -> Iterator[str]:
225
+ """
226
+ The ``dist_info`` command accepts ``tag-date`` and ``tag-build``.
227
+
228
+ .. warning::
229
+ We cannot use this yet as it requires the ``sdist`` and ``bdist_wheel``
230
+ commands run in ``build_sdist`` and ``build_wheel`` to reuse the egg-info
231
+ directory created in ``prepare_metadata_for_build_wheel``.
232
+
233
+ >>> fn = _ConfigSettingsTranslator()._ConfigSettingsTranslator__dist_info_args
234
+ >>> list(fn(None))
235
+ []
236
+ >>> list(fn({"tag-date": "False"}))
237
+ ['--no-date']
238
+ >>> list(fn({"tag-date": None}))
239
+ ['--no-date']
240
+ >>> list(fn({"tag-date": "true", "tag-build": ".a"}))
241
+ ['--tag-date', '--tag-build', '.a']
242
+ """
243
+ cfg = config_settings or {}
244
+ if "tag-date" in cfg:
245
+ val = strtobool(str(cfg["tag-date"] or "false"))
246
+ yield ("--tag-date" if val else "--no-date")
247
+ if "tag-build" in cfg:
248
+ yield from ["--tag-build", str(cfg["tag-build"])]
249
+
250
+ def _editable_args(self, config_settings: _ConfigSettings) -> Iterator[str]:
251
+ """
252
+ The ``editable_wheel`` command accepts ``editable-mode=strict``.
253
+
254
+ >>> fn = _ConfigSettingsTranslator()._editable_args
255
+ >>> list(fn(None))
256
+ []
257
+ >>> list(fn({"editable-mode": "strict"}))
258
+ ['--mode', 'strict']
259
+ """
260
+ cfg = config_settings or {}
261
+ mode = cfg.get("editable-mode") or cfg.get("editable_mode")
262
+ if not mode:
263
+ return
264
+ yield from ["--mode", str(mode)]
265
+
266
+ def _arbitrary_args(self, config_settings: _ConfigSettings) -> Iterator[str]:
267
+ """
268
+ Users may expect to pass arbitrary lists of arguments to a command
269
+ via "--global-option" (example provided in PEP 517 of a "escape hatch").
270
+
271
+ >>> fn = _ConfigSettingsTranslator()._arbitrary_args
272
+ >>> list(fn(None))
273
+ []
274
+ >>> list(fn({}))
275
+ []
276
+ >>> list(fn({'--build-option': 'foo'}))
277
+ ['foo']
278
+ >>> list(fn({'--build-option': ['foo']}))
279
+ ['foo']
280
+ >>> list(fn({'--build-option': 'foo'}))
281
+ ['foo']
282
+ >>> list(fn({'--build-option': 'foo bar'}))
283
+ ['foo', 'bar']
284
+ >>> list(fn({'--global-option': 'foo'}))
285
+ []
286
+ """
287
+ yield from self._get_config("--build-option", config_settings)
288
+
289
+
290
+ class _BuildMetaBackend(_ConfigSettingsTranslator):
291
+ def _get_build_requires(
292
+ self, config_settings: _ConfigSettings, requirements: list[str]
293
+ ):
294
+ sys.argv = [
295
+ *sys.argv[:1],
296
+ *self._global_args(config_settings),
297
+ "egg_info",
298
+ ]
299
+ try:
300
+ with Distribution.patch():
301
+ self.run_setup()
302
+ except SetupRequirementsError as e:
303
+ requirements += e.specifiers
304
+
305
+ return requirements
306
+
307
+ def run_setup(self, setup_script: str = 'setup.py') -> None:
308
+ # Note that we can reuse our build directory between calls
309
+ # Correctness comes first, then optimization later
310
+ __file__ = os.path.abspath(setup_script)
311
+ __name__ = '__main__'
312
+
313
+ with _open_setup_script(__file__) as f:
314
+ code = f.read().replace(r'\r\n', r'\n')
315
+
316
+ try:
317
+ exec(code, locals())
318
+ except SystemExit as e:
319
+ if e.code:
320
+ raise
321
+ # We ignore exit code indicating success
322
+ SetuptoolsDeprecationWarning.emit(
323
+ "Running `setup.py` directly as CLI tool is deprecated.",
324
+ "Please avoid using `sys.exit(0)` or similar statements "
325
+ "that don't fit in the paradigm of a configuration file.",
326
+ see_url="https://blog.ganssle.io/articles/2021/10/"
327
+ "setup-py-deprecated.html",
328
+ )
329
+
330
+ def get_requires_for_build_wheel(
331
+ self, config_settings: _ConfigSettings = None
332
+ ) -> list[str]:
333
+ return self._get_build_requires(config_settings, requirements=[])
334
+
335
+ def get_requires_for_build_sdist(
336
+ self, config_settings: _ConfigSettings = None
337
+ ) -> list[str]:
338
+ return self._get_build_requires(config_settings, requirements=[])
339
+
340
+ def _bubble_up_info_directory(
341
+ self, metadata_directory: StrPath, suffix: str
342
+ ) -> str:
343
+ """
344
+ PEP 517 requires that the .dist-info directory be placed in the
345
+ metadata_directory. To comply, we MUST copy the directory to the root.
346
+
347
+ Returns the basename of the info directory, e.g. `proj-0.0.0.dist-info`.
348
+ """
349
+ info_dir = self._find_info_directory(metadata_directory, suffix)
350
+ if not same_path(info_dir.parent, metadata_directory):
351
+ shutil.move(str(info_dir), metadata_directory)
352
+ # PEP 517 allow other files and dirs to exist in metadata_directory
353
+ return info_dir.name
354
+
355
+ def _find_info_directory(self, metadata_directory: StrPath, suffix: str) -> Path:
356
+ for parent, dirs, _ in os.walk(metadata_directory):
357
+ candidates = [f for f in dirs if f.endswith(suffix)]
358
+
359
+ if len(candidates) != 0 or len(dirs) != 1:
360
+ assert len(candidates) == 1, (
361
+ f"Exactly one {suffix} should have been produced, but found {len(candidates)}: {candidates}"
362
+ )
363
+ return Path(parent, candidates[0])
364
+
365
+ msg = f"No {suffix} directory found in {metadata_directory}"
366
+ raise errors.InternalError(msg)
367
+
368
+ def prepare_metadata_for_build_wheel(
369
+ self, metadata_directory: StrPath, config_settings: _ConfigSettings = None
370
+ ) -> str:
371
+ sys.argv = [
372
+ *sys.argv[:1],
373
+ *self._global_args(config_settings),
374
+ "dist_info",
375
+ "--output-dir",
376
+ str(metadata_directory),
377
+ "--keep-egg-info",
378
+ ]
379
+ with no_install_setup_requires():
380
+ self.run_setup()
381
+
382
+ self._bubble_up_info_directory(metadata_directory, ".egg-info")
383
+ return self._bubble_up_info_directory(metadata_directory, ".dist-info")
384
+
385
+ def _build_with_temp_dir(
386
+ self,
387
+ setup_command: Iterable[str],
388
+ result_extension: str | tuple[str, ...],
389
+ result_directory: StrPath,
390
+ config_settings: _ConfigSettings,
391
+ arbitrary_args: Iterable[str] = (),
392
+ ):
393
+ result_directory = os.path.abspath(result_directory)
394
+
395
+ # Build in a temporary directory, then copy to the target.
396
+ os.makedirs(result_directory, exist_ok=True)
397
+
398
+ with tempfile.TemporaryDirectory(
399
+ prefix=".tmp-", dir=result_directory
400
+ ) as tmp_dist_dir:
401
+ sys.argv = [
402
+ *sys.argv[:1],
403
+ *self._global_args(config_settings),
404
+ *setup_command,
405
+ "--dist-dir",
406
+ tmp_dist_dir,
407
+ *arbitrary_args,
408
+ ]
409
+ with no_install_setup_requires():
410
+ self.run_setup()
411
+
412
+ result_basename = _file_with_extension(tmp_dist_dir, result_extension)
413
+ result_path = os.path.join(result_directory, result_basename)
414
+ if os.path.exists(result_path):
415
+ # os.rename will fail overwriting on non-Unix.
416
+ os.remove(result_path)
417
+ os.rename(os.path.join(tmp_dist_dir, result_basename), result_path)
418
+
419
+ return result_basename
420
+
421
+ def build_wheel(
422
+ self,
423
+ wheel_directory: StrPath,
424
+ config_settings: _ConfigSettings = None,
425
+ metadata_directory: StrPath | None = None,
426
+ ) -> str:
427
+ def _build(cmd: list[str]):
428
+ with suppress_known_deprecation():
429
+ return self._build_with_temp_dir(
430
+ cmd,
431
+ '.whl',
432
+ wheel_directory,
433
+ config_settings,
434
+ self._arbitrary_args(config_settings),
435
+ )
436
+
437
+ if metadata_directory is None:
438
+ return _build(['bdist_wheel'])
439
+
440
+ try:
441
+ return _build(['bdist_wheel', '--dist-info-dir', str(metadata_directory)])
442
+ except SystemExit as ex: # pragma: nocover
443
+ # pypa/setuptools#4683
444
+ if "--dist-info-dir not recognized" not in str(ex):
445
+ raise
446
+ _IncompatibleBdistWheel.emit()
447
+ return _build(['bdist_wheel'])
448
+
449
+ def build_sdist(
450
+ self, sdist_directory: StrPath, config_settings: _ConfigSettings = None
451
+ ) -> str:
452
+ return self._build_with_temp_dir(
453
+ ['sdist', '--formats', 'gztar'], '.tar.gz', sdist_directory, config_settings
454
+ )
455
+
456
+ def _get_dist_info_dir(self, metadata_directory: StrPath | None) -> str | None:
457
+ if not metadata_directory:
458
+ return None
459
+ dist_info_candidates = list(Path(metadata_directory).glob("*.dist-info"))
460
+ assert len(dist_info_candidates) <= 1
461
+ return str(dist_info_candidates[0]) if dist_info_candidates else None
462
+
463
+ def build_editable(
464
+ self,
465
+ wheel_directory: StrPath,
466
+ config_settings: _ConfigSettings = None,
467
+ metadata_directory: StrPath | None = None,
468
+ ) -> str:
469
+ # XXX can or should we hide our editable_wheel command normally?
470
+ info_dir = self._get_dist_info_dir(metadata_directory)
471
+ opts = ["--dist-info-dir", info_dir] if info_dir else []
472
+ cmd = ["editable_wheel", *opts, *self._editable_args(config_settings)]
473
+ with suppress_known_deprecation():
474
+ return self._build_with_temp_dir(
475
+ cmd, ".whl", wheel_directory, config_settings
476
+ )
477
+
478
+ def get_requires_for_build_editable(
479
+ self, config_settings: _ConfigSettings = None
480
+ ) -> list[str]:
481
+ return self.get_requires_for_build_wheel(config_settings)
482
+
483
+ def prepare_metadata_for_build_editable(
484
+ self, metadata_directory: StrPath, config_settings: _ConfigSettings = None
485
+ ) -> str:
486
+ return self.prepare_metadata_for_build_wheel(
487
+ metadata_directory, config_settings
488
+ )
489
+
490
+
491
+ class _BuildMetaLegacyBackend(_BuildMetaBackend):
492
+ """Compatibility backend for setuptools
493
+
494
+ This is a version of setuptools.build_meta that endeavors
495
+ to maintain backwards
496
+ compatibility with pre-PEP 517 modes of invocation. It
497
+ exists as a temporary
498
+ bridge between the old packaging mechanism and the new
499
+ packaging mechanism,
500
+ and will eventually be removed.
501
+ """
502
+
503
+ def run_setup(self, setup_script: str = 'setup.py') -> None:
504
+ # In order to maintain compatibility with scripts assuming that
505
+ # the setup.py script is in a directory on the PYTHONPATH, inject
506
+ # '' into sys.path. (pypa/setuptools#1642)
507
+ sys_path = list(sys.path) # Save the original path
508
+
509
+ script_dir = os.path.dirname(os.path.abspath(setup_script))
510
+ if script_dir not in sys.path:
511
+ sys.path.insert(0, script_dir)
512
+
513
+ # Some setup.py scripts (e.g. in pygame and numpy) use sys.argv[0] to
514
+ # get the directory of the source code. They expect it to refer to the
515
+ # setup.py script.
516
+ sys_argv_0 = sys.argv[0]
517
+ sys.argv[0] = setup_script
518
+
519
+ try:
520
+ super().run_setup(setup_script=setup_script)
521
+ finally:
522
+ # While PEP 517 frontends should be calling each hook in a fresh
523
+ # subprocess according to the standard (and thus it should not be
524
+ # strictly necessary to restore the old sys.path), we'll restore
525
+ # the original path so that the path manipulation does not persist
526
+ # within the hook after run_setup is called.
527
+ sys.path[:] = sys_path
528
+ sys.argv[0] = sys_argv_0
529
+
530
+
531
+ class _IncompatibleBdistWheel(SetuptoolsDeprecationWarning):
532
+ _SUMMARY = "wheel.bdist_wheel is deprecated, please import it from setuptools"
533
+ _DETAILS = """
534
+ Ensure that any custom bdist_wheel implementation is a subclass of
535
+ setuptools.command.bdist_wheel.bdist_wheel.
536
+ """
537
+ _DUE_DATE = (2025, 10, 15)
538
+ # Initially introduced in 2024/10/15, but maybe too disruptive to be enforced?
539
+ _SEE_URL = "https://github.com/pypa/wheel/pull/631"
540
+
541
+
542
+ # The primary backend
543
+ _BACKEND = _BuildMetaBackend()
544
+
545
+ get_requires_for_build_wheel = _BACKEND.get_requires_for_build_wheel
546
+ get_requires_for_build_sdist = _BACKEND.get_requires_for_build_sdist
547
+ prepare_metadata_for_build_wheel = _BACKEND.prepare_metadata_for_build_wheel
548
+ build_wheel = _BACKEND.build_wheel
549
+ build_sdist = _BACKEND.build_sdist
550
+ get_requires_for_build_editable = _BACKEND.get_requires_for_build_editable
551
+ prepare_metadata_for_build_editable = _BACKEND.prepare_metadata_for_build_editable
552
+ build_editable = _BACKEND.build_editable
553
+
554
+
555
+ # The legacy backend
556
+ __legacy__ = _BuildMetaLegacyBackend()
data/diffusion/.venv/lib/python3.11/site-packages/setuptools/cli.exe ADDED
Binary file (11.8 kB). View file
 
data/diffusion/.venv/lib/python3.11/site-packages/setuptools/dist.py ADDED
@@ -0,0 +1,1124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import functools
4
+ import io
5
+ import itertools
6
+ import numbers
7
+ import os
8
+ import re
9
+ import sys
10
+ from collections.abc import Iterable, Iterator, MutableMapping, Sequence
11
+ from glob import glob
12
+ from pathlib import Path
13
+ from typing import TYPE_CHECKING, Any
14
+
15
+ from more_itertools import partition, unique_everseen
16
+ from packaging.markers import InvalidMarker, Marker
17
+ from packaging.specifiers import InvalidSpecifier, SpecifierSet
18
+ from packaging.version import Version
19
+
20
+ from . import (
21
+ _entry_points,
22
+ _reqs,
23
+ _static,
24
+ command as _, # noqa: F401 # imported for side-effects
25
+ )
26
+ from ._importlib import metadata
27
+ from ._normalization import _canonicalize_license_expression
28
+ from ._path import StrPath
29
+ from ._reqs import _StrOrIter
30
+ from .config import pyprojecttoml, setupcfg
31
+ from .discovery import ConfigDiscovery
32
+ from .errors import InvalidConfigError
33
+ from .monkey import get_unpatched
34
+ from .warnings import InformationOnly, SetuptoolsDeprecationWarning
35
+
36
+ import distutils.cmd
37
+ import distutils.command
38
+ import distutils.core
39
+ import distutils.dist
40
+ import distutils.log
41
+ from distutils.debug import DEBUG
42
+ from distutils.errors import DistutilsOptionError, DistutilsSetupError
43
+ from distutils.fancy_getopt import translate_longopt
44
+ from distutils.util import strtobool
45
+
46
+ if TYPE_CHECKING:
47
+ from typing import TypeAlias
48
+
49
+
50
+ __all__ = ['Distribution']
51
+
52
+ _sequence = tuple, list
53
+ """
54
+ :meta private:
55
+
56
+ Supported iterable types that are known to be:
57
+ - ordered (which `set` isn't)
58
+ - not match a str (which `Sequence[str]` does)
59
+ - not imply a nested type (like `dict`)
60
+ for use with `isinstance`.
61
+ """
62
+ _Sequence: TypeAlias = tuple[str, ...] | list[str]
63
+ # This is how stringifying _Sequence would look in Python 3.10
64
+ _sequence_type_repr = "tuple[str, ...] | list[str]"
65
+ _OrderedStrSequence: TypeAlias = str | dict[str, Any] | Sequence[str]
66
+ """
67
+ :meta private:
68
+ Avoid single-use iterable. Disallow sets.
69
+ A poor approximation of an OrderedSequence (dict doesn't match a Sequence).
70
+ """
71
+
72
+
73
+ def __getattr__(name: str) -> Any: # pragma: no cover
74
+ if name == "sequence":
75
+ SetuptoolsDeprecationWarning.emit(
76
+ "`setuptools.dist.sequence` is an internal implementation detail.",
77
+ "Please define your own `sequence = tuple, list` instead.",
78
+ due_date=(2025, 8, 28), # Originally added on 2024-08-27
79
+ )
80
+ return _sequence
81
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
82
+
83
+
84
+ def check_importable(dist, attr, value):
85
+ try:
86
+ ep = metadata.EntryPoint(value=value, name=None, group=None)
87
+ assert not ep.extras
88
+ except (TypeError, ValueError, AttributeError, AssertionError) as e:
89
+ raise DistutilsSetupError(
90
+ f"{attr!r} must be importable 'module:attrs' string (got {value!r})"
91
+ ) from e
92
+
93
+
94
+ def assert_string_list(dist, attr: str, value: _Sequence) -> None:
95
+ """Verify that value is a string list"""
96
+ try:
97
+ # verify that value is a list or tuple to exclude unordered
98
+ # or single-use iterables
99
+ assert isinstance(value, _sequence)
100
+ # verify that elements of value are strings
101
+ assert ''.join(value) != value
102
+ except (TypeError, ValueError, AttributeError, AssertionError) as e:
103
+ raise DistutilsSetupError(
104
+ f"{attr!r} must be of type <{_sequence_type_repr}> (got {value!r})"
105
+ ) from e
106
+
107
+
108
+ def check_nsp(dist, attr, value):
109
+ """Verify that namespace packages are valid"""
110
+ ns_packages = value
111
+ assert_string_list(dist, attr, ns_packages)
112
+ for nsp in ns_packages:
113
+ if not dist.has_contents_for(nsp):
114
+ raise DistutilsSetupError(
115
+ f"Distribution contains no modules or packages for namespace package {nsp!r}"
116
+ )
117
+ parent, _sep, _child = nsp.rpartition('.')
118
+ if parent and parent not in ns_packages:
119
+ distutils.log.warn(
120
+ "WARNING: %r is declared as a package namespace, but %r"
121
+ " is not: please correct this in setup.py",
122
+ nsp,
123
+ parent,
124
+ )
125
+ SetuptoolsDeprecationWarning.emit(
126
+ "The namespace_packages parameter is deprecated.",
127
+ "Please replace its usage with implicit namespaces (PEP 420).",
128
+ see_docs="references/keywords.html#keyword-namespace-packages",
129
+ # TODO: define due_date, it may break old packages that are no longer
130
+ # maintained (e.g. sphinxcontrib extensions) when installed from source.
131
+ # Warning officially introduced in May 2022, however the deprecation
132
+ # was mentioned much earlier in the docs (May 2020, see #2149).
133
+ )
134
+
135
+
136
+ def check_extras(dist, attr, value):
137
+ """Verify that extras_require mapping is valid"""
138
+ try:
139
+ list(itertools.starmap(_check_extra, value.items()))
140
+ except (TypeError, ValueError, AttributeError) as e:
141
+ raise DistutilsSetupError(
142
+ "'extras_require' must be a dictionary whose values are "
143
+ "strings or lists of strings containing valid project/version "
144
+ "requirement specifiers."
145
+ ) from e
146
+
147
+
148
+ def _check_extra(extra, reqs):
149
+ _name, _sep, marker = extra.partition(':')
150
+ try:
151
+ _check_marker(marker)
152
+ except InvalidMarker:
153
+ msg = f"Invalid environment marker: {marker} ({extra!r})"
154
+ raise DistutilsSetupError(msg) from None
155
+ list(_reqs.parse(reqs))
156
+
157
+
158
+ def _check_marker(marker):
159
+ if not marker:
160
+ return
161
+ m = Marker(marker)
162
+ m.evaluate()
163
+
164
+
165
+ def assert_bool(dist, attr, value):
166
+ """Verify that value is True, False, 0, or 1"""
167
+ if bool(value) != value:
168
+ raise DistutilsSetupError(f"{attr!r} must be a boolean value (got {value!r})")
169
+
170
+
171
+ def invalid_unless_false(dist, attr, value):
172
+ if not value:
173
+ DistDeprecationWarning.emit(f"{attr} is ignored.")
174
+ # TODO: should there be a `due_date` here?
175
+ return
176
+ raise DistutilsSetupError(f"{attr} is invalid.")
177
+
178
+
179
+ def check_requirements(dist, attr: str, value: _OrderedStrSequence) -> None:
180
+ """Verify that install_requires is a valid requirements list"""
181
+ try:
182
+ list(_reqs.parse(value))
183
+ if isinstance(value, set):
184
+ raise TypeError("Unordered types are not allowed")
185
+ except (TypeError, ValueError) as error:
186
+ msg = (
187
+ f"{attr!r} must be a string or iterable of strings "
188
+ f"containing valid project/version requirement specifiers; {error}"
189
+ )
190
+ raise DistutilsSetupError(msg) from error
191
+
192
+
193
+ def check_specifier(dist, attr, value):
194
+ """Verify that value is a valid version specifier"""
195
+ try:
196
+ SpecifierSet(value)
197
+ except (InvalidSpecifier, AttributeError) as error:
198
+ msg = f"{attr!r} must be a string containing valid version specifiers; {error}"
199
+ raise DistutilsSetupError(msg) from error
200
+
201
+
202
+ def check_entry_points(dist, attr, value):
203
+ """Verify that entry_points map is parseable"""
204
+ try:
205
+ _entry_points.load(value)
206
+ except Exception as e:
207
+ raise DistutilsSetupError(e) from e
208
+
209
+
210
+ def check_package_data(dist, attr, value):
211
+ """Verify that value is a dictionary of package names to glob lists"""
212
+ if not isinstance(value, dict):
213
+ raise DistutilsSetupError(
214
+ f"{attr!r} must be a dictionary mapping package names to lists of "
215
+ "string wildcard patterns"
216
+ )
217
+ for k, v in value.items():
218
+ if not isinstance(k, str):
219
+ raise DistutilsSetupError(
220
+ f"keys of {attr!r} dict must be strings (got {k!r})"
221
+ )
222
+ assert_string_list(dist, f'values of {attr!r} dict', v)
223
+
224
+
225
+ def check_packages(dist, attr, value):
226
+ for pkgname in value:
227
+ if not re.match(r'\w+(\.\w+)*', pkgname):
228
+ distutils.log.warn(
229
+ "WARNING: %r not a valid package name; please use only "
230
+ ".-separated package names in setup.py",
231
+ pkgname,
232
+ )
233
+
234
+
235
+ if TYPE_CHECKING:
236
+ # Work around a mypy issue where type[T] can't be used as a base: https://github.com/python/mypy/issues/10962
237
+ from distutils.core import Distribution as _Distribution
238
+ else:
239
+ _Distribution = get_unpatched(distutils.core.Distribution)
240
+
241
+
242
+ class Distribution(_Distribution):
243
+ """Distribution with support for tests and package data
244
+
245
+ This is an enhanced version of 'distutils.dist.Distribution' that
246
+ effectively adds the following new optional keyword arguments to 'setup()':
247
+
248
+ 'install_requires' -- a string or sequence of strings specifying project
249
+ versions that the distribution requires when installed, in the format
250
+ used by 'pkg_resources.require()'. They will be installed
251
+ automatically when the package is installed. If you wish to use
252
+ packages that are not available in PyPI, or want to give your users an
253
+ alternate download location, you can add a 'find_links' option to the
254
+ '[easy_install]' section of your project's 'setup.cfg' file, and then
255
+ setuptools will scan the listed web pages for links that satisfy the
256
+ requirements.
257
+
258
+ 'extras_require' -- a dictionary mapping names of optional "extras" to the
259
+ additional requirement(s) that using those extras incurs. For example,
260
+ this::
261
+
262
+ extras_require = dict(reST = ["docutils>=0.3", "reSTedit"])
263
+
264
+ indicates that the distribution can optionally provide an extra
265
+ capability called "reST", but it can only be used if docutils and
266
+ reSTedit are installed. If the user installs your package using
267
+ EasyInstall and requests one of your extras, the corresponding
268
+ additional requirements will be installed if needed.
269
+
270
+ 'package_data' -- a dictionary mapping package names to lists of filenames
271
+ or globs to use to find data files contained in the named packages.
272
+ If the dictionary has filenames or globs listed under '""' (the empty
273
+ string), those names will be searched for in every package, in addition
274
+ to any names for the specific package. Data files found using these
275
+ names/globs will be installed along with the package, in the same
276
+ location as the package. Note that globs are allowed to reference
277
+ the contents of non-package subdirectories, as long as you use '/' as
278
+ a path separator. (Globs are automatically converted to
279
+ platform-specific paths at runtime.)
280
+
281
+ In addition to these new keywords, this class also has several new methods
282
+ for manipulating the distribution's contents. For example, the 'include()'
283
+ and 'exclude()' methods can be thought of as in-place add and subtract
284
+ commands that add or remove packages, modules, extensions, and so on from
285
+ the distribution.
286
+ """
287
+
288
+ _DISTUTILS_UNSUPPORTED_METADATA = {
289
+ 'long_description_content_type': lambda: None,
290
+ 'project_urls': dict,
291
+ 'provides_extras': dict, # behaves like an ordered set
292
+ 'license_expression': lambda: None,
293
+ 'license_file': lambda: None,
294
+ 'license_files': lambda: None,
295
+ 'install_requires': list,
296
+ 'extras_require': dict,
297
+ }
298
+
299
+ # Used by build_py, editable_wheel and install_lib commands for legacy namespaces
300
+ namespace_packages: list[str] #: :meta private: DEPRECATED
301
+
302
+ # Any: Dynamic assignment results in Incompatible types in assignment
303
+ def __init__(self, attrs: MutableMapping[str, Any] | None = None) -> None:
304
+ have_package_data = hasattr(self, "package_data")
305
+ if not have_package_data:
306
+ self.package_data: dict[str, list[str]] = {}
307
+ attrs = attrs or {}
308
+ self.dist_files: list[tuple[str, str, str]] = []
309
+ self.include_package_data: bool | None = None
310
+ self.exclude_package_data: dict[str, list[str]] | None = None
311
+ # Filter-out setuptools' specific options.
312
+ self.src_root: str | None = attrs.pop("src_root", None)
313
+ self.dependency_links: list[str] = attrs.pop('dependency_links', [])
314
+ self.setup_requires: list[str] = attrs.pop('setup_requires', [])
315
+ for ep in metadata.entry_points(group='distutils.setup_keywords'):
316
+ vars(self).setdefault(ep.name, None)
317
+
318
+ metadata_only = set(self._DISTUTILS_UNSUPPORTED_METADATA)
319
+ metadata_only -= {"install_requires", "extras_require"}
320
+ dist_attrs = {k: v for k, v in attrs.items() if k not in metadata_only}
321
+ _Distribution.__init__(self, dist_attrs)
322
+
323
+ # Private API (setuptools-use only, not restricted to Distribution)
324
+ # Stores files that are referenced by the configuration and need to be in the
325
+ # sdist (e.g. `version = file: VERSION.txt`)
326
+ self._referenced_files = set[str]()
327
+
328
+ self.set_defaults = ConfigDiscovery(self)
329
+
330
+ self._set_metadata_defaults(attrs)
331
+
332
+ self.metadata.version = self._normalize_version(self.metadata.version)
333
+ self._finalize_requires()
334
+
335
+ def _validate_metadata(self):
336
+ required = {"name"}
337
+ provided = {
338
+ key
339
+ for key in vars(self.metadata)
340
+ if getattr(self.metadata, key, None) is not None
341
+ }
342
+ missing = required - provided
343
+
344
+ if missing:
345
+ msg = f"Required package metadata is missing: {missing}"
346
+ raise DistutilsSetupError(msg)
347
+
348
+ def _set_metadata_defaults(self, attrs):
349
+ """
350
+ Fill-in missing metadata fields not supported by distutils.
351
+ Some fields may have been set by other tools (e.g. pbr).
352
+ Those fields (vars(self.metadata)) take precedence to
353
+ supplied attrs.
354
+ """
355
+ for option, default in self._DISTUTILS_UNSUPPORTED_METADATA.items():
356
+ vars(self.metadata).setdefault(option, attrs.get(option, default()))
357
+
358
+ @staticmethod
359
+ def _normalize_version(version):
360
+ from . import sic
361
+
362
+ if isinstance(version, numbers.Number):
363
+ # Some people apparently take "version number" too literally :)
364
+ version = str(version)
365
+ elif isinstance(version, sic) or version is None:
366
+ return version
367
+
368
+ normalized = str(Version(version))
369
+ if version != normalized:
370
+ InformationOnly.emit(f"Normalizing '{version}' to '{normalized}'")
371
+ return normalized
372
+ return version
373
+
374
+ def _finalize_requires(self):
375
+ """
376
+ Set `metadata.python_requires` and fix environment markers
377
+ in `install_requires` and `extras_require`.
378
+ """
379
+ if getattr(self, 'python_requires', None):
380
+ self.metadata.python_requires = self.python_requires
381
+
382
+ self._normalize_requires()
383
+ self.metadata.install_requires = self.install_requires
384
+ self.metadata.extras_require = self.extras_require
385
+
386
+ if self.extras_require:
387
+ for extra in self.extras_require.keys():
388
+ # Setuptools allows a weird "<name>:<env markers> syntax for extras
389
+ extra = extra.split(':')[0]
390
+ if extra:
391
+ self.metadata.provides_extras.setdefault(extra)
392
+
393
+ def _normalize_requires(self):
394
+ """Make sure requirement-related attributes exist and are normalized"""
395
+ install_requires = getattr(self, "install_requires", None) or []
396
+ extras_require = getattr(self, "extras_require", None) or {}
397
+
398
+ # Preserve the "static"-ness of values parsed from config files
399
+ list_ = _static.List if _static.is_static(install_requires) else list
400
+ self.install_requires = list_(map(str, _reqs.parse(install_requires)))
401
+
402
+ dict_ = _static.Dict if _static.is_static(extras_require) else dict
403
+ self.extras_require = dict_(
404
+ (k, list(map(str, _reqs.parse(v or [])))) for k, v in extras_require.items()
405
+ )
406
+
407
+ def _finalize_license_expression(self) -> None:
408
+ """
409
+ Normalize license and license_expression.
410
+ >>> dist = Distribution({"license_expression": _static.Str("mit aNd gpl-3.0-OR-later")})
411
+ >>> _static.is_static(dist.metadata.license_expression)
412
+ True
413
+ >>> dist._finalize_license_expression()
414
+ >>> _static.is_static(dist.metadata.license_expression) # preserve "static-ness"
415
+ True
416
+ >>> print(dist.metadata.license_expression)
417
+ MIT AND GPL-3.0-or-later
418
+ """
419
+ classifiers = self.metadata.get_classifiers()
420
+ license_classifiers = [cl for cl in classifiers if cl.startswith("License :: ")]
421
+
422
+ license_expr = self.metadata.license_expression
423
+ if license_expr:
424
+ str_ = _static.Str if _static.is_static(license_expr) else str
425
+ normalized = str_(_canonicalize_license_expression(license_expr))
426
+ if license_expr != normalized:
427
+ InformationOnly.emit(f"Normalizing '{license_expr}' to '{normalized}'")
428
+ self.metadata.license_expression = normalized
429
+ if license_classifiers:
430
+ raise InvalidConfigError(
431
+ "License classifiers have been superseded by license expressions "
432
+ "(see https://peps.python.org/pep-0639/). Please remove:\n\n"
433
+ + "\n".join(license_classifiers),
434
+ )
435
+ elif license_classifiers:
436
+ pypa_guides = "guides/writing-pyproject-toml/#license"
437
+ SetuptoolsDeprecationWarning.emit(
438
+ "License classifiers are deprecated.",
439
+ "Please consider removing the following classifiers in favor of a "
440
+ "SPDX license expression:\n\n" + "\n".join(license_classifiers),
441
+ see_url=f"https://packaging.python.org/en/latest/{pypa_guides}",
442
+ # Warning introduced on 2025-02-17
443
+ # TODO: Should we add a due date? It may affect old/unmaintained
444
+ # packages in the ecosystem and cause problems...
445
+ )
446
+
447
+ def _finalize_license_files(self) -> None:
448
+ """Compute names of all license files which should be included."""
449
+ license_files: list[str] | None = self.metadata.license_files
450
+ patterns = license_files or []
451
+
452
+ license_file: str | None = self.metadata.license_file
453
+ if license_file and license_file not in patterns:
454
+ patterns.append(license_file)
455
+
456
+ if license_files is None and license_file is None:
457
+ # Default patterns match the ones wheel uses
458
+ # See https://wheel.readthedocs.io/en/stable/user_guide.html
459
+ # -> 'Including license files in the generated wheel file'
460
+ patterns = ['LICEN[CS]E*', 'COPYING*', 'NOTICE*', 'AUTHORS*']
461
+ files = self._expand_patterns(patterns, enforce_match=False)
462
+ else: # Patterns explicitly given by the user
463
+ files = self._expand_patterns(patterns, enforce_match=True)
464
+
465
+ self.metadata.license_files = list(unique_everseen(files))
466
+
467
+ @classmethod
468
+ def _expand_patterns(
469
+ cls, patterns: list[str], enforce_match: bool = True
470
+ ) -> Iterator[str]:
471
+ """
472
+ >>> getfixture('sample_project_cwd')
473
+ >>> list(Distribution._expand_patterns(['LICENSE.txt']))
474
+ ['LICENSE.txt']
475
+ >>> list(Distribution._expand_patterns(['pyproject.toml', 'LIC*']))
476
+ ['pyproject.toml', 'LICENSE.txt']
477
+ >>> list(Distribution._expand_patterns(['src/**/*.dat']))
478
+ ['src/sample/package_data.dat']
479
+ """
480
+ return (
481
+ path.replace(os.sep, "/")
482
+ for pattern in patterns
483
+ for path in sorted(cls._find_pattern(pattern, enforce_match))
484
+ if not path.endswith('~') and os.path.isfile(path)
485
+ )
486
+
487
+ @staticmethod
488
+ def _find_pattern(pattern: str, enforce_match: bool = True) -> list[str]:
489
+ r"""
490
+ >>> getfixture('sample_project_cwd')
491
+ >>> Distribution._find_pattern("LICENSE.txt")
492
+ ['LICENSE.txt']
493
+ >>> Distribution._find_pattern("/LICENSE.MIT")
494
+ Traceback (most recent call last):
495
+ ...
496
+ setuptools.errors.InvalidConfigError: Pattern '/LICENSE.MIT' should be relative...
497
+ >>> Distribution._find_pattern("../LICENSE.MIT")
498
+ Traceback (most recent call last):
499
+ ...
500
+ setuptools.warnings.SetuptoolsDeprecationWarning: ...Pattern '../LICENSE.MIT' cannot contain '..'...
501
+ >>> Distribution._find_pattern("LICEN{CSE*")
502
+ Traceback (most recent call last):
503
+ ...
504
+ setuptools.warnings.SetuptoolsDeprecationWarning: ...Pattern 'LICEN{CSE*' contains invalid characters...
505
+ """
506
+ pypa_guides = "specifications/glob-patterns/"
507
+ if ".." in pattern:
508
+ SetuptoolsDeprecationWarning.emit(
509
+ f"Pattern {pattern!r} cannot contain '..'",
510
+ """
511
+ Please ensure the files specified are contained by the root
512
+ of the Python package (normally marked by `pyproject.toml`).
513
+ """,
514
+ see_url=f"https://packaging.python.org/en/latest/{pypa_guides}",
515
+ due_date=(2027, 2, 18), # Introduced in 2025-03-20
516
+ # Replace with InvalidConfigError after deprecation
517
+ )
518
+ if pattern.startswith((os.sep, "/")) or ":\\" in pattern:
519
+ raise InvalidConfigError(
520
+ f"Pattern {pattern!r} should be relative and must not start with '/'"
521
+ )
522
+ if re.match(r'^[\w\-\.\/\*\?\[\]]+$', pattern) is None:
523
+ SetuptoolsDeprecationWarning.emit(
524
+ "Please provide a valid glob pattern.",
525
+ "Pattern {pattern!r} contains invalid characters.",
526
+ pattern=pattern,
527
+ see_url=f"https://packaging.python.org/en/latest/{pypa_guides}",
528
+ due_date=(2027, 2, 18), # Introduced in 2025-02-20
529
+ )
530
+
531
+ found = glob(pattern, recursive=True)
532
+
533
+ if enforce_match and not found:
534
+ SetuptoolsDeprecationWarning.emit(
535
+ "Cannot find any files for the given pattern.",
536
+ "Pattern {pattern!r} did not match any files.",
537
+ pattern=pattern,
538
+ due_date=(2027, 2, 18), # Introduced in 2025-02-20
539
+ # PEP 639 requires us to error, but as a transition period
540
+ # we will only issue a warning to give people time to prepare.
541
+ # After the transition, this should raise an InvalidConfigError.
542
+ )
543
+ return found
544
+
545
+ # FIXME: 'Distribution._parse_config_files' is too complex (14)
546
+ def _parse_config_files(self, filenames=None): # noqa: C901
547
+ """
548
+ Adapted from distutils.dist.Distribution.parse_config_files,
549
+ this method provides the same functionality in subtly-improved
550
+ ways.
551
+ """
552
+ from configparser import ConfigParser
553
+
554
+ # Ignore install directory options if we have a venv
555
+ ignore_options = (
556
+ []
557
+ if sys.prefix == sys.base_prefix
558
+ else [
559
+ 'install-base',
560
+ 'install-platbase',
561
+ 'install-lib',
562
+ 'install-platlib',
563
+ 'install-purelib',
564
+ 'install-headers',
565
+ 'install-scripts',
566
+ 'install-data',
567
+ 'prefix',
568
+ 'exec-prefix',
569
+ 'home',
570
+ 'user',
571
+ 'root',
572
+ ]
573
+ )
574
+
575
+ ignore_options = frozenset(ignore_options)
576
+
577
+ if filenames is None:
578
+ filenames = self.find_config_files()
579
+
580
+ if DEBUG:
581
+ self.announce("Distribution.parse_config_files():")
582
+
583
+ parser = ConfigParser()
584
+ parser.optionxform = str
585
+ for filename in filenames:
586
+ with open(filename, encoding='utf-8') as reader:
587
+ if DEBUG:
588
+ self.announce(" reading {filename}".format(**locals()))
589
+ parser.read_file(reader)
590
+ for section in parser.sections():
591
+ options = parser.options(section)
592
+ opt_dict = self.get_option_dict(section)
593
+
594
+ for opt in options:
595
+ if opt == '__name__' or opt in ignore_options:
596
+ continue
597
+
598
+ val = parser.get(section, opt)
599
+ opt = self._enforce_underscore(opt, section)
600
+ opt = self._enforce_option_lowercase(opt, section)
601
+ opt_dict[opt] = (filename, val)
602
+
603
+ # Make the ConfigParser forget everything (so we retain
604
+ # the original filenames that options come from)
605
+ parser.__init__()
606
+
607
+ if 'global' not in self.command_options:
608
+ return
609
+
610
+ # If there was a "global" section in the config file, use it
611
+ # to set Distribution options.
612
+
613
+ for opt, (src, val) in self.command_options['global'].items():
614
+ alias = self.negative_opt.get(opt)
615
+ if alias:
616
+ val = not strtobool(val)
617
+ elif opt == 'verbose':
618
+ val = strtobool(val)
619
+
620
+ try:
621
+ setattr(self, alias or opt, val)
622
+ except ValueError as e:
623
+ raise DistutilsOptionError(e) from e
624
+
625
+ def _enforce_underscore(self, opt: str, section: str) -> str:
626
+ if "-" not in opt or self._skip_setupcfg_normalization(section):
627
+ return opt
628
+
629
+ underscore_opt = opt.replace('-', '_')
630
+ affected = f"(Affected: {self.metadata.name})." if self.metadata.name else ""
631
+ SetuptoolsDeprecationWarning.emit(
632
+ f"Invalid dash-separated key {opt!r} in {section!r} (setup.cfg), "
633
+ f"please use the underscore name {underscore_opt!r} instead.",
634
+ f"""
635
+ Usage of dash-separated {opt!r} will not be supported in future
636
+ versions. Please use the underscore name {underscore_opt!r} instead.
637
+ {affected}
638
+
639
+ Available configuration options are listed in:
640
+ https://setuptools.pypa.io/en/latest/userguide/declarative_config.html
641
+ """,
642
+ see_url="https://github.com/pypa/setuptools/discussions/5011",
643
+ due_date=(2026, 3, 3),
644
+ # Warning initially introduced in 3 Mar 2021
645
+ )
646
+ return underscore_opt
647
+
648
+ def _enforce_option_lowercase(self, opt: str, section: str) -> str:
649
+ if opt.islower() or self._skip_setupcfg_normalization(section):
650
+ return opt
651
+
652
+ lowercase_opt = opt.lower()
653
+ affected = f"(Affected: {self.metadata.name})." if self.metadata.name else ""
654
+ SetuptoolsDeprecationWarning.emit(
655
+ f"Invalid uppercase key {opt!r} in {section!r} (setup.cfg), "
656
+ f"please use lowercase {lowercase_opt!r} instead.",
657
+ f"""
658
+ Usage of uppercase key {opt!r} in {section!r} will not be supported in
659
+ future versions. Please use lowercase {lowercase_opt!r} instead.
660
+ {affected}
661
+
662
+ Available configuration options are listed in:
663
+ https://setuptools.pypa.io/en/latest/userguide/declarative_config.html
664
+ """,
665
+ see_url="https://github.com/pypa/setuptools/discussions/5011",
666
+ due_date=(2026, 3, 3),
667
+ # Warning initially introduced in 6 Mar 2021
668
+ )
669
+ return lowercase_opt
670
+
671
+ def _skip_setupcfg_normalization(self, section: str) -> bool:
672
+ skip = (
673
+ 'options.extras_require',
674
+ 'options.data_files',
675
+ 'options.entry_points',
676
+ 'options.package_data',
677
+ 'options.exclude_package_data',
678
+ )
679
+ return section in skip or not self._is_setuptools_section(section)
680
+
681
+ def _is_setuptools_section(self, section: str) -> bool:
682
+ return (
683
+ section == "metadata"
684
+ or section.startswith("options")
685
+ or section in _setuptools_commands()
686
+ )
687
+
688
+ # FIXME: 'Distribution._set_command_options' is too complex (14)
689
+ def _set_command_options(self, command_obj, option_dict=None): # noqa: C901
690
+ """
691
+ Set the options for 'command_obj' from 'option_dict'. Basically
692
+ this means copying elements of a dictionary ('option_dict') to
693
+ attributes of an instance ('command').
694
+
695
+ 'command_obj' must be a Command instance. If 'option_dict' is not
696
+ supplied, uses the standard option dictionary for this command
697
+ (from 'self.command_options').
698
+
699
+ (Adopted from distutils.dist.Distribution._set_command_options)
700
+ """
701
+ command_name = command_obj.get_command_name()
702
+ if option_dict is None:
703
+ option_dict = self.get_option_dict(command_name)
704
+
705
+ if DEBUG:
706
+ self.announce(f" setting options for '{command_name}' command:")
707
+ for option, (source, value) in option_dict.items():
708
+ if DEBUG:
709
+ self.announce(f" {option} = {value} (from {source})")
710
+ try:
711
+ bool_opts = [translate_longopt(o) for o in command_obj.boolean_options]
712
+ except AttributeError:
713
+ bool_opts = []
714
+ try:
715
+ neg_opt = command_obj.negative_opt
716
+ except AttributeError:
717
+ neg_opt = {}
718
+
719
+ try:
720
+ is_string = isinstance(value, str)
721
+ if option in neg_opt and is_string:
722
+ setattr(command_obj, neg_opt[option], not strtobool(value))
723
+ elif option in bool_opts and is_string:
724
+ setattr(command_obj, option, strtobool(value))
725
+ elif hasattr(command_obj, option):
726
+ setattr(command_obj, option, value)
727
+ else:
728
+ raise DistutilsOptionError(
729
+ f"error in {source}: command '{command_name}' has no such option '{option}'"
730
+ )
731
+ except ValueError as e:
732
+ raise DistutilsOptionError(e) from e
733
+
734
+ def _get_project_config_files(self, filenames: Iterable[StrPath] | None):
735
+ """Add default file and split between INI and TOML"""
736
+ tomlfiles = []
737
+ standard_project_metadata = Path(self.src_root or os.curdir, "pyproject.toml")
738
+ if filenames is not None:
739
+ parts = partition(lambda f: Path(f).suffix == ".toml", filenames)
740
+ filenames = list(parts[0]) # 1st element => predicate is False
741
+ tomlfiles = list(parts[1]) # 2nd element => predicate is True
742
+ elif standard_project_metadata.exists():
743
+ tomlfiles = [standard_project_metadata]
744
+ return filenames, tomlfiles
745
+
746
+ def parse_config_files(
747
+ self,
748
+ filenames: Iterable[StrPath] | None = None,
749
+ ignore_option_errors: bool = False,
750
+ ) -> None:
751
+ """Parses configuration files from various levels
752
+ and loads configuration.
753
+ """
754
+ inifiles, tomlfiles = self._get_project_config_files(filenames)
755
+
756
+ self._parse_config_files(filenames=inifiles)
757
+
758
+ setupcfg.parse_configuration(
759
+ self, self.command_options, ignore_option_errors=ignore_option_errors
760
+ )
761
+ for filename in tomlfiles:
762
+ pyprojecttoml.apply_configuration(self, filename, ignore_option_errors)
763
+
764
+ self._finalize_requires()
765
+ self._finalize_license_expression()
766
+ self._finalize_license_files()
767
+
768
+ def fetch_build_eggs(self, requires: _StrOrIter) -> list[metadata.Distribution]:
769
+ """Resolve pre-setup requirements"""
770
+ from .installer import _fetch_build_eggs
771
+
772
+ return _fetch_build_eggs(self, requires)
773
+
774
+ def finalize_options(self) -> None:
775
+ """
776
+ Allow plugins to apply arbitrary operations to the
777
+ distribution. Each hook may optionally define a 'order'
778
+ to influence the order of execution. Smaller numbers
779
+ go first and the default is 0.
780
+ """
781
+ group = 'setuptools.finalize_distribution_options'
782
+
783
+ def by_order(hook):
784
+ return getattr(hook, 'order', 0)
785
+
786
+ defined = metadata.entry_points(group=group)
787
+ filtered = itertools.filterfalse(self._removed, defined)
788
+ loaded = map(lambda e: e.load(), filtered)
789
+ for ep in sorted(loaded, key=by_order):
790
+ ep(self)
791
+
792
+ @staticmethod
793
+ def _removed(ep):
794
+ """
795
+ When removing an entry point, if metadata is loaded
796
+ from an older version of Setuptools, that removed
797
+ entry point will attempt to be loaded and will fail.
798
+ See #2765 for more details.
799
+ """
800
+ removed = {
801
+ # removed 2021-09-05
802
+ '2to3_doctests',
803
+ }
804
+ return ep.name in removed
805
+
806
+ def _finalize_setup_keywords(self):
807
+ for ep in metadata.entry_points(group='distutils.setup_keywords'):
808
+ value = getattr(self, ep.name, None)
809
+ if value is not None:
810
+ ep.load()(self, ep.name, value)
811
+
812
+ def get_egg_cache_dir(self) -> str:
813
+ from . import windows_support
814
+
815
+ egg_cache_dir = os.path.join(os.curdir, '.eggs')
816
+ if not os.path.exists(egg_cache_dir):
817
+ os.mkdir(egg_cache_dir)
818
+ windows_support.hide_file(egg_cache_dir)
819
+ readme_txt_filename = os.path.join(egg_cache_dir, 'README.txt')
820
+ with open(readme_txt_filename, 'w', encoding="utf-8") as f:
821
+ f.write(
822
+ 'This directory contains eggs that were downloaded '
823
+ 'by setuptools to build, test, and run plug-ins.\n\n'
824
+ )
825
+ f.write(
826
+ 'This directory caches those eggs to prevent '
827
+ 'repeated downloads.\n\n'
828
+ )
829
+ f.write('However, it is safe to delete this directory.\n\n')
830
+
831
+ return egg_cache_dir
832
+
833
+ def fetch_build_egg(self, req):
834
+ """Fetch an egg needed for building"""
835
+ from .installer import fetch_build_egg
836
+
837
+ return fetch_build_egg(self, req)
838
+
839
+ def get_command_class(self, command: str) -> type[distutils.cmd.Command]: # type: ignore[override] # Not doing complex overrides yet
840
+ """Pluggable version of get_command_class()"""
841
+ if command in self.cmdclass:
842
+ return self.cmdclass[command]
843
+
844
+ # Special case bdist_wheel so it's never loaded from "wheel"
845
+ if command == 'bdist_wheel':
846
+ from .command.bdist_wheel import bdist_wheel
847
+
848
+ return bdist_wheel
849
+
850
+ eps = metadata.entry_points(group='distutils.commands', name=command)
851
+ for ep in eps:
852
+ self.cmdclass[command] = cmdclass = ep.load()
853
+ return cmdclass
854
+ else:
855
+ return _Distribution.get_command_class(self, command)
856
+
857
+ def print_commands(self):
858
+ for ep in metadata.entry_points(group='distutils.commands'):
859
+ if ep.name not in self.cmdclass:
860
+ cmdclass = ep.load()
861
+ self.cmdclass[ep.name] = cmdclass
862
+ return _Distribution.print_commands(self)
863
+
864
+ def get_command_list(self):
865
+ for ep in metadata.entry_points(group='distutils.commands'):
866
+ if ep.name not in self.cmdclass:
867
+ cmdclass = ep.load()
868
+ self.cmdclass[ep.name] = cmdclass
869
+ return _Distribution.get_command_list(self)
870
+
871
+ def include(self, **attrs) -> None:
872
+ """Add items to distribution that are named in keyword arguments
873
+
874
+ For example, 'dist.include(py_modules=["x"])' would add 'x' to
875
+ the distribution's 'py_modules' attribute, if it was not already
876
+ there.
877
+
878
+ Currently, this method only supports inclusion for attributes that are
879
+ lists or tuples. If you need to add support for adding to other
880
+ attributes in this or a subclass, you can add an '_include_X' method,
881
+ where 'X' is the name of the attribute. The method will be called with
882
+ the value passed to 'include()'. So, 'dist.include(foo={"bar":"baz"})'
883
+ will try to call 'dist._include_foo({"bar":"baz"})', which can then
884
+ handle whatever special inclusion logic is needed.
885
+ """
886
+ for k, v in attrs.items():
887
+ include = getattr(self, '_include_' + k, None)
888
+ if include:
889
+ include(v)
890
+ else:
891
+ self._include_misc(k, v)
892
+
893
+ def exclude_package(self, package: str) -> None:
894
+ """Remove packages, modules, and extensions in named package"""
895
+
896
+ pfx = package + '.'
897
+ if self.packages:
898
+ self.packages = [
899
+ p for p in self.packages if p != package and not p.startswith(pfx)
900
+ ]
901
+
902
+ if self.py_modules:
903
+ self.py_modules = [
904
+ p for p in self.py_modules if p != package and not p.startswith(pfx)
905
+ ]
906
+
907
+ if self.ext_modules:
908
+ self.ext_modules = [
909
+ p
910
+ for p in self.ext_modules
911
+ if p.name != package and not p.name.startswith(pfx)
912
+ ]
913
+
914
+ def has_contents_for(self, package: str) -> bool:
915
+ """Return true if 'exclude_package(package)' would do something"""
916
+
917
+ pfx = package + '.'
918
+
919
+ for p in self.iter_distribution_names():
920
+ if p == package or p.startswith(pfx):
921
+ return True
922
+
923
+ return False
924
+
925
+ def _exclude_misc(self, name: str, value: _Sequence) -> None:
926
+ """Handle 'exclude()' for list/tuple attrs without a special handler"""
927
+ if not isinstance(value, _sequence):
928
+ raise DistutilsSetupError(
929
+ f"{name}: setting must be of type <{_sequence_type_repr}> (got {value!r})"
930
+ )
931
+ try:
932
+ old = getattr(self, name)
933
+ except AttributeError as e:
934
+ raise DistutilsSetupError(f"{name}: No such distribution setting") from e
935
+ if old is not None and not isinstance(old, _sequence):
936
+ raise DistutilsSetupError(
937
+ name + ": this setting cannot be changed via include/exclude"
938
+ )
939
+ elif old:
940
+ setattr(self, name, [item for item in old if item not in value])
941
+
942
+ def _include_misc(self, name: str, value: _Sequence) -> None:
943
+ """Handle 'include()' for list/tuple attrs without a special handler"""
944
+
945
+ if not isinstance(value, _sequence):
946
+ raise DistutilsSetupError(
947
+ f"{name}: setting must be of type <{_sequence_type_repr}> (got {value!r})"
948
+ )
949
+ try:
950
+ old = getattr(self, name)
951
+ except AttributeError as e:
952
+ raise DistutilsSetupError(f"{name}: No such distribution setting") from e
953
+ if old is None:
954
+ setattr(self, name, value)
955
+ elif not isinstance(old, _sequence):
956
+ raise DistutilsSetupError(
957
+ name + ": this setting cannot be changed via include/exclude"
958
+ )
959
+ else:
960
+ new = [item for item in value if item not in old]
961
+ setattr(self, name, list(old) + new)
962
+
963
+ def exclude(self, **attrs) -> None:
964
+ """Remove items from distribution that are named in keyword arguments
965
+
966
+ For example, 'dist.exclude(py_modules=["x"])' would remove 'x' from
967
+ the distribution's 'py_modules' attribute. Excluding packages uses
968
+ the 'exclude_package()' method, so all of the package's contained
969
+ packages, modules, and extensions are also excluded.
970
+
971
+ Currently, this method only supports exclusion from attributes that are
972
+ lists or tuples. If you need to add support for excluding from other
973
+ attributes in this or a subclass, you can add an '_exclude_X' method,
974
+ where 'X' is the name of the attribute. The method will be called with
975
+ the value passed to 'exclude()'. So, 'dist.exclude(foo={"bar":"baz"})'
976
+ will try to call 'dist._exclude_foo({"bar":"baz"})', which can then
977
+ handle whatever special exclusion logic is needed.
978
+ """
979
+ for k, v in attrs.items():
980
+ exclude = getattr(self, '_exclude_' + k, None)
981
+ if exclude:
982
+ exclude(v)
983
+ else:
984
+ self._exclude_misc(k, v)
985
+
986
+ def _exclude_packages(self, packages: _Sequence) -> None:
987
+ if not isinstance(packages, _sequence):
988
+ raise DistutilsSetupError(
989
+ f"packages: setting must be of type <{_sequence_type_repr}> (got {packages!r})"
990
+ )
991
+ list(map(self.exclude_package, packages))
992
+
993
+ def _parse_command_opts(self, parser, args):
994
+ # Remove --with-X/--without-X options when processing command args
995
+ self.global_options = self.__class__.global_options
996
+ self.negative_opt = self.__class__.negative_opt
997
+
998
+ # First, expand any aliases
999
+ command = args[0]
1000
+ aliases = self.get_option_dict('aliases')
1001
+ while command in aliases:
1002
+ _src, alias = aliases[command]
1003
+ del aliases[command] # ensure each alias can expand only once!
1004
+ import shlex
1005
+
1006
+ args[:1] = shlex.split(alias, True)
1007
+ command = args[0]
1008
+
1009
+ nargs = _Distribution._parse_command_opts(self, parser, args)
1010
+
1011
+ # Handle commands that want to consume all remaining arguments
1012
+ cmd_class = self.get_command_class(command)
1013
+ if getattr(cmd_class, 'command_consumes_arguments', None):
1014
+ self.get_option_dict(command)['args'] = ("command line", nargs)
1015
+ if nargs is not None:
1016
+ return []
1017
+
1018
+ return nargs
1019
+
1020
+ def get_cmdline_options(self) -> dict[str, dict[str, str | None]]:
1021
+ """Return a '{cmd: {opt:val}}' map of all command-line options
1022
+
1023
+ Option names are all long, but do not include the leading '--', and
1024
+ contain dashes rather than underscores. If the option doesn't take
1025
+ an argument (e.g. '--quiet'), the 'val' is 'None'.
1026
+
1027
+ Note that options provided by config files are intentionally excluded.
1028
+ """
1029
+
1030
+ d: dict[str, dict[str, str | None]] = {}
1031
+
1032
+ for cmd, opts in self.command_options.items():
1033
+ val: str | None
1034
+ for opt, (src, val) in opts.items():
1035
+ if src != "command line":
1036
+ continue
1037
+
1038
+ opt = opt.replace('_', '-')
1039
+
1040
+ if val == 0:
1041
+ cmdobj = self.get_command_obj(cmd)
1042
+ neg_opt = self.negative_opt.copy()
1043
+ neg_opt.update(getattr(cmdobj, 'negative_opt', {}))
1044
+ for neg, pos in neg_opt.items():
1045
+ if pos == opt:
1046
+ opt = neg
1047
+ val = None
1048
+ break
1049
+ else:
1050
+ raise AssertionError("Shouldn't be able to get here")
1051
+
1052
+ elif val == 1:
1053
+ val = None
1054
+
1055
+ d.setdefault(cmd, {})[opt] = val
1056
+
1057
+ return d
1058
+
1059
+ def iter_distribution_names(self) -> Iterator[str]:
1060
+ """Yield all packages, modules, and extension names in distribution"""
1061
+
1062
+ yield from self.packages or ()
1063
+
1064
+ yield from self.py_modules or ()
1065
+
1066
+ for ext in self.ext_modules or ():
1067
+ if isinstance(ext, tuple):
1068
+ name, _buildinfo = ext
1069
+ else:
1070
+ name = ext.name
1071
+ name = name.removesuffix('module')
1072
+ yield name
1073
+
1074
+ def handle_display_options(self, option_order):
1075
+ """If there were any non-global "display-only" options
1076
+ (--help-commands or the metadata display options) on the command
1077
+ line, display the requested info and return true; else return
1078
+ false.
1079
+ """
1080
+ import sys
1081
+
1082
+ if self.help_commands:
1083
+ return _Distribution.handle_display_options(self, option_order)
1084
+
1085
+ # Stdout may be StringIO (e.g. in tests)
1086
+ if not isinstance(sys.stdout, io.TextIOWrapper):
1087
+ return _Distribution.handle_display_options(self, option_order)
1088
+
1089
+ # Don't wrap stdout if utf-8 is already the encoding. Provides
1090
+ # workaround for #334.
1091
+ if sys.stdout.encoding.lower() in ('utf-8', 'utf8'):
1092
+ return _Distribution.handle_display_options(self, option_order)
1093
+
1094
+ # Print metadata in UTF-8 no matter the platform
1095
+ encoding = sys.stdout.encoding
1096
+ sys.stdout.reconfigure(encoding='utf-8')
1097
+ try:
1098
+ return _Distribution.handle_display_options(self, option_order)
1099
+ finally:
1100
+ sys.stdout.reconfigure(encoding=encoding)
1101
+
1102
+ def run_command(self, command) -> None:
1103
+ self.set_defaults()
1104
+ # Postpone defaults until all explicit configuration is considered
1105
+ # (setup() args, config files, command line and plugins)
1106
+
1107
+ super().run_command(command)
1108
+
1109
+
1110
+ @functools.cache
1111
+ def _setuptools_commands() -> set[str]:
1112
+ try:
1113
+ # Use older API for importlib.metadata compatibility
1114
+ entry_points = metadata.distribution('setuptools').entry_points
1115
+ eps: Iterable[str] = (ep.name for ep in entry_points)
1116
+ except metadata.PackageNotFoundError:
1117
+ # during bootstrapping, distribution doesn't exist
1118
+ eps = []
1119
+ return {*distutils.command.__all__, *eps}
1120
+
1121
+
1122
+ class DistDeprecationWarning(SetuptoolsDeprecationWarning):
1123
+ """Class for warning about deprecations in dist in
1124
+ setuptools. Not ignored by default, unlike DeprecationWarning."""
data/diffusion/.venv/lib/python3.11/site-packages/setuptools/glob.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Filename globbing utility. Mostly a copy of `glob` from Python 3.5.
3
+
4
+ Changes include:
5
+ * `yield from` and PEP3102 `*` removed.
6
+ * Hidden files are not ignored.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import fnmatch
12
+ import os
13
+ import re
14
+ from collections.abc import Iterable, Iterator
15
+ from typing import TYPE_CHECKING, AnyStr, overload
16
+
17
+ if TYPE_CHECKING:
18
+ from _typeshed import BytesPath, StrOrBytesPath, StrPath
19
+
20
+ __all__ = ["glob", "iglob", "escape"]
21
+
22
+
23
+ def glob(pathname: AnyStr, recursive: bool = False) -> list[AnyStr]:
24
+ """Return a list of paths matching a pathname pattern.
25
+
26
+ The pattern may contain simple shell-style wildcards a la
27
+ fnmatch. However, unlike fnmatch, filenames starting with a
28
+ dot are special cases that are not matched by '*' and '?'
29
+ patterns.
30
+
31
+ If recursive is true, the pattern '**' will match any files and
32
+ zero or more directories and subdirectories.
33
+ """
34
+ return list(iglob(pathname, recursive=recursive))
35
+
36
+
37
+ def iglob(pathname: AnyStr, recursive: bool = False) -> Iterator[AnyStr]:
38
+ """Return an iterator which yields the paths matching a pathname pattern.
39
+
40
+ The pattern may contain simple shell-style wildcards a la
41
+ fnmatch. However, unlike fnmatch, filenames starting with a
42
+ dot are special cases that are not matched by '*' and '?'
43
+ patterns.
44
+
45
+ If recursive is true, the pattern '**' will match any files and
46
+ zero or more directories and subdirectories.
47
+ """
48
+ it = _iglob(pathname, recursive)
49
+ if recursive and _isrecursive(pathname):
50
+ s = next(it) # skip empty string
51
+ assert not s
52
+ return it
53
+
54
+
55
+ def _iglob(pathname: AnyStr, recursive: bool) -> Iterator[AnyStr]:
56
+ dirname, basename = os.path.split(pathname)
57
+ glob_in_dir = glob2 if recursive and _isrecursive(basename) else glob1
58
+
59
+ if not has_magic(pathname):
60
+ if basename:
61
+ if os.path.lexists(pathname):
62
+ yield pathname
63
+ else:
64
+ # Patterns ending with a slash should match only directories
65
+ if os.path.isdir(dirname):
66
+ yield pathname
67
+ return
68
+
69
+ if not dirname:
70
+ yield from glob_in_dir(dirname, basename)
71
+ return
72
+ # `os.path.split()` returns the argument itself as a dirname if it is a
73
+ # drive or UNC path. Prevent an infinite recursion if a drive or UNC path
74
+ # contains magic characters (i.e. r'\\?\C:').
75
+ if dirname != pathname and has_magic(dirname):
76
+ dirs: Iterable[AnyStr] = _iglob(dirname, recursive)
77
+ else:
78
+ dirs = [dirname]
79
+ if not has_magic(basename):
80
+ glob_in_dir = glob0
81
+ for dirname in dirs:
82
+ for name in glob_in_dir(dirname, basename):
83
+ yield os.path.join(dirname, name)
84
+
85
+
86
+ # These 2 helper functions non-recursively glob inside a literal directory.
87
+ # They return a list of basenames. `glob1` accepts a pattern while `glob0`
88
+ # takes a literal basename (so it only has to check for its existence).
89
+
90
+
91
+ @overload
92
+ def glob1(dirname: StrPath, pattern: str) -> list[str]: ...
93
+ @overload
94
+ def glob1(dirname: BytesPath, pattern: bytes) -> list[bytes]: ...
95
+ def glob1(dirname: StrOrBytesPath, pattern: str | bytes) -> list[str] | list[bytes]:
96
+ if not dirname:
97
+ if isinstance(pattern, bytes):
98
+ dirname = os.curdir.encode('ASCII')
99
+ else:
100
+ dirname = os.curdir
101
+ try:
102
+ names = os.listdir(dirname)
103
+ except OSError:
104
+ return []
105
+ # mypy false-positives: str or bytes type possibility is always kept in sync
106
+ return fnmatch.filter(names, pattern) # type: ignore[type-var, return-value]
107
+
108
+
109
+ def glob0(dirname, basename):
110
+ if not basename:
111
+ # `os.path.split()` returns an empty basename for paths ending with a
112
+ # directory separator. 'q*x/' should match only directories.
113
+ if os.path.isdir(dirname):
114
+ return [basename]
115
+ else:
116
+ if os.path.lexists(os.path.join(dirname, basename)):
117
+ return [basename]
118
+ return []
119
+
120
+
121
+ # This helper function recursively yields relative pathnames inside a literal
122
+ # directory.
123
+
124
+
125
+ @overload
126
+ def glob2(dirname: StrPath, pattern: str) -> Iterator[str]: ...
127
+ @overload
128
+ def glob2(dirname: BytesPath, pattern: bytes) -> Iterator[bytes]: ...
129
+ def glob2(dirname: StrOrBytesPath, pattern: str | bytes) -> Iterator[str | bytes]:
130
+ assert _isrecursive(pattern)
131
+ yield pattern[:0]
132
+ yield from _rlistdir(dirname)
133
+
134
+
135
+ # Recursively yields relative pathnames inside a literal directory.
136
+ @overload
137
+ def _rlistdir(dirname: StrPath) -> Iterator[str]: ...
138
+ @overload
139
+ def _rlistdir(dirname: BytesPath) -> Iterator[bytes]: ...
140
+ def _rlistdir(dirname: StrOrBytesPath) -> Iterator[str | bytes]:
141
+ if not dirname:
142
+ if isinstance(dirname, bytes):
143
+ dirname = os.curdir.encode('ASCII')
144
+ else:
145
+ dirname = os.curdir
146
+ try:
147
+ names = os.listdir(dirname)
148
+ except OSError:
149
+ return
150
+ for x in names:
151
+ yield x
152
+ # mypy false-positives: str or bytes type possibility is always kept in sync
153
+ path = os.path.join(dirname, x) if dirname else x # type: ignore[arg-type]
154
+ for y in _rlistdir(path):
155
+ yield os.path.join(x, y) # type: ignore[arg-type]
156
+
157
+
158
+ magic_check = re.compile('([*?[])')
159
+ magic_check_bytes = re.compile(b'([*?[])')
160
+
161
+
162
+ def has_magic(s: str | bytes) -> bool:
163
+ if isinstance(s, bytes):
164
+ return magic_check_bytes.search(s) is not None
165
+ else:
166
+ return magic_check.search(s) is not None
167
+
168
+
169
+ def _isrecursive(pattern: str | bytes) -> bool:
170
+ if isinstance(pattern, bytes):
171
+ return pattern == b'**'
172
+ else:
173
+ return pattern == '**'
174
+
175
+
176
+ def escape(pathname):
177
+ """Escape all special characters."""
178
+ # Escaping is done by wrapping any of "*?[" between square brackets.
179
+ # Metacharacters do not work in the drive part and shouldn't be escaped.
180
+ drive, pathname = os.path.splitdrive(pathname)
181
+ if isinstance(pathname, bytes):
182
+ pathname = magic_check_bytes.sub(rb'[\1]', pathname)
183
+ else:
184
+ pathname = magic_check.sub(r'[\1]', pathname)
185
+ return drive + pathname
data/diffusion/.venv/lib/python3.11/site-packages/setuptools/gui-32.exe ADDED
Binary file (11.8 kB). View file
 
data/diffusion/.venv/lib/python3.11/site-packages/setuptools/gui-64.exe ADDED
Binary file (14.3 kB). View file